Swift core

29
Swift Core Mercari Inc. @kitasuke

Transcript of Swift core

Page 1: Swift core

Swift CoreMercari Inc.@kitasuke

Page 2: Swift core
Page 3: Swift core

Swift Libraries• swiftAST• swiftLLVMParses• swiftSIL• swiftRuntime• swiftCore• swiftDarwin• swiftFoundation• etc.

Page 4: Swift core

DocumentationSphinx documentation generator toolCompiles .rst into HTML

• easy_install -U Sphinx

• make

In case make command fails...

export LC_ALL=en_US.UTF-8export LANG=en_US.UTF-8source $HOME/.bash_profile

Page 5: Swift core

Arrays.html

Page 6: Swift core

weak.htmlLanguage and Library Precedents

• Objective-C• C++• Java• .NET• Python• Ruby• Rust• Haskell

Page 7: Swift core

SIL.html• Abstract• Syntax• Dataflow Errors• Runtime Failure• Undefined Behavior• Calling Convention• Type Based Alias Analysis• Value Dependence• Instruction Set

Page 8: Swift core

Instalattiongit clone [email protected]:apple/swift.gitcd swift./utils/update-checkout --clone-with-ssh

git clone [email protected]:ninja-build/ninja.git

Page 9: Swift core

Developing Swift in Xcodeutils/build-script -X --skip-build -- --reconfigure

cd build/Xcode-DebugAssert/swift-macosx-x86_64open Swift.xcodeproj

Page 10: Swift core

Must-see files• Attr.def• Builtin.def• CFDatabase.def• MappedTypes.def

Page 11: Swift core

Attr.def• TYPE_ATTR(noreturn)

• SIMPLE_DECL_ATTR(final, Final, OnClass | OnFunc | OnVar | OnSubscript|DeclModifier, 2)

• DECL_ATTR(objc, ObjC, OnFunc | OnClass | OnProtocol | OnVar | OnSubscript | OnConstructor | OnDestructor | OnEnum | OnEnumElement, 3)

Page 12: Swift core

@_silgen_nameBridgeObjectiveC.swift/// Convert `x` from its Objective-C representation to its Swift/// representation.@warn_unused_result@_silgen_name("_forceBridgeFromObjectiveC_bridgeable")public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(x: T._ObjectiveCType, _: T.Type) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result!}

Page 13: Swift core

@inlineBuiltin.swift@inline(__always)@warn_unused_resultpublic func unsafeUnwrap<T>(nonEmpty: T?) -> T { if let x = nonEmpty { return x } _debugPreconditionFailure("unsafeUnwrap of nil optional")}

Page 14: Swift core

@_semanticsFoundation.swift@_semantics("convertToObjectiveC")public func _bridgeToObjectiveC() -> NSString { // This method should not do anything extra except calling into the // implementation inside core. (These two entry points should be // equivalent.) return unsafeBitCast(_bridgeToObjectiveCImpl(), NSString.self)}

Page 15: Swift core

@_transparentBuiltin.swift@_transparent@warn_unused_resultpublic func unsafeBitCast<T, U>(x: T, _: U.Type) -> U { _precondition(sizeof(T.self) == sizeof(U.self), "can't unsafeBitCast between types of different sizes") return Builtin.reinterpretCast(x)}

Page 16: Swift core

@effectsString.swift@warn_unused_result@effects(readonly)@_semantics("string.concat")public func + (lhs: String, rhs: String) -> String { var lhs = lhs if (lhs.isEmpty) { return rhs } lhs._core.append(rhs._core) return lhs}

Page 17: Swift core

Builtin.def• BUILTINSILOPERATION(CastToUnknownObject,

"castToUnknownObject", Special)• BUILTINSILOPERATION(CastFromUnknownObject,

"castFromUnknownObject", Special)• BUILTINSILOPERATION(CastToNativeObject,

"castToNativeObject", Special)• BUILTINSILOPERATION(CastFromNativeObject,

"castFromNativeObject", Special)

Page 18: Swift core

CFDatabase.def• CF_TYPE(ABAddressBookRef)• CF_TYPE(CFAllocatorRef)• CF_TYPE(CGColorRef)• CF_TYPE(CTFontCollectionRef)• NONCFTYPE(JSClassRef)

Page 19: Swift core

MappedTypes.def• MAPSTDLIBTYPE("UInt8", UnsignedInt, 8, "UInt8",

false, DoNothing)• MAPSTDLIBTYPE("size_t", UnsignedWord, 0, "Int",

false, DefineOnly)• MAP_TYPE("BOOL", ObjCBool, 8, "ObjectiveC",

"ObjCBool", false, DoNothing)• MAPSTDLIBTYPE("Class", ObjCClass, 0, "AnyClass",

false, DoNothing)

Page 20: Swift core

Swift Core• Algorithm.swift• Assert.swift• Bool.swift• BridgeObjectiveC.swift• Builtin.swift• CocoaArray.swift• etc.

Page 21: Swift core

public func min<T : Comparable>(x: T, _ y: T) -> T

/// Returns the lesser of `x` and `y`.////// If `x == y`, returns `x`.@warn_unused_resultpublic func min<T : Comparable>(x: T, _ y: T) -> T { // In case `x == y` we pick `x`. // This preserves any pre-existing order in case `T` has identity, // which is important for e.g. the stability of sorting algorithms. // `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`. return y < x ? y : x}

Page 22: Swift core

public struct Bool

/// A value type whose instances are either `true` or `false`.public struct Bool { internal var _value: Builtin.Int1

/// Default-initialize Boolean value to `false`. @_transparent public init() { let zero: Int8 = 0 self._value = Builtin.trunc_Int8_Int1(zero._value) }

@_transparent internal init(_ v: Builtin.Int1) { self._value = v }}

Page 23: Swift core

public func _bridgeToObjectiveC<T>(x: T) -> AnyObject?/// Attempt to convert `x` to its Objective-C representation.////// - If `T` is a class type, it is always bridged verbatim, the function/// returns `x`;////// - otherwise, `T` conforms to `_ObjectiveCBridgeable`:/// + if `T._isBridgedToObjectiveC()` returns `false`, then the/// result is empty;/// + otherwise, returns the result of `x._bridgeToObjectiveC()`;////// - otherwise, the result is empty.@warn_unused_resultpublic func _bridgeToObjectiveC<T>(x: T) -> AnyObject? { if _fastPath(_isClassOrObjCExistential(T.self)) { return unsafeBitCast(x, AnyObject.self) } return _bridgeNonVerbatimToObjectiveC(x)}

Page 24: Swift core

public prefix func ++ <T : _Incrementable> (inout i: T) -> T/// Replace `i` with its `successor()` and return the updated value of/// `i`.@_transparent@available(*, deprecated, message="it will be removed in Swift 3")public prefix func ++ <T : _Incrementable> (inout i: T) -> T { i._successorInPlace() return i}

Page 25: Swift core

public func == <T: Equatable> (lhs: T?, rhs: T?) -> Bool@warn_unused_resultpublic func == <T: Equatable> (lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l == r case (nil, nil): return true default: return false }}

Page 26: Swift core

public func map<T>(@noescape transform: (Generator.Element) throws -> T) rethrows -> [T]@warn_unused_resultpublic func map<T>( @noescape transform: (Generator.Element) throws -> T) rethrows -> [T] { let initialCapacity = underestimateCount() var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity)

var generator = generate()

// Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(generator.next()!)) } // Add remaining elements, if any. while let element = generator.next() { result.append(try transform(element)) } return Array(result)}

Page 27: Swift core

public func forEach(@noescape body: (Generator.Element) throws -> Void) rethrowspublic func forEach( @noescape body: (Generator.Element) throws -> Void) rethrows { for element in self { try body(element) }}

Page 28: Swift core

Contributing to Swift• fatalError("not implemented")• FIXME

Page 29: Swift core

.gyb filesAny editors for .gyb files?