diff --git a/.dir-locals.el b/.dir-locals.el
index bd65e5345441f..feea22ea295c1 100644
--- a/.dir-locals.el
+++ b/.dir-locals.el
@@ -2,7 +2,7 @@
;
; This source file is part of the Swift.org open source project
;
-; Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+; Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
; Licensed under Apache License v2.0 with Runtime Library Exception
;
; See http://swift.org/LICENSE.txt for license information
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000000000..46ccb95c0fde1
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,5342 @@
+Latest
+------
+
+* The ++ and -- operators have been deprecated, and are slated to be removed in
+ Swift 3.0. As a replacement, please use "x += 1" on integer or floating point
+ types, and "x = x.successor()" on Index types.
+
+* The operator identifier lexer grammar has been revised to simplify the rules
+ for operators that start with a dot ("."). The new rule is that an operator
+ that starts with a dot may contain other dots in it, but operators that start
+ with some other character may not contain dots. For example:
+
+ ```
+ x....foo --> "x" "...." "foo"
+ x&%^.foo --> "x" "&%^" ".foo"
+ ```
+
+ This eliminates a special case for the ..< operator, folding it into a simple
+ and consistent rule.
+
+* The "C-style for loop", which is spelled `for init; comparison; increment {}`
+ has been deprecated and is slated for removal in Swift 3.0. See
+ [SE-0007](https://github.com/apple/swift-evolution/blob/master/proposals/0007-remove-c-style-for-loops.md)
+ for more information.
+
+* Three new doc comment fields, namely `- keyword:`, `- recommended:`
+ and `- recommendedover:`, allow Swift users to cooperate with code
+ completion engine to deliver more effective code completion results.
+ The `- keyword:` field specifies concepts that are not fully manifested in
+ declaration names. `- recommended:` indicates other declarations are preferred
+ to the one decorated; to the contrary, `- recommendedover:` indicates
+ the decorated declaration is preferred to those declarations whose names
+ are specified.
+
+* Designated class initializers declared as failable or throwing may now
+ return nil or throw an error, respectively, before the object has been
+ fully initialized. For example:
+
+ ```swift
+ class Widget : Gadget {
+ let complexity: Int
+
+ init(complexity: Int, elegance: Int) throws {
+ if complexity > 3 { throw WidgetError.TooComplex }
+ self.complexity = complexity
+
+ try super.init(elegance: elegance)
+ }
+ }
+ ```
+
+* All slice types now have `removeFirst()` and `removeLast()` methods.
+
+* `ArraySlice.removeFirst()` now preserves element indices.
+
+* Global `anyGenerator()` functions have been changed into initializers on
+ `AnyGenerator`, making the API more intuitive and idiomatic. They have been
+ deprecated in Swift 2.2, and will be removed in Swift 3.
+
+* Closures appearing inside generic types and generic methods can now be
+ converted to C function pointers as long as no generic type parameters
+ are referenced in the closure's argument list or body. A conversion of
+ a closure that references generic type parameters now produces a
+ diagnostic instead of crashing.
+
+ **(rdar://problem/22204968)**
+
+* Anonymously-typed members of C structs and unions can now be accessed
+ from Swift. For example, given the following struct 'Pie', the 'crust'
+ and 'filling' members are now imported:
+
+ ```swift
+ struct Pie {
+ struct { bool crispy; } crust;
+ union { int fruit; } filling;
+ }
+ ```
+
+ Since Swift does not support anonymous structs, these fields are
+ imported as properties named `crust` and `filling` having nested types
+ named `Pie.__Unnamed_crust` and `Pie.__Unnamed_filling`.
+
+ **(rdar://problem/21683348)**
+
+* Argument labels and parameter names can now be any keyword except
+ `var`, `let`, or `inout`. For example:
+
+ NSURLProtectionSpace(host: "somedomain.com", port: 443, protocol: "https", realm: "Some Domain", authenticationMethod: "Basic")
+
+ would previously have required `protocol` to be surrounded in
+ back-ticks. For more information, see
+ [SE-0001](https://github.com/apple/swift-evolution/blob/master/proposals/0001-keywords-as-argument-labels.md).
+
+* Tuples (up to arity 6) whose elements are all `Comparable` or `Equatable` now
+ implement the full set of comparison/equality operators. The comparison
+ operators are defined in terms of [lexicographical order][]. See [SE-0015][]
+ for more information.
+
+[lexicographical order]: https://en.wikipedia.org/wiki/Lexicographical_order
+[SE-0015]: https://github.com/apple/swift-evolution/blob/master/proposals/0015-tuple-comparison-operators.md
+
+* The `@objc(SomeName)` attribute is now supported on enums and enum cases to
+ rename the generated Objective-C declaration.
+
+ **(rdar://problem/21930334)**
+
+2015-09-17 [Xcode 7.1, Swift 2.1]
+----------
+
+* Enums imported from C now automatically conform to the `Equatable` protocol,
+ including a default implementation of the `==` operator. This conformance
+ allows you to use C enum pattern matching in switch statements with no
+ additional code. **(17287720)**
+
+* The `NSNumber.unsignedIntegerValue` property now has the type `UInt` instead
+ of `Int`, as do other methods and properties that use the `NSUInteger` type
+ in Objective-C and whose names contain `unsigned..`. Most other uses of
+ `NSUInteger` in system frameworks are imported as `Int` as they were in
+ Xcode 7. **(19134055)**
+
+* Field getters and setters are now created for named unions imported from C.
+ In addition, an initializer with a named parameter for the field is provided.
+ For example, given the following Objective-C `typedef`:
+
+ ```objc
+ typedef union IntOrFloat {
+ int intField;
+ float floatField;
+ } IntOrFloat;
+ ```
+
+ Importing this `typedef` into Swift generates the following interface:
+
+ ```swift
+ struct IntOrFloat {
+ var intField: Int { get set }
+ init(intField: Int)
+
+ var floatField: Float { get set }
+ init(floatField: Float)
+ }
+ ```
+
+ **(19660119)**
+
+* Bitfield members of C structs are now imported into Swift. **(21702107)**
+
+* The type `dispatch_block_t` now refers to the type
+ `@convention(block) () -> Void`, as it did in Swift 1.2.
+ This change allows programs using `dispatch_block_create` to work as expected,
+ solving an issue that surfaced in Xcode 7.0 with Swift 2.0.
+
+ **Note:** Converting to a Swift closure value and back is not guaranteed to
+ preserve the identity of a `dispatch_block_t`.
+ **(22432170)**
+
+* Editing a file does not trigger a recompile of files that depend upon it if
+ the edits only modify declarations marked private. **(22239821)**
+
+* Expressions interpolated in strings may now contain string literals.
+ For example, `My name is \(attributes["name"]!)` is now a valid expression.
+ **(14050788)**
+
+* Error messages produced when the type checker cannot solve its constraint
+ system continue to improve in many cases.
+
+ For example, errors in the body of generic closures (for instance, the
+ argument closure to `map`) are much more usefully diagnosed. **(18835890)**
+
+* Conversions between function types are supported, exhibiting covariance in
+ function result types and contravariance in function parameter types.
+ For example, it is legal to assign a function of type `Any -> Int` to a
+ variable of type `String -> Any`. **(19517003)**
+
+
+2015-09-17 [Xcode 7.0, Swift 2]
+----------
+
+## Swift Language Features
+
+* New `defer` statement. This statement runs cleanup code when the scope is
+ exited, which is particularly useful in conjunction with the new error
+ handling model. For example:
+
+ ```swift
+ func xyz() throws {
+ let f = fopen("x.txt", "r")
+ defer { fclose(f) }
+ try foo(f) // f is closed if an error is propagated.
+ let f2 = fopen("y.txt", "r")
+ defer { fclose(f2) }
+ try bar(f, f2) // f2 is closed, then f is closed if an error is propagated.
+ } // f2 is closed, then f is closed on a normal path
+ ```
+
+ **(17302850)**
+
+* Printing values of certain `enum` types shows the enum `case` and payload, if
+ any. This is not supported for `@objc` enums or certain enums with multiple
+ payloads. **(18334936)**
+
+* You can specify availability information on your own declarations with the
+ `@available()` attribute.
+
+ For example:
+
+ ```swift
+ @available(iOS 8.0, OSX 10.10, *)
+ func startUserActivity() -> NSUserActivity {
+ ...
+ }
+ ```
+
+ This code fragment indicates that the `startUserActivity()` method is
+ available on iOS 8.0+, on OS X v10.10+, and on all versions of any other
+ platform. **(20938565)**
+
+* A new `@nonobjc` attribute is introduced to selectively suppress ObjC export
+ for instance members that would otherwise be `@objc`. **(16763754)**
+
+* Nongeneric classes may now inherit from generic classes. **(15520519)**
+
+* Public extensions of generic types are now permitted.
+
+ ```swift
+ public extension Array { … }
+ ```
+
+ **(16974298)**
+
+* Enums now support multiple generic associated values, for example:
+
+ ```swift
+ enum Either {
+ case Left(T), Right(U)
+ }
+ ```
+
+ **(15666173)**
+
+* **Protocol extensions**: Extensions can be written for protocol types.
+ With these extensions, methods and properties can be added to any type that
+ conforms to a particular protocol, allowing you to reuse more of your code.
+ This leads to more natural caller side "dot" method syntax that follows the
+ principle of "fluent interfaces" and that makes the definition of generic
+ code simpler (reducing "angle bracket blindness"). **(11735843)**
+
+* **Protocol default implementations**: Protocols can have default
+ implementations for requirements specified in a protocol extension, allowing
+ "mixin" or "trait" like patterns.
+
+* **Availability checking**. Swift reports an error at compile time if you call an
+ API that was introduced in a version of the operating system newer than the
+ currently selected deployment target.
+
+ To check whether a potentially unavailable API is available at runtime, use
+ the new `#available()` condition in an if or guard statement. For example:
+
+ ```swift
+ if #available(iOS 8.0, OSX 10.10, *) {
+ // Use Handoff APIs when available.
+ let activity =
+ NSUserActivity(activityType:"com.example.ShoppingList.view")
+ activity.becomeCurrent()
+ } else {
+ // Fall back when Handoff APIs not available.
+ }
+ ```
+
+ **(14586648)**
+
+* Native support for C function pointers: C functions that take function pointer
+ arguments can be called using closures or global functions, with the
+ restriction that the closure must not capture any of its local context.
+ For example, the standard C qsort function can be invoked as follows:
+
+ ```swift
+ var array = [3, 14, 15, 9, 2, 6, 5]
+ qsort(&array, array.count, sizeofValue(array[0])) { a, b in
+ return Int32(UnsafePointer(a).memory - UnsafePointer(b).memory)
+ }
+ print(array)
+ ```
+
+ **(16339559)**
+
+* **Error handling**. You can create functions that `throw`, `catch`, and manage
+ errors in Swift.
+
+ Using this capability, you can surface and deal with recoverable
+ errors, such as "file-not-found" or network timeouts. Swift's error handling
+ interoperates with `NSError`. **(17158652)**
+
+* **Testability**: Tests of Swift 2.0 frameworks and apps are written without
+ having to make internal routines public.
+
+ Use `@testable import {ModuleName}` in your test source code to make all
+ public and internal routines usable. The app or framework target needs to be
+ compiled with the `Enable Testability` build setting set to `Yes`. The `Enable
+ Testability` build setting should be used only in your Debug configuration,
+ because it prohibits optimizations that depend on not exporting internal
+ symbols from the app or framework. **(17732115)**
+
+* if statements can be labeled, and labeled break statements can be used as a
+ jump out of the matching if statement.
+
+ An unlabeled break does not exit the if statement. It exits the enclosing
+ loop or switch statement, or it is illegal if none exists. (19150249)
+
+* A new `x?` pattern can be used to pattern match against optionals as a
+ synonym for `.Some(x)`. **(19382878)**
+
+* Concatenation of Swift string literals, including across multiple lines, is
+ now a guaranteed compile-time optimization, even at `-Onone`. **(19125926)**
+
+* Nested functions can now recursively reference themselves and other nested
+ functions. **(11266246)**
+
+* Improved diagnostics:
+ - A warning has been introduced to encourage the use of let instead of var
+ when appropriate.
+ - A warning has been introduced to signal unused variables.
+ - Invalid mutation diagnostics are more precise.
+ - Unreachable switch cases cause a warning.
+ - The switch statement "exhaustiveness checker" is smarter.
+ **(15975935,20130240)**
+
+* Failable convenience initializers are allowed to return `nil` before calling
+ `self.init`.
+
+ Designated initializers still must initialize all stored properties before
+ returning `nil`; this is a known limitation. **(20193929)**
+
+* A new `readLine()` function has been added to the standard library.
+ **(15911365)**
+
+* **SIMD Support**: Clang extended vectors are imported and usable in Swift.
+
+ This capability enables many graphics and other low-level numeric APIs
+ (for example, `simd.h`) to be usable in Swift.
+
+* New `guard` statement: This statement allows you to model an early exit out
+ of a scope.
+
+ For example:
+
+ ```swift
+ guard let z = bar() else { return }
+ use(z)
+ ```
+
+ The `else` block is required to exit the scope (for example, with `return`,
+ `throw`, `break`, `continue`, and so forth) or end in a call to a `@noreturn`
+ function. **(20109722)**
+
+* Improved pattern matching: `switch`/`case` pattern matching is available to
+ many new conditional control flow statements, including `if`/`case`,
+ `while`/`case`, `guard`/`case`, and `for-in`/`case`. `for-in` statements can
+ also have `where` clauses, which combine to support many of the features of
+ list comprehensions in other languages.
+
+* A new `do` statement allows scopes to be introduced with the `do` statement.
+
+ For example:
+
+ ```swift
+ do {
+ //new scope
+ do {
+ //another scope
+ }
+ }
+ ```
+
+## Swift Enhancements and Changes
+
+* A new keyword `try?` has been added to Swift.
+
+ `try?` attempts to perform an operation that may throw. If the operation
+ succeeds, the result is wrapped in an optional; if it fails (that is, if an
+ error is thrown), the result is `nil` and the error is discarded.
+
+ For example:
+
+ ```swift
+ func produceGizmoUsingTechnology() throws -> Gizmo { … }
+ func produceGizmoUsingMagic() throws -> Gizmo { … }
+
+ if let result = try? produceGizmoUsingTechnology() { return result }
+ if let result = try? produceGizmoUsingMagic() { return result }
+ print("warning: failed to produce a Gizmo in any way")
+ return nil
+ ```
+
+ `try?` always adds an extra level of `Optional` to the result type of the
+ expression being evaluated. If a throwing function's normal return type is
+ `Int?`, the result of calling it with `try?` will be `Int??`, or
+ `Optional>`. **(21692467)**
+
+* Type names and enum cases now print and convert to `String` without
+ qualification by default. `debugPrint` or `String(reflecting:)` can still be
+ used to get fully qualified names. For example:
+
+ ```swift
+ enum Fruit { case Apple, Banana, Strawberry }
+ print(Fruit.Apple) // "Apple"
+ debugPrint(Fruit.Apple) // "MyApp.Fruit.Apple")
+ ```
+
+ **(21788604)**
+
+* C `typedef`s of block types are imported as `typealias`s for Swift closures.
+
+ The primary result of this is that `typedef`s for blocks with a parameter of
+ type `BOOL` are imported as closures with a parameter of type `Bool` (rather
+ than `ObjCBool` as in the previous release). This matches the behavior of
+ block parameters to imported Objective-C methods. **(22013912)**
+
+* The type `Boolean` in `MacTypes.h` is imported as `Bool` in contexts that allow
+ bridging between Swift and Objective-C types.
+
+ In cases where the representation is significant, `Boolean` is imported as a
+ distinct `DarwinBoolean` type, which is `BooleanLiteralConvertible` and can be
+ used in conditions (much like the `ObjCBool` type). **(19013551)**
+
+* Fields of C structs that are marked `__unsafe_unretained` are presented in
+ Swift using `Unmanaged`.
+
+ It is not possible for the Swift compiler to know if these references are
+ really intended to be strong (+1) or unretained (+0). **(19790608)**
+
+* The `NS_REFINED_FOR_SWIFT` macro can be used to move an Objective-C
+ declaration aside to provide a better version of the same API in Swift,
+ while still having the original implementation available. (For example, an
+ Objective-C API that takes a `Class` could offer a more precise parameter
+ type in Swift.)
+
+ The `NS_REFINED_FOR_SWIFT` macro operates differently on different declarations:
+
+ - `init` methods will be imported with the resulting Swift initializer having
+ `__` prepended to its first external parameter name.
+
+ ```objc
+ // Objective-C
+ - (instancetype)initWithClassName:(NSString *)name NS_REFINED_FOR_SWIFT;
+ ```
+
+ ```swift
+ // Swift
+ init(__className: String)
+ ```
+
+ - Other methods will be imported with `__` prepended to their base name.
+
+ ```objc
+ // Objective-C
+ - (NSString *)displayNameForMode:(DisplayMode)mode NS_REFINED_FOR_SWIFT;
+ ```
+
+ ```swift
+ // Swift
+ func __displayNameForMode(mode: DisplayMode) -> String
+ ```
+
+ - Subscript methods will be treated like any other methods and will not be
+ imported as subscripts.
+
+ - Other declarations will have `__` prepended to their name.
+
+ ```objc
+ // Objective-C
+ @property DisplayMode mode NS_REFINED_FOR_SWIFT;
+ ```
+
+ ```swift
+ // Swift
+ var __mode: DisplayMode { get set }
+ ```
+
+ **(20070465)**
+
+* Xcode provides context-sensitive code completions for enum elements and
+ option sets when using the shorter dot syntax. **(16659653)**
+
+* The `NSManaged` attribute can be used with methods as well as properties,
+ for access to Core Data's automatically generated Key-Value-Coding-compliant
+ to-many accessors.
+
+ ```swift
+ @NSManaged var employees: NSSet
+
+ @NSManaged func addEmployeesObject(employee: Employee)
+ @NSManaged func removeEmployeesObject(employee: Employee)
+ @NSManaged func addEmployees(employees: NSSet)
+ @NSManaged func removeEmployees(employees: NSSet)
+ ```
+
+ These can be declared in your `NSManagedObject` subclass. **(17583057)**
+
+* The grammar has been adjusted so that lines beginning with '.' are always
+ parsed as method or property lookups following the previous line, allowing
+ for code formatted like this to work:
+
+ ```swift
+ foo
+ .bar
+ .bas = 68000
+ ```
+
+ It is no longer possible to begin a line with a contextual static member
+ lookup (for example, to say `.staticVar = MyType()`). **(20238557)**
+
+* Code generation for large `struct` and `enum` types has been improved to reduce
+ code size. **(20598289)**
+
+* Nonmutating methods of structs, enums, and protocols may now be partially
+ applied to their self parameter:
+
+ ```swift
+ let a: Set = [1, 2, 3]
+ let b: [Set] = [[1], [4]]
+ b.map(a.union) // => [[1, 2, 3], [1, 2, 3, 4]]
+ ```
+
+ **(21091944)**
+
+* Swift documentation comments recognize a new top-level list
+ item: `- Throws: ...`
+
+ This item is used to document what errors can be thrown and why. The
+ documentation appears alongside parameters and return descriptions in Xcode
+ QuickHelp. **(21621679)**
+
+* Unnamed parameters now require an explicit `_:` to indicate that they are
+ unnamed. For example, the following is now an error:
+
+ ```swift
+ func f(Int) { }
+ ```
+
+ and must be written as:
+
+ ```swift
+ func f(_: Int) { }
+ ```
+
+ This simplifies the argument label model and also clarifies why cases like
+ `func f((a: Int, b: Int))` do not have parameters named `a` and `b`.
+ **(16737312)**
+
+* It is now possible to append a tuple to an array. **(17875634)**
+
+* The ability to refer to the 0 element of a scalar value (producing the
+ scalar value itself) has been removed. **(17963034)**
+
+* Variadic parameters can now appear anywhere in the parameter list for a
+ function or initializer. For example:
+
+ ```swift
+ func doSomethingToValues(values: Int... , options: MyOptions = [], fn: (Int) -> Void) { … }
+ ```
+
+ **(20127197)**
+
+* Generic subclasses of Objective-C classes are now supported. **(18505295)**
+
+* If an element of an enum with string raw type does not have an explicit raw
+ value, it will default to the text of the enum's name. For example:
+
+ ```swift
+ enum WorldLayer : String {
+ case Ground, BelowCharacter, Character
+ }
+ ```
+
+ is equivalent to:
+
+ ```swift
+ enum WorldLayer : String {
+ case Ground = "Ground"
+ case BelowCharacter = "BelowCharacter"
+ case Character = "Character"
+ }
+ ```
+
+ **(15819953)**
+
+* The `performSelector` family of APIs is now available for Swift code.
+ **(17227475)**
+
+* When delegating or chaining to a failable initializer (for example, with
+ `self.init(…)` or `super.init(…)`), one can now force-unwrap the result with
+ `!`. For example:
+
+ ```swift
+ extension UIImage {
+ enum AssetIdentifier: String {
+ case Isabella
+ case William
+ case Olivia
+ }
+
+ convenience init(assetIdentifier: AssetIdentifier) {
+ self.init(named: assetIdentifier.rawValue)!
+ }
+ }
+ ```
+
+ **(18497407)**
+
+* Initializers can now be referenced like static methods by referring to
+ `.init` on a static type reference or type object. For example:
+
+ ```swift
+ let x = String.init(5)
+ let stringType = String.self
+ let y = stringType.init(5)
+
+ let oneTwoThree = [1, 2, 3].map(String.init).reduce("", combine: +)
+ ```
+
+ `.init` is still implicit when constructing using a static type, as in
+ `String(5)`. `.init` is required when using dynamic type objects or when
+ referring to the initializer as a function value. **(21375845)**
+
+* Enums and cases can now be marked indirect, which causes the associated
+ value for the enum to be stored indirectly, allowing for recursive data
+ structures to be defined. For example:
+
+ ```swift
+ enum List {
+ case Nil
+ indirect case Cons(head: T, tail: List)
+ }
+
+ indirect enum Tree {
+ case Leaf(T)
+ case Branch(left: Tree, right: Tree)
+ }
+ ```
+
+ **(21643855)**
+
+* Formatting for Swift expression results has changed significantly when
+ using `po` or `expr -O`. Customization that was introduced has been refined
+ in the following ways:
+
+ - The formatted summary provided by either `debugDescription` or
+ `description` methods will always be used for types that conform to
+ `CustomDebugStringConvertible` or `CustomStringConvertible` respectively.
+ When neither conformance is present, the type name is displayed and
+ reference types also display the referenced address to more closely mimic
+ existing behavior for Objective-C classes.
+
+ - Value types such as enums, tuples, and structs display all members
+ indented below the summary by default, while reference types will not. This
+ behavior can be customized for all types by implementing
+ `CustomReflectable`.
+
+ These output customizations can be bypassed by using `p` or `expr` without
+ the `-O` argument to provide a complete list of all fields and their values.
+ **(21463866)**
+
+* Properties and methods using `Unmanaged` can now be exposed to Objective-C.
+ **(16832080)**
+
+* Applying the `@objc` attribute to a class changes that class's compile-time
+ name in the target's generated Objective-C header as well as changing its
+ runtime name. This applies to protocols as well. For example:
+
+ ```swift
+ // Swift
+ @objc(MyAppDelegate)
+ class AppDelegate : NSObject, UIApplicationDelegate {
+ // ...
+ }
+ ```
+
+ ```objc
+ // Objective-C
+ @interface MyAppDelegate : NSObject
+ // ...
+ @end
+ ```
+
+ **(17469485)**
+
+* Collections containing types that are not Objective-C compatible are no
+ longer considered Objective-C compatible types themselves.
+
+ For example, previously `Array` was permitted as the type
+ of a property marked `@objc`; this is no longer the case. **(19787270)**
+
+* Generic subclasses of Objective-C classes, as well as nongeneric classes
+ that inherit from such a class, require runtime metadata instantiation and
+ cannot be directly named from Objective-C code.
+
+ When support for generic subclasses of Objective-C classes was first added,
+ the generated Objective-C bridging header erroneously listed such classes,
+ which, when used, could lead to incorrect runtime behavior or compile-time
+ errors. This has been fixed.
+
+ The behavior of the `@objc` attribute on a class has been clarified such that
+ applying `@objc` to a class which cannot appear in a bridging header is now
+ an error.
+
+ Note that this change does not result in a change of behavior with valid
+ code because members of a class are implicitly `@objc` if any superclass of
+ the class is an `@objc` class, and all `@objc` classes must inherit from
+ NSObject. **(21342574)**
+
+* The performance of `-Onone` (debug) builds has been improved by using
+ prespecialized instances of generics in the standard library. It produces
+ significantly faster executables in debug builds in many cases, without
+ impacting compile time. **(20486658)**
+
+* `AnyObject` and `NSObject` variables that refer to class objects can be cast
+ back to class object types. For example, this code succeeds:
+
+ ```swift
+ let x: AnyObject = NSObject.self
+ let y = x as! NSObject.Type
+ ```
+
+ Arrays, dictionaries, and sets that contain class objects successfully
+ bridge with `NSArray`, `NSDictionary`, and `NSSet` as well. Objective-C APIs
+ that provide `NSArray *` objects, such as `-[NSURLSessionConfiguration
+ protocolClasses]`, now work correctly when used in Swift. **(16238475)**
+
+* `print()` and reflection via Mirrors is able to report both the current
+ case and payload for all enums with multiple payload types. The only
+ remaining enum types that do not support reflection are `@objc` enums and
+ enums imported from C. **(21739870)**
+
+* Enum cases with payloads can be used as functions. For example:
+
+ ```swift
+ enum Either { case Left(T), Right(U) }
+ let lefts: [Either] = [1, 2, 3].map(Either.Left)
+ let rights: [Either] = ["one", "two", "three"].map(Either.Right)
+ ```
+
+ **(19091028)**
+
+* `ExtensibleCollectionType` has been folded into
+ `RangeReplaceableCollectionType`. In addition, default implementations have
+ been added as methods, which should be used instead of the free Swift
+ module functions related to these protocols. **(18220295)**
+
+## Swift Standard Library
+
+* The standard library moved many generic global functions (such as `map`,
+ `filter`, and `sort`) to be methods written with protocol extensions. This
+ allows those methods to be pervasively available on all sequence and
+ collection types and allowed the removal of the global functions.
+
+* Deprecated enum elements no longer affect the names of nondeprecated
+ elements when an Objective-C enum is imported into Swift. This may cause
+ the Swift names of some enum elements to change. **(17686122)**
+
+* All enums imported from C are `RawRepresentable`, including those not
+ declared with `NS_ENUM` or `NS_OPTIONS`. As part of this change, the value
+ property of such enums has been renamed `rawValue`. **(18702016)**
+
+* Swift documentation comments use a syntax based on the Markdown format,
+ aligning them with rich comments in playgrounds.
+
+ - Outermost list items are interpreted as special fields and are highlighted
+ in Xcode QuickHelp.
+
+ - There are two methods of documenting parameters: parameter outlines and
+ separate parameter fields. You can mix and match these forms as you see
+ fit in any order or continuity throughout the doc comment. Because these
+ are parsed as list items, you can nest arbitrary content underneath them.
+
+ - Parameter outline syntax:
+
+ ```swift
+ - Parameters:
+ - x: ...
+ - y: ...
+ ```
+
+ - Separate parameter fields:
+
+ ```swift
+ - parameter x: ...
+ - parameter y: ...
+ ```
+
+ - Documenting return values:
+
+ ```swift
+ - returns: ...
+ ```
+
+ Other special fields are highlighted in QuickHelp, as well as rendering
+ support for all of Markdown. (20180161)
+
+* The `CFunctionPointer U>` type has been removed. C function types are
+ specified using the new `@convention(c)` attribute. Like other function
+ types, `@convention(c) T -> U` is not nullable unless made optional. The
+ `@objc_block` attribute for specifying block types has also been removed and
+ replaced with `@convention(block)`.
+
+* Methods and functions have the same rules for parameter names. You can omit
+ providing an external parameter name with `_`. To further simplify the model,
+ the shorthand `#` for specifying a parameter name has been removed, as have
+ the special rules for default arguments.
+
+ ```swift
+ // Declaration
+ func printFunction(str: String, newline: Bool)
+ func printMethod(str: String, newline: Bool)
+ func printFunctionOmitParameterName(str: String, _ newline: Bool)
+
+ // Call
+ printFunction("hello", newline: true)
+ printMethod("hello", newline: true)
+ printFunctionOmitParameterName("hello", true)
+ ```
+
+ **(17218256)**
+
+* `NS_OPTIONS` types get imported as conforming to the `OptionSetType` protocol,
+ which presents a set-like interface for options. Instead of using bitwise
+ operations such as:
+
+ ```swift
+ // Swift 1.2:
+ object.invokeMethodWithOptions(.OptionA | .OptionB)
+ object.invokeMethodWithOptions(nil)
+
+ if options @ .OptionC == .OptionC {
+ // .OptionC is set
+ }
+ ```
+
+ Option sets support set literal syntax, and set-like methods such as contains:
+
+ ```swift
+ object.invokeMethodWithOptions([.OptionA, .OptionB])
+ object.invokeMethodWithOptions([])
+
+ if options.contains(.OptionC) {
+ // .OptionC is set
+ }
+ ```
+
+ A new option set type can be written in Swift as a struct that conforms to
+ the `OptionSetType` protocol. If the type specifies a `rawValue` property and
+ option constants as `static let` constants, the standard library will provide
+ default implementations of the rest of the option set API:
+
+ ```swift
+ struct MyOptions: OptionSetType {
+ let rawValue: Int
+
+ static let TuringMachine = MyOptions(rawValue: 1)
+ static let LambdaCalculus = MyOptions(rawValue: 2)
+ static let VonNeumann = MyOptions(rawValue: 4)
+ }
+
+ let churchTuring: MyOptions = [.TuringMachine, .LambdaCalculus]
+ ```
+
+ **(18069205)**
+
+* Type annotations are no longer allowed in patterns and are considered part
+ of the outlying declaration. This means that code previously written as:
+
+ ```swift
+ var (a : Int, b : Float) = foo()
+ ```
+
+ needs to be written as:
+
+ ```swift
+ var (a,b) : (Int, Float) = foo()
+ ```
+
+ if an explicit type annotation is needed. The former syntax was ambiguous
+ with tuple element labels. **(20167393)**
+
+* The `do`/`while` loop is renamed to `repeat`/`while` to make it obvious
+ whether a statement is a loop from its leading keyword.
+
+ In Swift 1.2:
+
+ ```swift
+ do {
+ ...
+ } while
+ In Swift 2.0:
+ repeat {
+ ...
+ } while
+ ```
+
+ **(20336424)**
+
+* `forEach` has been added to `SequenceType`. This lets you iterate over
+ elements of a sequence, calling a body closure on each. For example:
+
+ ```swift
+ (0..<10).forEach {
+ print($0)
+ }
+ ```
+
+ This is very similar to the following:
+
+ ```swift
+ for x in 0..<10 {
+ print(x)
+ }
+ ```
+
+ But take note of the following differences:
+
+ - Unlike for-in loops, you can't use `break` or `continue` to exit the current
+ call of the body closure or skip subsequent calls.
+
+ - Also unlike for-in loops, using `return` in the body closure only exits from
+ the current call to the closure, not any outer scope, and won't skip
+ subsequent calls.
+
+ **(18231840)**
+
+* The `Word` and `UWord` types have been removed from the standard library; use
+ `Int` and `UInt` instead. **(18693488)**
+
+* Most standard library APIs that take closures or `@autoclosure` parameters
+ now use `rethrows`. This allows the closure parameters to methods like `map`
+ and `filter` to throw errors, and allows short-circuiting operators like `&&`,
+ `||`, and `??` to work with expressions that may produce errors.
+ **(21345565)**
+
+* SIMD improvements: Integer vector types in the simd module now only support
+ unchecked arithmetic with wraparound semantics using the `&+`, `&-`, and `&*`
+ operators, in order to better support the machine model for vectors.
+ The `+`, `-`, and `*` operators are unavailable on integer vectors, and Xcode
+ automatically suggests replacing them with the wrapping operators.
+
+ Code generation for vector types in the simd module has been improved to
+ better utilize vector hardware, leading to dramatically improved performance
+ in many cases. **(21574425)**
+
+* All `CollectionType` objects are now sliceable. `SequenceType` now has a notion
+ of `SubSequence`, which is a type that represents only some of the values but
+ in the same order. For example, the `ArraySubSequence` type is `ArraySlice`,
+ which is an efficient view on the `Array` type's buffer that avoids copying as
+ long as it uniquely references the `Array` from which it came.
+
+ The following free Swift functions for splitting/slicing sequences have been
+ removed and replaced by method requirements on the `SequenceType` protocol
+ with default implementations in protocol extensions. `CollectionType` has
+ specialized implementations, where possible, to take advantage of efficient
+ access of its elements.
+
+ ```swift
+ /// Returns the first `maxLength` elements of `self`,
+ /// or all the elements if `self` has fewer than `maxLength` elements.
+ prefix(maxLength: Int) -> SubSequence
+
+ /// Returns the last `maxLength` elements of `self`,
+ /// or all the elements if `self` has fewer than `maxLength` elements.
+ suffix(maxLength: Int) -> SubSequence
+
+ /// Returns all but the first `n` elements of `self`.
+ dropFirst(n: Int) -> SubSequence
+
+ /// Returns all but the last `n` elements of `self`.
+ dropLast(n: Int) -> SubSequence
+
+ /// Returns the maximal `SubSequence`s of `self`, in order, that
+ /// don't contain elements satisfying the predicate `isSeparator`.
+ split(maxSplits maxSplits: Int, allowEmptySlices: Bool, @noescape isSeparator: (Generator.Element) -> Bool) -> [SubSequence]
+ ```
+
+ The following convenience extension is provided for `split`:
+
+ ```swift
+ split(separator: Generator.Element, maxSplit: Int, allowEmptySlices: Bool) -> [SubSequence]
+ ```
+
+ Also, new protocol requirements and default implementations on
+ `CollectionType` are now available:
+
+ ```swift
+ /// Returns `self[startIndex.. SubSequence
+
+ /// Returns `self[start.. SubSequence
+
+ /// Returns `prefixUpTo(position.successor())`
+ prefixThrough(position: Index) -> SubSequence
+ ```
+
+ **(21663830)**
+
+* The `print` and `debugPrint` functions are improved:
+ - Both functions have become variadic, and you can print any number of items
+ with a single call.
+ - `separator: String = " "` was added so you can control how the items are
+ separated.
+ - `terminator: String = "\n"` replaced `appendNewline: bool = true.` With
+ this change, `print(x, appendNewline: false)` is expressed as
+ `print(x, terminator: "")`.
+
+ - For the variants that take an output stream, the argument label `toStream`
+ was added to the stream argument.
+
+ The `println` function from Swift 1.2 has been removed. **(21788540)**
+
+* For consistency and better composition of generic code, `ArraySlice` indices
+ are no longer always zero-based but map directly onto the indices of the
+ collection they are slicing and maintain that mapping even after mutations.
+
+ Before:
+
+ ```swift
+ var a = Array(0..<10)
+ var s = a[5..<10]
+ s.indices // 0..<5
+ s[0] = 111
+ s // [111, 6, 7, 8, 9]
+ s.removeFirst()
+ s.indices // 1..<5
+ ```
+
+ After:
+
+ ```swift
+ var a = Array(0..<10)
+ var s = a[5..<10]
+ s.indices // 5..<10
+ s[5] = 99
+ s // [99, 6, 7, 8, 9]
+ s.removeFirst()
+ s.indices // 6..<10
+ ```
+
+ Rather than define variants of collection algorithms that take explicit
+ subrange arguments, such as `a.sortSubrangeInPlace(3..<7)`, the Swift
+ standard library provides "slicing," which composes well with algorithms.
+ This enables you to write `a[3..<7].sortInPlace()`, for example. With most
+ collections, these algorithms compose naturally.
+
+ For example, before this change was incorporated:
+
+ ```swift
+ extension MyIntCollection {
+ func prefixThroughFirstNegativeSubrange() -> SubSequence {
+ // Find the first negative element
+ let firstNegative = self.indexOf { $0 < 0 } ?? endIndex
+
+ // Slice off non-negative prefix
+ let startsWithNegative = self.suffixFrom(firstNegative)
+
+ // Find the first non-negative position in the slice
+ let end = startsWithNegative.indexOf { $0 >= 0 } ?? endIndex
+ return self[startIndex..`. Unfortunately, when array slice indices are zero-based,
+ the last two lines of the method need to change to:
+
+ ```swift
+ let end = startsWithNegative.indexOf { $0 >= 0 }
+ ?? startsWithNegative.endIndex
+ return self[startIndex..() { } // error: generic parameter 'T' is not used in function signature
+ ```
+
+* The `Dictionary.removeAtIndex(_:)` method now returns the key-value pair
+ being removed as a two-element tuple (rather than returning `Void`).
+ Similarly, the `Set.removeAtIndex(_:)` method returns the element being
+ removed. **(20299881)**
+
+* Generic parameters on types in the Swift standard library have been renamed
+ to reflect the role of the types in the API. For example, `Array` became
+ `Array`, `UnsafePointer` became `UnsafePointer`, and so
+ forth. **(21429126)**
+
+* The `SinkType` protocol and `SinkOf` struct have been removed from the standard
+ library in favor of `(T) -> ()` closures. **(21663799)**
+
+
+2015-04-08 [Xcode 6.3, Swift 1.2]
+----------
+
+## Swift Language Changes
+
+* The notions of guaranteed conversion and "forced failable" conversion are now
+ separated into two operators. Forced failable conversion now uses the `as!`
+ operator. The `!` makes it clear to readers of code that the cast may fail and
+ produce a runtime error. The `as` operator remains for upcasts
+ (e.g. `someDerivedValue as Base`) and type annotations (`0 as Int8`) which
+ are guaranteed to never fail. **(19031957)**
+
+* Immutable (`let`) properties in `struct` and `class` initializers have been
+ revised to standardize on a general "`let`s are singly initialized but never
+ reassigned or mutated" model. Previously, they were completely mutable
+ within the body of initializers. Now, they are only allowed to be assigned
+ to once to provide their value. If the property has an initial value in its
+ declaration, that counts as the initial value for all initializers.
+ **(19035287)**
+
+* The implicit conversions from bridged Objective-C classes
+ (`NSString`/`NSArray`/`NSDictionary`) to their corresponding Swift value types
+ (`String`/`Array`/`Dictionary`) have been removed, making the Swift type
+ system simpler and more predictable.
+
+ This means that the following code will no longer work:
+
+ ```swift
+ import Foundation
+ func log(s: String) { println(x) }
+ let ns: NSString = "some NSString" // okay: literals still work
+ log(ns) // fails with the error
+ // "'NSString' is not convertible to 'String'"
+ ```
+
+ In order to perform such a bridging conversion, make the conversion explicit
+ with the as keyword:
+
+ ```swift
+ log(ns as String) // succeeds
+ ```
+
+ Implicit conversions from Swift value types to their bridged Objective-C
+ classes are still permitted. For example:
+
+ ```swift
+ func nsLog(ns: NSString) { println(ns) }
+ let s: String = "some String"
+ nsLog(s) // okay: implicit conversion from String to NSString is permitted
+ ```
+
+ Note that these Cocoa types in Objective-C headers are still automatically
+ bridged to their corresponding Swift type, which means that code is only
+ affected if it is explicitly referencing (for example) `NSString` in a Swift
+ source file. It is recommended you use the corresponding Swift types (for
+ example, `String`) directly unless you are doing something advanced, like
+ implementing a subclass in the class cluster. **(18311362)**
+
+* The `@autoclosure` attribute is now an attribute on a parameter, not an
+ attribute on the parameter's type.
+
+ Where before you might have used:
+
+ ```swift
+ func assert(predicate : @autoclosure () -> Bool) {...}
+ you now write this as:
+ func assert(@autoclosure predicate : () -> Bool) {...}
+ ```
+
+ **(15217242)**
+
+* The `@autoclosure` attribute on parameters now implies the new `@noescape`
+ attribute.
+
+* Curried function parameters can now specify argument labels.
+
+ For example:
+
+ ```swift
+ func curryUnnamed(a: Int)(_ b: Int) { return a + b }
+ curryUnnamed(1)(2)
+
+ func curryNamed(first a: Int)(second b: Int) -> Int { return a + b }
+ curryNamed(first: 1)(second: 2)
+ ```
+
+ **(17237268)**
+
+* Swift now detects discrepancies between overloading and overriding in the
+ Swift type system and the effective behavior seen via the Objective-C runtime.
+
+ For example, the following conflict between the Objective-C setter for
+ `property` in a class and the method `setProperty` in its extension is now
+ diagnosed:
+
+ ```swift
+ class A : NSObject {
+ var property: String = "Hello" // note: Objective-C method 'setProperty:'
+ // previously declared by setter for
+ // 'property' here
+ }
+
+ extension A {
+ func setProperty(str: String) { } // error: method 'setProperty'
+ // redeclares Objective-C method
+ //'setProperty:'
+ }
+ Similar checking applies to accidental overrides in the Objective-C runtime:
+ class B : NSObject {
+ func method(arg: String) { } // note: overridden declaration
+ // here has type '(String) -> ()'
+ }
+
+ class C : B {
+ func method(arg: [String]) { } // error: overriding method with
+ // selector 'method:' has incompatible
+ // type '([String]) -> ()'
+ }
+ as well as protocol conformances:
+ class MyDelegate : NSObject, NSURLSessionDelegate {
+ func URLSession(session: NSURLSession, didBecomeInvalidWithError:
+ Bool){ } // error: Objective-C method 'URLSession:didBecomeInvalidWithError:'
+ // provided by method 'URLSession(_:didBecomeInvalidWithError:)'
+ // conflicts with optional requirement method
+ // 'URLSession(_:didBecomeInvalidWithError:)' in protocol
+ // 'NSURLSessionDelegate'
+ }
+ ```
+
+ **(18391046, 18383574)**
+
+* The precedence of the Nil Coalescing Operator (`??`) has been raised to bind
+ tighter than short-circuiting logical and comparison operators, but looser
+ than as conversions and range operators. This provides more useful behavior
+ for expressions like:
+
+ ```swift
+ if allowEmpty || items?.count ?? 0 > 0 {...}
+ ```
+
+* The `&/` and `&%` operators were removed, to simplify the language and
+ improve consistency.
+
+ Unlike the `&+`, `&-`, and `&*` operators, these operators did not provide
+ two's-complement arithmetic behavior; they provided special case behavior
+ for division, remainder by zero, and `Int.min/-1`. These tests should be
+ written explicitly in the code as comparisons if needed. **(17926954)**
+
+* Constructing a `UInt8` from an ASCII value now requires the ascii keyword
+ parameter. Using non-ASCII unicode scalars will cause this initializer to
+ trap. **(18509195)**
+
+* The C `size_t` family of types are now imported into Swift as `Int`, since
+ Swift prefers sizes and counts to be represented as signed numbers, even if
+ they are non-negative.
+
+ This change decreases the amount of explicit type conversion between `Int`
+ and `UInt`, better aligns with `sizeof` returning `Int`, and provides safer
+ arithmetic properties. **(18949559)**
+
+* Classes that do not inherit from `NSObject` but do adopt an `@objc` protocol
+ will need to explicitly mark those methods, properties, and initializers
+ used to satisfy the protocol requirements as `@objc`.
+
+ For example:
+
+ ```swift
+ @objc protocol SomethingDelegate {
+ func didSomething()
+ }
+
+ class MySomethingDelegate : SomethingDelegate {
+ @objc func didSomething() { … }
+ }
+ ```
+
+## Swift Language Fixes
+
+* Dynamic casts (`as!`, `as?` and `is`) now work with Swift protocol types, so
+ long as they have no associated types. **(18869156)**
+
+* Adding conformances within a Playground now works as expected.
+
+ For example:
+
+ ```swift
+ struct Point {
+ var x, y: Double
+ }
+
+ extension Point : Printable {
+ var description: String {
+ return "(\(x), \(y))"
+ }
+ }
+
+ var p1 = Point(x: 1.5, y: 2.5)
+ println(p1) // prints "(1.5, 2.5)"
+ ```
+
+* Imported `NS_ENUM` types with undocumented values, such as
+ `UIViewAnimationCurve`, can now be converted from their raw integer values
+ using the `init(rawValue:)` initializer without being reset to `nil`. Code
+ that used `unsafeBitCast` as a workaround for this issue can be written to
+ use the raw value initializer.
+
+ For example:
+
+ ```swift
+ let animationCurve =
+ unsafeBitCast(userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue,
+ UIViewAnimationCurve.self)
+ can now be written instead as:
+ let animationCurve = UIViewAnimationCurve(rawValue:
+ userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue)!
+ ```
+
+ **(19005771)**
+
+* Negative floating-point literals are now accepted as raw values in enums.
+ **(16504472)**
+
+* Unowned references to Objective-C objects, or Swift objects inheriting from
+ Objective-C objects, no longer cause a crash if the object holding the
+ unowned reference is deallocated after the referenced object has been
+ released. **(18091547)**
+
+* Variables and properties with observing accessors no longer require an
+ explicit type if it can be inferred from the initial value expression.
+ **(18148072)**
+
+* Generic curried functions no longer produce random results when fully
+ applied. **(18988428)**
+
+* Comparing the result of a failed `NSClassFromString` lookup against `nil` now
+ behaves correctly. **(19318533)**
+
+* Subclasses that override base class methods with co- or contravariance in
+ Optional types no longer cause crashes at runtime.
+
+ For example:
+
+ ```swift
+ class Base {
+ func foo(x: String) -> String? { return x }
+ }
+ class Derived: Base {
+ override func foo(x: String?) -> String { return x! }
+ }
+ ```
+
+ **(19321484)**
+
+## Swift Language Enhancements
+
+* Swift now supports building targets incrementally, i.e. not rebuilding
+ every Swift source file in a target when a single file is changed.
+
+ The incremental build capability is based on a conservative dependency
+ analysis, so you may still see more files rebuilding than absolutely
+ necessary. If you find any cases where a file is not rebuilt when it should
+ be, please file a bug report. Running Clean on your target afterwards should
+ allow you to complete your build normally. **(18248514)**
+
+* A new `Set` data structure is included which provides a generic collection of
+ unique elements with full value semantics. It bridges with `NSSet`, providing
+ functionality analogous to `Array` and `Dictionary`. **(14661754)**
+
+* The `if–let` construct has been expanded to allow testing multiple optionals
+ and guarding conditions in a single `if` (or `while`) statement using syntax
+ similar to generic constraints:
+
+ ```swift
+ if let a = foo(), b = bar() where a < b,
+ let c = baz() {
+ }
+ ```
+
+ This allows you to test multiple optionals and include intervening boolean
+ conditions, without introducing undesirable nesting (for instance, to avoid
+ the optional unwrapping _"pyramid of doom"_).
+
+ Further, `if–let` now also supports a single leading boolean condition along
+ with optional binding `let` clauses. For example:
+
+ ```swift
+ if someValue > 42 && someOtherThing < 19, let a = getOptionalThing() where a > someValue {
+ }
+ ```
+
+ **(19797158, 19382942)**
+
+* The `if–let` syntax has been extended to support a single leading boolean
+ condition along with optional binding `let` clauses.
+
+ For example:
+
+ ```swift
+ if someValue > 42 && someOtherThing < 19, let a = getOptionalThing() where a > someValue {
+ }
+ ```
+
+ **(19797158)**
+
+* `let` constants have been generalized to no longer require immediate
+ initialization. The new rule is that a `let` constant must be initialized
+ before use (like a `var`), and that it may only be initialized: not
+ reassigned or mutated after initialization. This enables patterns such as:
+
+ ```swift
+ let x: SomeThing
+ if condition {
+ x = foo()
+ } else {
+ x = bar()
+ }
+ use(x)
+ ```
+
+ which formerly required the use of a `var`, even though there is no mutation
+ taking place. **(16181314)**
+
+* `static` methods and properties are now allowed in classes (as an alias for
+ `class final`). You are now allowed to declare static stored properties in
+ classes, which have global storage and are lazily initialized on first
+ access (like global variables). Protocols now declare type requirements as
+ static requirements instead of declaring them as class requirements.
+ **(17198298)**
+
+* Type inference for single-expression closures has been improved in several ways:
+ - Closures that are comprised of a single return statement are now type
+ checked as single-expression closures.
+ - Unannotated single-expression closures with non-`Void` return types can now
+ be used in `Void` contexts.
+ - Situations where a multi-statement closure's type could not be inferred
+ because of a missing return-type annotation are now properly diagnosed.
+
+* Swift enums can now be exported to Objective-C using the `@objc` attribute.
+ `@objc` enums must declare an integer raw type, and cannot be generic or use
+ associated values. Because Objective-C enums are not namespaced, enum cases
+ are imported into Objective-C as the concatenation of the enum name and
+ case name.
+
+ For example, this Swift declaration:
+
+ ```swift
+ // Swift
+ @objc
+ enum Bear: Int {
+ case Black, Grizzly, Polar
+ }
+ ```
+
+ imports into Objective-C as:
+
+ ```objc
+ // Objective-C
+ typedef NS_ENUM(NSInteger, Bear) {
+ BearBlack, BearGrizzly, BearPolar
+ };
+ ```
+
+ **(16967385)**
+
+* Objective-C language extensions are now available to indicate the nullability
+ of pointers and blocks in Objective-C APIs, allowing your Objective-C APIs
+ to be imported without `ImplicitlyUnwrappedOptional`. (See items below for
+ more details.) **(18868820)**
+
+* Swift can now partially import C aggregates containing unions, bitfields,
+ SIMD vector types, and other C language features that are not natively
+ supported in Swift. The unsupported fields will not be accessible from
+ Swift, but C and Objective-C APIs that have arguments and return values of
+ these types can be used in Swift. This includes the Foundation `NSDecimal`
+ type and the `GLKit` `GLKVector` and `GLKMatrix` types, among others.
+ **(15951448)**
+
+* Imported C structs now have a default initializer in Swift that initializes
+ all of the struct's fields to zero.
+
+ For example:
+
+ ```swift
+ import Darwin
+ var devNullStat = stat()
+ stat("/dev/null", &devNullStat)
+ ```
+
+ If a structure contains fields that cannot be correctly zero initialized
+ (i.e. pointer fields marked with the new `__nonnull` modifier), this default
+ initializer will be suppressed. **(18338802)**
+
+* New APIs for converting among the `Index` types for `String`,
+ `String.UnicodeScalarView`, `String.UTF16View`, and `String.UTF8View` are
+ available, as well as APIs for converting each of the `String` views into
+ `String`s. **(18018911)**
+
+* Type values now print as the full demangled type name when used with
+ `println` or string interpolation.
+
+ ```swift
+ toString(Int.self) // prints "Swift.Int"
+ println([Float].self) // prints "Swift.Array<Swift.Float>"
+ println((Int, String).self) // prints "(Swift.Int, Swift.String)"
+ ```
+
+ **(18947381)**
+
+* A new `@noescape` attribute may be used on closure parameters to functions.
+ This indicates that the parameter is only ever called (or passed as an
+ `@noescape` parameter in a call), which means that it cannot outlive the
+ lifetime of the call. This enables some minor performance optimizations,
+ but more importantly disables the `self.` requirement in closure arguments.
+ This enables control-flow-like functions to be more transparent about their
+ behavior. In a future beta, the standard library will adopt this attribute
+ in functions like `autoreleasepool()`.
+
+ ```swift
+ func autoreleasepool(@noescape code: () -> ()) {
+ pushAutoreleasePool()
+ code()
+ popAutoreleasePool()
+ }
+ ```
+
+ **(16323038)**
+
+* Performance is substantially improved over Swift 1.1 in many cases. For
+ example, multidimensional arrays are algorithmically faster in some cases,
+ unoptimized code is much faster in many cases, and many other improvements
+ have been made.
+
+* The diagnostics emitted for expression type check errors are greatly
+ improved in many cases. **(18869019)**
+
+* Type checker performance for many common expression kinds has been greatly
+ improved. This can significantly improve build times and reduces the number
+ of "expression too complex" errors. **(18868985)**
+
+* The `@autoclosure` attribute has a second form, `@autoclosure(escaping)`, that
+ provides the same caller-side syntax as `@autoclosure` but allows the
+ resulting closure to escape in the implementation.
+
+ For example:
+
+ ```swift
+ func lazyAssertion(@autoclosure(escaping) condition: () -> Bool,
+ message: String = "") {
+ lazyAssertions.append(condition) // escapes
+ }
+ lazyAssertion(1 == 2, message: "fail eventually")
+ ```
+
+ **(19499207)**
+
+## Swift Performance
+
+* A new compilation mode has been introduced for Swift called Whole Module
+ Optimization. This option optimizes all of the files in a target together
+ and enables better performance (at the cost of increased compile time). The
+ new flag can be enabled in Xcode using the `Whole Module Optimization` build
+ setting or by using the `swiftc` command line tool with the flag
+ `-whole-module-optimization`. **(18603795)**
+
+## Swift Standard Library Enhancements and Changes
+
+* `flatMap` was added to the standard library. `flatMap` is the function that
+ maps a function over something and returns the result flattened one level.
+ `flatMap` has many uses, such as to flatten an array:
+
+ ```swift
+ [[1,2],[3,4]].flatMap { $0 }
+ ```
+
+ or to chain optionals with functions:
+
+ ```swift
+ [[1,2], [3,4]].first.flatMap { find($0, 1) }
+ ```
+
+ **(19881534)**
+
+* The function `zip` was added. It joins two sequences together into one
+ sequence of tuples. **(17292393)**
+
+* `utf16Count` is removed from `String`. Instead use count on the `UTF16` view
+ of the `String`.
+
+ For example:
+
+ ```swift
+ count(string.utf16)
+ ```
+
+ **(17627758)**
+
+
+2014-12-02 [Xcode 6.1.1]
+----------
+
+* Class methods and initializers that satisfy protocol requirements now properly
+ invoke subclass overrides when called in generic contexts. For example:
+
+ ```swift
+ protocol P {
+ class func foo()
+ }
+
+ class C: P {
+ class func foo() { println("C!") }
+ }
+
+ class D: C {
+ override class func foo() { println("D!") }
+ }
+
+ func foo(x: T) {
+ x.dynamicType.foo()
+ }
+
+ foo(C()) // Prints "C!"
+ foo(D()) // Used to incorrectly print "C!", now prints "D!"
+ ```
+
+ **(18828217)**
+
+2014-10-09 [Xcode 6.1 Release Notes, Swift 1.1]
+----------
+
+* Values of type `Any` can now contain values of function type. **(16406907)**
+
+* Documentation for the standard library (displayed in quick help and in the
+ synthesized header for the Swift module) is improved. **(16462500)**
+
+* Class properties don't need to be marked final to avoid `O(n)` mutations on
+ value semantic types. **(17416120)**
+
+* Casts can now be performed between `CF` types (such as `CFString`, `CGImage`,
+ and `SecIdentity`) and AnyObject. Such casts will always succeed at run-time.
+ For example:
+
+ ```swift
+ var cfStr: CFString = ...
+ var obj: AnyObject = cfStr as AnyObject
+ var cfStr = obj as CFString
+ ```
+
+ **(18088474)**
+
+
+2014-10-09 [Roughly Xcode 6.1, and Swift 1.1]
+----------
+
+* `HeapBuffer`, `HeapBufferStorage`, and
+ `OnHeap` were never really useful, because their APIs were
+ insufficiently public. They have been replaced with a single class,
+ `ManagedBuffer`. See also the new function
+ `isUniquelyReferenced(x)` which is often useful in conjunction with
+ `ManagedBuffer`.
+
+* The `Character` enum has been turned into a struct, to avoid
+ exposing its internal implementation details.
+
+* The `countElements` function has been renamed `count`, for better
+ consistency with our naming conventions.
+
+* Mixed-sign addition and subtraction operations, that were
+ unintentionally allowed in previous versions, now cause a
+ compilation error.
+
+* OS X apps can now apply the `@NSApplicationMain` attribute to their app delegate
+ class in order to generate an implicit `main` for the app. This works like
+ the `@UIApplicationMain` attribute for iOS apps.
+
+* Objective-C `init` and factory methods are now imported as failable
+ initializers when they can return `nil`. In the absence of information
+ about a potentially-`nil` result, an Objective-C `init` or factory
+ method will be imported as `init!`.
+
+ As part of this change, factory methods that have NSError**
+ parameters, such as `+[NSString
+ stringWithContentsOfFile:encoding:error:]`, will now be imported as
+ (failable) initializers, e.g.,
+
+ ```swift
+ init?(contentsOfFile path: String,
+ encoding: NSStringEncoding,
+ error: NSErrorPointer)
+ ```
+
+* Nested classes explicitly marked `@objc` will now properly be included in a
+ target's generated header as long as the containing context is also
+ (implicitly or explicitly) `@objc`. Nested classes not explicitly marked
+ `@objc` will never be printed in the generated header, even if they extend an
+ Objective-C class.
+
+* All of the `*LiteralConvertible` protocols, as well as
+ `StringInterpolationConvertible`, now use initializers for their
+ requirements rather than static methods starting with
+ `convertFrom`. For example, `IntegerLiteralConvertible` now has the
+ following initializer requirement:
+
+ ```swift
+ init(integerLiteral value: IntegerLiteralType)
+ ```
+ Any type that previously conformed to one of these protocols will
+ need to replace its `convertFromXXX` static methods with the
+ corresponding initializer.
+
+2014-09-15
+----------
+
+* Initializers can now fail by returning `nil`. A failable initializer is
+ declared with `init?` (to return an explicit optional) or `init!` (to return
+ an implicitly-unwrapped optional). For example, you could implement
+ `String.toInt` as a failable initializer of `Int` like this:
+
+ ```swift
+ extension Int {
+ init?(fromString: String) {
+ if let i = fromString.toInt() {
+ // Initialize
+ self = i
+ } else {
+ // Discard self and return 'nil'.
+ return nil
+ }
+ }
+ }
+ ```
+
+ The result of constructing a value using a failable initializer then becomes
+ optional:
+
+ ```swift
+ if let twentytwo = Int(fromString: "22") {
+ println("the number is \(twentytwo)")
+ } else {
+ println("not a number")
+ }
+ ```
+
+ In the current implementation, struct and enum initializers can return nil
+ at any point inside the initializer, but class initializers can only return
+ nil after all of the stored properties of the object have been initialized
+ and `self.init` or `super.init` has been called. If `self.init` or
+ `super.init` is used to delegate to a failable initializer, then the `nil`
+ return is implicitly propagated through the current initializer if the
+ called initializer fails.
+
+* The `RawRepresentable` protocol that enums with raw types implicitly conform
+ to has been redefined to take advantage of failable initializers. The
+ `fromRaw(RawValue)` static method has been replaced with an initializer
+ `init?(rawValue: RawValue)`, and the `toRaw()` method has been replaced with
+ a `rawValue` property. Enums with raw types can now be used like this:
+
+ ```swift
+ enum Foo: Int { case A = 0, B = 1, C = 2 }
+ let foo = Foo(rawValue: 2)! // formerly 'Foo.fromRaw(2)!'
+ println(foo.rawValue) // formerly 'foo.toRaw()'
+ ```
+
+2014-09-02
+----------
+
+* Characters can no longer be concatenated using `+`. Use `String(c1) +
+ String(c2)` instead.
+
+2014-08-18
+---------
+
+* When force-casting between arrays of class or `@objc` protocol types
+ using `a as [C]`, type checking is now deferred until the moment
+ each element is accessed. Because bridging conversions from NSArray
+ are equivalent to force-casts from `[NSArray]`, this makes certain
+ Array round-trips through Objective-C code `O(1)` instead of `O(N)`.
+
+2014-08-04
+----------
+
+* `RawOptionSetType` now implements `BitwiseOperationsType`, so imported
+ `NS_OPTIONS` now support the bitwise assignment operators `|=`, `&=`,
+ and `^=`. It also no longer implements `BooleanType`; to check if an option
+ set is empty, compare it to `nil`.
+
+* Types implementing `BitwiseOperationsType` now automatically support
+ the bitwise assignment operators `|=`, `&=`, and `^=`.
+
+* Optionals can now be coalesced with default values using the `??` operator.
+ `??` is a short-circuiting operator that takes an optional on the left and
+ a non-optional expression on the right. If the optional has a value, its
+ value is returned as a non-optional; otherwise, the expression on the right
+ is evaluated and returned:
+
+ ```swift
+ var sequence: [Int] = []
+ sequence.first ?? 0 // produces 0, because sequence.first is nil
+ sequence.append(22)
+ sequence.first ?? 0 // produces 22, the value of sequence.first
+ ```
+
+* The optional chaining `?` operator can now be mutated through, like `!`.
+ The assignment and the evaluation of the right-hand side of the operator
+ are conditional on the presence of the optional value:
+
+ ```swift
+ var sequences = ["fibonacci": [1, 1, 2, 3, 4], "perfect": [6, 28, 496]]
+ sequences["fibonacci"]?[4]++ // Increments element 4 of key "fibonacci"
+ sequences["perfect"]?.append(8128) // Appends to key "perfect"
+
+ sequences["cubes"]?[3] = 3*3*3 // Does nothing; no "cubes" key
+ ```
+
+ Note that optional chaining still flows to the right, so prefix increment
+ operators are *not* included in the chain, so this won't type-check:
+
+ ```swift
+ ++sequences["fibonacci"]?[4] // Won't type check, can't '++' Int?
+ ```
+
+2014-07-28
+----------
+
+* The swift command line interface is now divided into an interactive driver
+ `swift`, and a batch compiler `swiftc`:
+
+ ```
+ swift [options] input-file [program-arguments]
+ Runs the script 'input-file' immediately, passing any program-arguments
+ to the script. Without any input files, invokes the repl.
+
+ swiftc [options] input-filenames
+ The familiar swift compiler interface: compiles the input-files according
+ to the mode options like -emit-object, -emit-executable, etc.
+ ```
+
+* For greater clarity and explicitness when bypassing the type system,
+ `reinterpretCast` has been renamed `unsafeBitCast`, and it has acquired
+ a (required) explicit type parameter. So
+
+ ```swift
+ let x: T = reinterpretCast(y)
+ ```
+
+ becomes
+
+ ```swift
+ let x = unsafeBitCast(y, T.self)
+ ```
+
+* Because their semantics were unclear, the methods `asUnsigned` (on
+ the signed integer types) and `asSigned` (on the unsigned integer
+ types) have been replaced. The new idiom is explicit construction
+ of the target type using the `bitPattern:` argument label. So,
+
+ ```swift
+ myInt.asUnsigned()
+ ```
+
+ has become
+
+ ```swift
+ UInt(bitPattern: myInt)
+ ```
+
+* To better follow Cocoa naming conventions and to encourage
+ immutability, The following pointer types were renamed:
+
+ | Old Name | New Name |
+ |---------------------------------|----------------------------------------|
+ | `UnsafePointer` | `UnsafeMutablePointer` |
+ | `ConstUnsafePointer` | `UnsafePointer` |
+ | `AutoreleasingUnsafePointer` | `AutoreleasingUnsafeMutablePointer` |
+
+ Note that the meaning of `UnsafePointer` has changed from mutable to
+ immutable. As a result, some of your code may fail to compile when
+ assigning to an `UnsafePointer.memory` property. The fix is to
+ change your `UnsafePointer` into an `UnsafeMutablePointer`.
+
+* The optional unwrapping operator `x!` can now be assigned through, and
+ mutating methods and operators can be applied through it:
+
+ ```swift
+ var x: Int! = 0
+ x! = 2
+ x!++
+
+ // Nested dictionaries can now be mutated directly:
+ var sequences = ["fibonacci": [1, 1, 2, 3, 0]]
+ sequences["fibonacci"]![4] = 5
+ sequences["fibonacci"]!.append(8)
+ ```
+
+* The `@auto_closure` attribute has been renamed to `@autoclosure`.
+
+* There is a new `dynamic` declaration modifier. When applied to a method,
+ property, subscript, or initializer, it guarantees that references to the
+ declaration are always dynamically dispatched and never inlined or
+ devirtualized, and that the method binding can be reliably changed at runtime.
+ The implementation currently relies on the Objective-C runtime, so `dynamic`
+ can only be applied to `@objc-compatible` declarations for now. `@objc` now
+ only makes a declaration visible to Objective-C; the compiler may now use
+ vtable lookup or direct access to access (non-dynamic) `@objc` declarations.
+
+ ```swift
+ class Foo {
+ // Always accessed by objc_msgSend
+ dynamic var x: Int
+
+ // Accessed by objc_msgSend from ObjC; may be accessed by vtable
+ // or by static reference in Swift
+ @objc var y: Int
+
+ // Not exposed to ObjC (unless Foo inherits NSObject)
+ var z: Int
+ }
+ ```
+
+ `dynamic` enables KVO, proxying, and other advanced Cocoa features to work
+ reliably with Swift declarations.
+
+* Clang submodules can now be imported:
+
+ ```swift
+ import UIKit.UIGestureRecognizerSubclass
+ ```
+
+* The numeric optimization levels `-O[0-3]` have been removed in favor of the
+ named levels `-Onone` and `-O`.
+
+* The `-Ofast` optimization flag has been renamed to `-Ounchecked`. We will accept
+ both names for now and remove `-Ofast` in a later build.
+
+* An initializer that overrides a designated initializer from its
+ superclass must be marked with the `override` keyword, so that all
+ overrides in the language consistently require the use of
+ `override`. For example:
+
+ ```swift
+ class A {
+ init() { }
+ }
+
+ class B : A {
+ override init() { super.init() }
+ }
+ ```
+
+* Required initializers are now more prominent in several ways. First,
+ a (non-final) class that conforms to a protocol that contains an
+ initializer requirement must provide a required initializer to
+ satisfy that requirement. This ensures that subclasses will also
+ conform to the protocol, and will be most visible with classes that
+ conform to `NSCoding`:
+
+ ```swift
+ class MyClass : NSObject, NSCoding {
+ required init(coder aDecoder: NSCoder!) { /*... */ }
+ func encodeWithCoder(aCoder: NSCoder!) { /* ... */ }
+ }
+ ```
+ Second, because `required` places a significant requirement on all
+ subclasses, the `required` keyword must be placed on overrides of a
+ required initializer:
+
+ ```swift
+ class MySubClass : MyClass {
+ var title: String = "Untitled"
+
+ required init(coder aDecoder: NSCoder!) { /*... */ }
+ override func encodeWithCoder(aCoder: NSCoder!) { /* ... */ }
+ }
+ ```
+ Finally, required initializers can now be inherited like any other
+ initializer:
+
+ ```swift
+ class MySimpleSubClass : MyClass { } // inherits the required init(coder:).
+ ```
+
+2014-07-21
+----------
+
+* Access control has been implemented.
+
+ - `public` declarations can be accessed from any module.
+ - `internal` declarations (the default) can be accessed from within the
+ current module.
+ - `private` declarations can be accessed only from within the current file.
+
+ There are still details to iron out here, but the model is in place.
+ The general principle is that an entity cannot be defined in terms of another
+ entity with less accessibility.
+
+ Along with this, the generated header for a framework will only include
+ public declarations. Generated headers for applications will include public
+ and internal declarations.
+
+* `CGFloat` is now a distinct floating-point type that wraps either a
+ `Float` (on 32-bit architectures) or a `Double` (on 64-bit
+ architectures). It provides all of the same comparison and
+ arithmetic operations of Float and Double, and can be created using
+ numeric literals.
+
+* The immediate mode `swift -i` now works for writing `#!` scripts that take
+ command line arguments. The `-i` option to the swift driver must now come at
+ the end of the compiler arguments, directly before the input filename. Any
+ arguments that come after `-i` and the input filename are treated as arguments
+ to the interpreted file and forwarded to `Process.arguments`.
+
+* Type inference for `for..in` loops has been improved to consider the
+ sequence along with the element pattern. For example, this accepts
+ the following loops that were previously rejected:
+
+ ```swift
+ for i: Int8 in 0..<10 { }
+ for i: Float in 0.0...10.0 { }
+ ```
+
+* Introduced the new `BooleanLiteralConvertible` protocol, which allows
+ user-defined types to support Boolean literals. `true` and `false`
+ are now `Boolean` constants and keywords.
+
+* The `@final`, `@lazy`, `@required` and `@optional` attributes are now
+ considered to be declaration modifiers - they no longer require (or allow) an
+ `@` sign.
+
+* The `@prefix`, `@infix`, and `@postfix` attributes have been changed to
+ declaration modifiers, so they are no longer spelled with an `@` sign.
+ Operator declarations have been rearranged from `operator prefix +` to
+ `prefix operator +` for consistency.
+
+2014-07-03
+----------
+
+* C function pointer types are now imported as `CFunctionPointer`, where `T`
+ is a Swift function type. `CFunctionPointer` and `COpaquePointer` can be
+ explicitly constructed from one another, but they do not freely convert, nor
+ is `CFunctionPointer` compatible with Swift closures.
+
+ Example: `int (*)(void)` becomes `CFunctionPointer<(Int) -> Void>`.
+
+* The interop model for pointers in C APIs has been simplified. Most code that
+ calls C functions by passing arrays, UnsafePointers, or the addresses of
+ variables with `&x` does not need to change. However, the `CConstPointer` and
+ `CMutablePointer` bridging types have been removed, and functions and methods
+ are now imported as and overridden by taking UnsafePointer and
+ `ConstUnsafePointer` directly. `Void` pointers are now imported as
+ `(Const)UnsafePointer`; `COpaquePointer` is only imported for opaque
+ types now.
+
+* `Array` types are now spelled with the brackets surrounding the
+ element type. For example, an array of `Int` is written as:
+
+ ```swift
+ var array: [Int]
+ ```
+
+* `Dictionary` types can now be spelled with the syntax `[K : V]`, where `K`
+ is the key type and `V` is the value type. For example:
+
+ ```swift
+ var dict: [String : Int] = ["Hello" : 1, "World" : 2]
+ ```
+
+ The type `[K : V]` is syntactic sugar for `Dictionary`; nothing
+ else has changed.
+
+* The `@IBOutlet` attribute no longer implicitly (and invisibly) changes the type
+ of the declaration it is attached to. It no longer implicitly makes variables
+ be an implicitly unwrapped optional and no longer defaults them to weak.
+
+* The `\x`, `\u` and `\U` escape sequences in string literals have been
+ consolidated into a single and less error prone `\u{123456}` syntax.
+
+
+2014-06-23
+---------
+
+* The half-open range operator has been renamed from `..` to `..<` to reduce
+ confusion. The `..<` operator is precedented in Groovy (among other languages)
+ and makes it much more clear that it doesn't include the endpoint.
+
+* Class objects such as `NSObject.self` can now be converted to `AnyObject` and
+ used as object values.
+
+* Objective-C protocol objects such as `NSCopying.self` can now be used as
+ instances of the `Protocol` class, such as in APIs such as XPC.
+
+* Arrays now have full value semantics: both assignment and
+ initialization create a logically-distinct object
+
+* The `sort` function and array method modify the target in-place. A
+ new `sorted` function and array method are non-mutating, creating
+ and returning a new collection.
+
+2014-05-19
+----------
+
+* `sort`, `map`, `filter`, and `reduce` methods on `Array`s accept trailing
+ closures:
+
+ ```swift
+ let a = [5, 6, 1, 3, 9]
+ a.sort{ $0 > $1 }
+ println(a) // [9, 6, 5, 3, 1]
+ println(a.map{ $0 * 2 }) // [18, 12, 10, 6, 2]
+ println(a.map{ $0 * 2 }.filter{ $0 < 10}) // [6, 2]
+ println(a.reduce(1000){ $0 + $1 }) // 1024 (no kidding)
+ ```
+
+* A lazy `map()` function in the standard library works on any `Sequence`.
+ Example:
+
+ ```swift
+ class X {
+ var value: Int
+
+ init(_ value: Int) {
+ self.value = value
+ println("created X(\(value))")
+ }
+ }
+
+ // logically, this sequence is X(0), X(1), X(2), ... X(50)
+ let lazyXs = map(0..50){ X($0) }
+
+ // Prints "created X(...)" 4 times
+ for x in lazyXs {
+ if x.value == 4 {
+ break
+ }
+ }
+ ```
+
+* There's a similar lazy `filter()` function:
+
+ ```swift
+ // 0, 10, 20, 30, 40
+ let tens = filter(0..50) { $0 % 10 == 0 }
+ let tenX = map(tens){ X($0) } // 5 lazy Xs
+ let tenXarray = Array(tenX) // Actually creates those Xs
+ ```
+
+* Weak pointers of classbound protocol type work now.
+
+* `IBOutlets` now default to weak pointers with implicit optional type (`T!`).
+
+* `NSArray*` parameters and result types of Objective-C APIs are now
+ imported as `AnyObject[]!`, i.e., an implicitly unwrapped optional
+ array storing `AnyObject` values. For example, `NSView`'s constraints
+ property
+
+ ```objc
+ @property (readonly) NSArray *constraints;
+ ```
+
+ is now imported as
+
+ ```swift
+ var constraints: AnyObject[]!
+ ```
+
+ Note that one can implicitly convert between an `AnyObject[]` and an
+ `NSArray` (in both directions), so (for example) one can still
+ explicitly use `NSArray` if desired:
+
+ ```swift
+ var array: NSArray = view.constraints
+ ```
+
+ Swift arrays bridge to `NSArray` similarly to the way Swift
+ strings bridge to `NSString`.
+
+* `ObjCMutablePointer` has been renamed `AutoreleasingUnsafePointer`.
+
+* `UnsafePointer` (and `AutoreleasingUnsafePointer`)'s `set()` and `get()`
+ have been replaced with a property called `memory`.
+
+ - Previously you would write:
+
+ ```swift
+ val = p.get()
+ p.set(val)
+ ```
+
+ - Now you write:
+
+ ```swift
+ val = p.memory
+ p.memory = val
+ ```
+
+* Removed shorthand `x as T!`; instead use `(x as T)!`
+
+ - `x as T!` now means "x as implicitly unwrapped optional".
+
+* Range operators `..` and `...` have been switched.
+
+ - `1..3` now means 1,2
+ - `1...3` now means 1,2,3
+
+* The pound sign (`#`) is now used instead of the back-tick (\`) to mark
+ an argument name as a keyword argument, e.g.,
+
+ ```swift
+ func moveTo(#x: Int, #y: Int) { ... }
+ moveTo(x: 5, y: 7)
+ ```
+
+* Objective-C factory methods are now imported as initializers. For
+ example, `NSColor`'s `+colorWithRed:green:blue:alpha` becomes
+
+ ```swift
+ init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
+ ```
+
+ which allows an `NSColor` to be created as, e.g.,
+
+ ```swift
+ NSColor(red: 0.5, green: 0.25, blue: 0.25, alpha: 0.5)
+ ```
+
+ Factory methods are identified by their kind (class methods), name
+ (starts with words that match the words that end the class name),
+ and result type (`instancetype` or the class type).
+
+* Objective-C properties of some `CF` type are no longer imported as `Unmanaged`.
+
+* REPL mode now uses LLDB, for a greatly-expanded set of features. The colon
+ prefix now treats the rest of the line as a command for LLDB, and entering
+ a single colon will drop you into the debugging command prompt. Most
+ importantly, crashes in the REPL will now drop you into debugging mode to
+ see what went wrong.
+
+ If you do have a need for the previous REPL, pass `-integrated-repl`.
+
+* In a UIKit-based application, you can now eliminate your 'main.swift' file
+ and instead apply the `@UIApplicationMain` attribute to your
+ `UIApplicationDelegate` class. This will cause the `main` entry point to the
+ application to be automatically generated as follows:
+
+ ```swift
+ UIApplicationMain(argc, argv, nil,
+ NSStringFromClass(YourApplicationDelegate.self))
+ ```
+
+ If you need nontrivial logic in your application entry point, you can still
+ write out a `main.swift`. Note that `@UIApplicationMain` and `main.swift` are
+ mutually exclusive.
+
+2014-05-13
+----------
+
+* weak pointers now work with implicitly unchecked optionals, enabling usecases
+ where you don't want to `!` every use of a weak pointer. For example:
+
+ ```swift
+ weak var myView : NSView!
+ ```
+
+ of course, they still work with explicitly checked optionals like `NSView?`
+
+* Dictionary subscripting now takes/returns an optional type. This allows
+ querying a dictionary via subscripting to gracefully fail. It also enables
+ the idiom of removing values from a dictionary using `dict[key] = nil`.
+ As part of this, `deleteKey` is no longer available.
+
+* Stored properties may now be marked with the `@lazy` attribute, which causes
+ their initializer to be evaluated the first time the property is touched
+ instead of when the enclosing type is initialized. For example:
+
+ ```swift
+ func myInitializer() -> Int { println("hello\n"); return 42 }
+ class MyClass {
+ @lazy var aProperty = myInitializer()
+ }
+
+ var c = MyClass() // doesn't print hello
+ var tmp = c.aProperty // prints hello on first access
+ tmp = c.aProperty // doesn't print on subsequent loads.
+
+ c = MyClass() // doesn't print hello
+ c.aProperty = 57 // overwriting the value prevents it from ever running
+ ```
+
+ Because lazy properties inherently rely on mutation of the property, they
+ cannot be `let`s. They are currently also limited to being members of structs
+ and classes (they aren't allowed as local or global variables yet) and cannot
+ be observed with `willSet`/`didSet` yet.
+
+* Closures can now specify a capture list to indicate with what strength they
+ want to capture a value, and to bind a particular field value if they want to.
+
+ Closure capture lists are square-bracket delimited and specified before the
+ (optional) argument list in a closure. Each entry may be specified as `weak`
+ or `unowned` to capture the value with a weak or unowned pointer, and may
+ contain an explicit expression if desired. Some examples:
+
+ ```swift
+ takeClosure { print(self.title) } // strong capture
+ takeClosure { [weak self] in print(self!.title) } // weak capture
+ takeClosure { [unowned self] in print(self.title) } // unowned capture
+ ```
+
+ You can also bind arbitrary expression to named values in the capture list.
+ The expression is evaluated when the closure is formed, and captured with the
+ specified strength. For example:
+
+ ```swift
+ // weak capture of "self.parent"
+ takeClosure { [weak tmp = self.parent] in print(tmp!.title) }
+ ```
+
+ The full form of a closure can take a signature (an argument list and
+ optionally a return type) if needed. To use either the capture list or the
+ signature, you must specify the context sensitive `in` keyword. Here is a
+ (weird because there is no need for `unowned`) example of a closure with both:
+
+ ```swift
+ myNSSet.enumerateObjectsUsingBlock { [unowned self] (obj, stop) in
+ self.considerWorkingWith(obj)
+ }
+ ```
+
+* The word `with` is now removed from the first keyword argument name
+ if an initialized imported from Objective-C. For example, instead of
+ building `UIColor` as:
+
+ ```swift
+ UIColor(withRed: r, green: g, blue: b, alpha: a)
+ ```
+
+ it will now be:
+
+ ```swift
+ UIColor(red: r, green: g, blue: b, alpha: a)
+ ```
+
+* `Dictionary` can be bridged to `NSDictionary` and vice versa:
+
+ - `NSDictionary` has an implicit conversion to `Dictionary`. It bridges in O(1), without memory allocation.
+
+ - `Dictionary` has an implicit conversion to `NSDictionary`.
+ `Dictionary` bridges to `NSDictionary` iff both `K` and `V` are
+ bridged. Otherwise, a runtime error is raised.
+
+ Depending on `K` and `V` the operation can be `O(1)` without memory
+ allocation, or `O(N)` with memory allocation.
+
+* Single-quoted literals are no longer recognized. Use double-quoted literals
+ and an explicit type annotation to define `Characters` and `UnicodeScalars`:
+
+ ```swift
+ var ch: Character = "a"
+ var us: UnicodeScalar = "a"
+ ```
+
+2014-05-09
+----------
+
+* The use of keyword arguments is now strictly enforced at the call
+ site. For example, consider this method along with a call to it:
+
+ ```swift
+ class MyColor {
+ func mixColorWithRed(red: Float, green: Float, blue: Float) { /* ... */ }
+ }
+
+ func mix(color: MyColor, r: Float, g: Float, b: Float) {
+ color.mixColorWithRed(r, g, b)
+ }
+ ```
+
+ The compiler will now complain about the missing `green:` and
+ `blue:` labels, with a Fix-It to correct the code:
+
+ ```
+ color.swift:6:24: error: missing argument labels 'green:blue:' in call
+ color.mixColorWithRed(r, g, b)
+ ^
+ green: blue:
+ ```
+
+ The compiler handles missing, extraneous, and incorrectly-typed
+ argument labels in the same manner. Recall that one can make a
+ parameter a keyword argument with the back-tick or remove a keyword
+ argument with the underscore.
+
+ ```swift
+ class MyColor {
+ func mixColor(`red: Float, green: Float, blue: Float) { /* ... */ }
+ func mixColorGuess(red: Float, _ green: Float, _ blue: Float) { /* ... */ }
+ }
+
+ func mix(color: MyColor, r: Float, g: Float, b: Float) {
+ color.mixColor(red: r, green: g, blue: b) // okay: all keyword arguments
+ color.mixColorGuess(r, g, b) // okay: no keyword arguments
+ }
+ ```
+
+ Arguments cannot be re-ordered unless the corresponding parameters
+ have default arguments. For example, given:
+
+ ```swift
+ func printNumber(`number: Int, radix: Int = 10, separator: String = ",") { }
+ ```
+
+ The following three calls are acceptable because only the arguments for
+ defaulted parameters are re-ordered relative to each other:
+
+ ```swift
+ printNumber(number: 256, radix: 16, separator: "_")
+ printNumber(number: 256, separator: "_")
+ printNumber(number: 256, separator: ",", radix: 16)
+ ```
+
+ However, this call:
+
+ ```swift
+ printNumber(separator: ",", radix: 16, number: 256)
+ ```
+
+ results in an error due to the re-ordering:
+
+ ```
+ printnum.swift:7:40: error: argument 'number' must precede argument 'separator'
+ printNumber(separator: ",", radix: 16, number: 256)
+ ~~~~~~~~~~~~~~ ^ ~~~
+ ```
+
+* `;` can no longer be used to demarcate an empty case in a switch statement,
+ use `break` instead.
+
+2014-05-07
+----------
+
+* The compiler's ability to diagnose many common kinds of type check errors has
+ improved. (`expression does not type-check` has been retired.)
+
+* Ranges can be formed with floating point numbers, e.g. `0.0 .. 100.0`.
+
+* Convenience initializers are now spelled as `convenience init` instead of with
+ the `-> Self` syntax. For example:
+
+ ```swift
+ class Foo {
+ init(x : Int) {} // designated initializer
+
+ convenience init() { self.init(42) } // convenience initializer
+ }
+ ```
+
+ You still cannot declare designated initializers in extensions, only
+ convenience initializers are allowed.
+
+* Reference types using the CoreFoundation runtime are now imported as
+ class types. This means that Swift will automatically manage the
+ lifetime of a `CFStringRef` the same way that it manages the lifetime
+ of an `NSString`.
+
+ In many common cases, this will just work. Unfortunately, values
+ are returned from `CF`-style APIs in a wide variety of ways, and
+ unlike Objective C methods, there simply isn't enough consistency
+ for Swift to be able to safely apply the documented conventions
+ universally. The framework teams have already audited many of the
+ most important `CF`-style APIs, and those APIs should be imported
+ without a hitch into Swift. For all the APIs which haven't yet
+ been audited, we must import return types using the `Unmanaged` type.
+ This type allows the programmer to control exactly how the object
+ is passed.
+
+ For example:
+
+ ```swift
+ // CFBundleGetAllBundles() returns an Unmanaged.
+ // From the documentation, we know that it returns a +0 value.
+ let bundles = CFBundleGetAllBundles().takeUnretainedValue()
+
+ // CFRunLoopCopyAllModes() returns an Unmanaged.
+ // From the documentation, we know that it returns a +1 value.
+ let modes = CFRunLoopCopyAllModes(CFRunLoopGetMain()).takeRetainedValue()
+ ```
+
+ You can also use `Unmanaged` types to pass and return objects
+ indirectly, as well as to generate unbalanced retains and releases
+ if you really require them.
+
+ The API of the Unmanaged type is still in flux, and your feedback
+ would be greatly appreciated.
+
+2014-05-03
+----------
+
+* The `@NSManaged` attribute can be applied to the properties of an
+ `NSManagedObject` subclass to indicate that they should be handled by
+ CoreData:
+
+ ```swift
+ class Employee : NSManagedObject {
+ @NSManaged var name: String
+ @NSManaged var department: Department
+ }
+ ```
+
+* The `@weak` and `@unowned` attributes have become context sensitive keywords
+ instead of attributes. To declare a `weak` or `unowned` pointer, use:
+
+ ```swift
+ weak var someOtherWindow : NSWindow?
+ unowned var someWindow : NSWindow
+ ```
+ ... with no `@` on the `weak`/`unowned`.
+
+2014-04-30
+----------
+
+* Swift now supports a `#elseif` form for build configurations, e.g.:
+
+ ```swift
+ #if os(OSX)
+ typealias SKColor = NSColor
+ #elseif os(iOS)
+ typealias SKColor = UIColor
+ #else
+ typealias SKColor = Green
+ #endif
+ ```
+
+* You can now use the `true` and `false` constants in build configurations,
+ allowing you to emulate the C idioms of `#if 0` (but spelled `#if false`).
+
+* `break` now breaks out of switch statements.
+
+* It is no longer possible to specify `@mutating` as an attribute, you may only
+ use it as a keyword, e.g.:
+
+ ```swift
+ struct Pair {
+ var x, y : Int
+ mutating func nuke() { x = 0; y = 0 }
+ }
+ ```
+ The former `@!mutating` syntax used to mark setters as non-mutating is now
+ spelled with the `nonmutating` keyword. Both mutating and nonmutating are
+ context sensitive keywords.
+
+* `NSLog` is now available from Swift code.
+
+* The parser now correctly handles expressions like `var x = Int[]()` to
+ create an empty array of integers. Previously you'd have to use syntax like
+ `Array()` to get this. Now that this is all working, please prefer to
+ use `Int[]` consistently instead of `Array`.
+
+* `Character` is the new character literal type:
+
+ ```swift
+ var x = 'a' // Infers 'Character' type
+ ```
+
+ You can force inference of `UnicodeScalar` like this:
+
+ ```swift
+ var scalar: UnicodeScalar = 'a'
+ ```
+
+ `Character` type represents a Unicode extended grapheme cluster (to put it
+ simply, a grapheme cluster is what users think of as a character: a base plus
+ any combining marks, or other cases explained in
+ [Unicode Standard Annex #29](http://unicode.org/reports/tr29/)).
+
+2014-04-22
+----------
+
+* Loops and switch statements can now carry labels, and you can
+ `break`/`continue` to those labels. These use conventional C-style label
+ syntax, and should be dedented relative to the code they are in. An example:
+
+ ```swift
+ func breakContinue(x : Int) -> Int {
+ Outer:
+ for a in 0..1000 {
+
+ Switch:
+ switch x {
+ case 42: break Outer
+ case 97: continue Outer
+ case 102: break Switch
+ case 13: continue // continue always works on loops.
+ case 139: break // break will break out of the switch (but see below)
+ }
+ }
+ }
+ ```
+
+* We are changing the behavior of `break` to provide C-style semantics, to allow
+ breaking out of a switch statement. Previously, break completely ignored
+ switches so that it would break out of the nearest loop. In the example above,
+ `case 139` would break out of the `Outer` loop, not the `Switch`.
+
+ In order to avoid breaking existing code, we're making this a compile time
+ error instead of a silent behavior change. If you need a solution for the
+ previous behavior, use labeled break.
+
+ This error will be removed in a week or two.
+
+* Cocoa methods and properties that are annotated with the
+ `NS_RETURNS_INNER_POINTER` attribute, including `-[NSData bytes]` and
+ `-[{NS,UI}Color CGColor]`, are now safe to use and follow the same lifetime
+ extension semantics as ARC.
+
+2014-04-18
+----------
+* Enabling/disabling of asserts
+
+ ```swift
+ assert(condition, msg)
+ ```
+
+ is enabled/disabled dependent on the optimization level. In debug mode at
+ `-O0` asserts are enabled. At higher optimization levels asserts are disabled
+ and no code is generated for them. However, asserts are always type checked
+ even at higher optimization levels.
+
+ Alternatively, assertions can be disabled/enabled by using the frontend flag
+ `-assert-config Debug`, or `-assert-config Release`.
+
+* Added optimization flag `-Ofast`. It disables all assertions (`assert`), and
+ runtime overflow and type checks.
+
+* The "selector-style" function and initializer declaration syntax is
+ being phased out. For example, this:
+
+ ```
+ init withRed(red: CGFloat) green(CGFloat) blue(CGFloat) alpha(CGFloat)
+ ```
+
+ will now be written as:
+
+ ```swift
+ init(withRed red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
+ ```
+
+ For each parameter, one can have both an argument API name (i.e.,
+ `withRed`, which comes first and is used at the call site) and an
+ internal parameter name that follows it (i.e. `red`, which comes
+ second and is used in the implementation). When the two names are
+ the same, one can simply write the name once and it will be used for
+ both roles (as with `green`, `blue`, and `alpha` above). The
+ underscore (`_`) can be used to mean "no name", as when the
+ following function/method:
+
+ ```
+ func murderInRoom(room:String) withWeapon(weapon: String)
+ ```
+
+ is translated to:
+
+ ```swift
+ func murderInRoom(_ room: String, withWeapon weapon: String)
+ ```
+
+ The compiler now complains when it sees the selector-style syntax
+ and will provide Fix-Its to rewrite to the newer syntax.
+
+ Note that the final form of selector syntax is still being hammered
+ out, but only having one declaration syntax, which will be very
+ close to this, is a known.
+
+* Stored properties can now be marked with the `@NSCopying` attribute, which
+ causes their setter to be synthesized with a copy to `copyWithZone:`. This may
+ only be used with types that conform to the `NSCopying` protocol, or option
+ types thereof. For example:
+
+ ```swift
+ @NSCopying var myURL : NSURL
+ ```
+
+ This fills the same niche as the (`copy`) attribute on Objective-C properties.
+
+
+2014-04-16
+----------
+
+* Optional variables and properties are now default-initialized to `nil`:
+
+ ```swift
+ class MyClass {
+ var cachedTitle: String? // "= nil" is implied
+ }
+ ```
+
+* `@IBOutlet` has been improved in a few ways:
+
+ - `IBOutlets` can now be `@unchecked` optional.
+
+ - An `IBOutlet` declared as non-optional, i.e.,
+
+ ```swift
+ @IBOutlet var button: NSButton
+ ```
+
+ will be treated as an `@unchecked` optional. This is considered to
+ be the best practice way to write an outlet, unless you want to explicitly
+ handle the null case - in which case, use `NSButton?` as the type. Either
+ way, the `= nil` that was formerly required is now implicit.
+
+* The precedence of `is` and `as` is now higher than comparisons, allowing the
+ following sorts of things to be written without parens:
+
+ ```swift
+ if x is NSButton && y is NSButtonCell { ... }
+
+ if 3/4 as Float == 6/8 as Float { ... }
+ ```
+
+* Objective-C blocks are now transparently bridged to Swift closures. You never
+ have to write `@objc_block` when writing Objective-C-compatible methods anymore.
+ Block parameters are now imported as unchecked optional closure types,
+ allowing `nil` to be passed.
+
+2014-04-09
+----------
+
+* `Dictionary` changes:
+
+ - `Elements` are now tuples, so you can write
+
+ ```swift
+ for (k, v) in d {
+ // ...
+ }
+ ```
+
+ - `keys` and `values` properties, which are `Collections` projecting
+ the corresponding aspect of each element. `Dictionary` indices are
+ usable with their `keys` and `values` properties, so:
+
+ ```swift
+ for i in indices(d) {
+ let (k, v) = d[i]
+ assert(k == d.keys[i])
+ assert(v == d.values[i])
+ }
+ ```
+
+* Semicolon can be used as a single no-op statement in otherwise empty cases in
+ `switch` statements:
+
+ ```swift
+ switch x {
+ case 1, 2, 3:
+ print("x is 1, 2 or 3")
+ default:
+ ;
+ }
+ ```
+
+* `override` is now a context sensitive keyword, instead of an attribute:
+
+ ```swift
+ class Base {
+ var property: Int { return 0 }
+ func instanceFunc() {}
+ class func classFunc() {}
+ }
+ class Derived : Base {
+ override var property: Int { return 1 }
+ override func instanceFunc() {}
+ override class func classFunc() {}
+ }
+ ```
+
+2014-04-02
+----------
+
+* Prefix splitting for imported enums has been revised again due to feedback:
+ - If stripping off a prefix would leave an invalid identifier (like `10_4`),
+ leave one more word in the result than would otherwise be there
+ (`Behavior10_4`).
+ - If all enumerators have a `k` prefix (for `constant`) and the enum doesn't,
+ the `k` should not be considered when finding the common prefix.
+ - If the enum name is a plural (like `NSSomethingOptions`) and the enumerator
+ names use the singular form (`NSSomethingOptionMagic`), this is considered
+ a matching prefix (but only if nothing follows the plural).
+
+* Cocoa APIs that take pointers to plain C types as arguments now get imported
+ as taking the new `CMutablePointer` and `CConstPointer` types instead
+ of `UnsafePointer`. These new types allow implicit conversions from
+ Swift `inout` parameters and from Swift arrays:
+
+ ```swift
+ let rgb = CGColorSpaceCreateDeviceRGB()
+ // CGColorRef CGColorCreate(CGColorSpaceRef, const CGFloat*);
+ let white = CGColorCreate(rgb, [1.0, 1.0, 1.0])
+
+ var s = 0.0, c = 0.0
+ // void sincos(double, double*, double*);
+ sincos(M_PI/2, &s, &c)
+ ```
+
+ Pointers to pointers to ObjC classes, such as `NSError**`, get imported as
+ `ObjCMutablePointer`. This type doesn't work with arrays, but
+ accepts inouts or `nil`:
+
+ ```swift
+ var error: NSError? = nil
+ let words = NSString.stringWithContentsOfFile("/usr/share/dict/words",
+ encoding: .UTF8StringEncoding,
+ error: &error)
+ ```
+
+ `Void` pointer parameters can be passed an array or inout of any type:
+
+ ```swift
+ // + (NSData*)dataWithBytes:(const void*)bytes length:(NSUInteger)length;
+ let data = NSData.dataWithBytes([1.5, 2.25, 3.125],
+ length: sizeof(Double.self) * 3)
+ var fromData = [0.0, 0.0, 0.0]
+ // - (void)getBytes:(void*)bytes length:(NSUInteger)length;
+ data.getBytes(&fromData, length: sizeof(Double.self) * 3)
+ ```
+
+ Note that we don't know whether an API reads or writes the C pointer, so
+ you need to explicitly initialize values (like `s` and `c` above) even if
+ you know that the API overwrites them.
+
+ This pointer bridging only applies to arguments, and only works with well-
+ behaved C and ObjC APIs that don't keep the pointers they receive as
+ arguments around or do other dirty pointer tricks. Nonstandard use of pointer
+ arguments still requires `UnsafePointer`.
+
+* Objective-C pointer types now get imported by default as the `@unchecked T?`
+ optional type. Swift class types no longer implicitly include `nil`.
+
+ A value of `@unchecked T?` can be implicitly used as a value of `T`.
+ Swift will implicitly cause a reliable failure if the value is `nil`,
+ rather than introducing undefined behavior (as in Objective-C ivar
+ accesses or everything in C/C++) or silently ignoring the operation
+ (as in Objective-C message sends).
+
+ A value of `@unchecked T?` can also be implicitly used as a value of `T?`,
+ allowing you explicitly handle the case of a `nil` value. For example,
+ if you would like to just silently ignore a message send a la Objective-C,
+ you can use the postfix `?` operator like so:
+
+ ```swift
+ fieldsForKeys[kHeroFieldKey]?.setEditable(true)
+ ```
+
+ This design allows you to isolate and handle `nil` values in Swift code
+ without requiring excessive "bookkeeping" boilerplate to use values that
+ you expect to be non-`nil`.
+
+ For now, we will continue to import C pointers as non-optional
+ `UnsafePointer` and `C*Pointer` types; that will be evaluated separately.
+
+ We intend to provide attributes for Clang to allow APIs to opt in to
+ importing specific parameters, return types, etc. as either the
+ explicit optional type `T?` or the simple non-optional type `T`.
+
+* The "separated" call syntax, i.e.,
+
+ ```
+ NSColor.colorWithRed(r) green(g) blue(b) alpha(a)
+ UIColor.init withRed(r) green(g) blue(b) alpha(a)
+ ```
+
+ is being removed. The compiler will now produce an error and provide
+ Fix-Its to rewrite calls to the "keyword-argument" syntax:
+
+ ```swift
+ NSColor.colorWithRed(r, green: g, blue: b, alpha: a)
+ UIColor(withRed: r, green:g, blue:b, alpha: a)
+ ```
+
+* The `objc` attribute now optionally accepts a name, which can be
+ used to provide the name for an entity as seen in Objective-C. For
+ example:
+
+ ```swift
+ class MyType {
+ var enabled: Bool {
+ @objc(isEnabled) get {
+ // ...
+ }
+ }
+ }
+ ```
+
+ The `@objc` attribute can be used to name initializers, methods,
+ getters, setters, classes, and protocols.
+
+* Methods, properties and subscripts in classes can now be marked with the
+ `@final` attribute. This attribute prevents overriding the declaration in any
+ subclass, and provides better performance (since dynamic dispatch is avoided
+ in many cases).
+
+
+2014-03-26
+----------
+
+* Attributes on declarations are no longer comma separated.
+
+ Old syntax:
+
+ ```
+ @_silgen_name("foo"), @objc func bar() {}
+ ```
+
+ New syntax:
+
+ ```swift
+ @_silgen_name("foo") @objc
+ ```
+
+ The `,` was vestigial when the attribute syntax consisted of bracket lists.
+
+* `switch` now always requires a statement after a `case` or `default`.
+
+ Old syntax:
+
+ ```swift
+ switch x {
+ case .A:
+ case .B(1):
+ println(".A or .B(1)")
+ default:
+ // Ignore it.
+ }
+ ```
+
+ New syntax:
+
+ ```swift
+ switch x {
+ case .A, .B(1):
+ println(".A or .B(1)")
+ default:
+ () // Ignore it.
+ }
+ ```
+
+ The following syntax can be used to introduce guard expressions for patterns
+ inside the `case`:
+
+ ```swift
+ switch x {
+ case .A where isFoo(),
+ .B(1) where isBar():
+ ...
+ }
+ ```
+
+* Observing properties can now `@override` properties in a base class, so you
+ can observe changes that happen to them.
+
+ ```swift
+ class MyAwesomeView : SomeBasicView {
+ @override
+ var enabled : Bool {
+ didSet {
+ println("Something changed")
+ }
+ }
+ ...
+ }
+ ```
+
+ Observing properties still invoke the base class getter/setter (or storage)
+ when accessed.
+
+
+* An `as` cast can now be forced using the postfix `!` operator without using
+ parens:
+
+ ```swift
+ class B {}
+ class D {}
+
+ let b: B = D()
+
+ // Before
+ let d1: D = (b as D)!
+ // After
+ let d2: D = b as D!
+ ```
+
+ Casts can also be chained without parens:
+
+ ```swift
+ // Before
+ let b2: B = (((D() as B) as D)!) as B
+ // After
+ let b3: B = D() as B as D! as B
+ ```
+
+* `as` can now be used in `switch` cases to match the result of a checked cast:
+
+ ```swift
+ func printHand(hand: Any) {
+ switch hand {
+ case 1 as Int:
+ print("ace")
+ case 11 as Int:
+ print("jack")
+ case 12 as Int:
+ print("queen")
+ case 13 as Int:
+ print("king")
+ case let numberCard as Int:
+ print("\(numberCard)")
+ case let (a, b) as (Int, Int) where a == b:
+ print("two ")
+ printHand(a)
+ print("s")
+ case let (a, b) as (Int, Int):
+ printHand(a)
+ print(" and a ")
+ printHand(b)
+ case let (a, b, c) as (Int, Int, Int) where a == b && b == c:
+ print("three ")
+ printHand(a)
+ print("s")
+ case let (a, b, c) as (Int, Int, Int):
+ printHand(a)
+ print(", ")
+ printHand(b)
+ print(", and a ")
+ printHand(c)
+ default:
+ print("unknown hand")
+ }
+ }
+ printHand(1, 1, 1) // prints "three aces"
+ printHand(12, 13) // prints "queen and a king"
+ ```
+
+* Enums and option sets imported from C/Objective-C still strip common
+ prefixes, but the name of the enum itself is now taken into consideration as
+ well. This keeps us from dropping important parts of a name that happen to be
+ shared by all members.
+
+ ```objc
+ // NSFileManager.h
+ typedef NS_OPTIONS(NSUInteger, NSDirectoryEnumerationOptions) {
+ NSDirectoryEnumerationSkipsSubdirectoryDescendants = 1UL << 0,
+ NSDirectoryEnumerationSkipsPackageDescendants = 1UL << 1,
+ NSDirectoryEnumerationSkipsHiddenFiles = 1UL << 2
+ } NS_ENUM_AVAILABLE(10_6, 4_0);
+ ```
+
+ ```swift
+ // Swift
+ let opts: NSDirectoryEnumerationOptions = .SkipsPackageDescendants
+ ```
+
+* `init` methods in Objective-C protocols are now imported as
+ initializers. To conform to `NSCoding`, you will now need to provide
+
+ ```swift
+ init withCoder(aDecoder: NSCoder) { ... }
+ ```
+
+ rather than
+
+ ```swift
+ func initWithCoder(aDecoder: NSCoder) { ... }
+ ```
+
+2014-03-19
+----------
+
+* When a class provides no initializers of its own but has default
+ values for all of its stored properties, it will automatically
+ inherit all of the initializers of its superclass. For example:
+
+ ```swift
+ class Document {
+ var title: String
+
+ init() -> Self {
+ self.init(withTitle: "Default title")
+ }
+
+ init withTitle(title: String) {
+ self.title = title
+ }
+ }
+
+ class VersionedDocument : Document {
+ var version = 0
+
+ // inherits 'init' and 'init withTitle:' from Document
+ }
+ ```
+
+ When one does provide a designated initializer in a subclass, as in
+ the following example:
+
+ ```swift
+ class SecureDocument : Document {
+ var key: CryptoKey
+
+ init withKey(key: CryptoKey) -> Self {
+ self.init(withKey: key, title: "Default title")
+ }
+
+ init withKey(key: CryptoKey) title(String) {
+ self.key = key
+ super.init(withTitle: title)
+ }
+ }
+ ```
+
+ the compiler emits Objective-C method stubs for all of the
+ designated initializers of the parent class that will abort at
+ runtime if called, and which indicate which initializer needs to be
+ implemented. This provides memory safety for cases where an
+ Objective-C initializer (such as `-[Document init]` in this example)
+ appears to be inherited, but isn't actually implemented.
+
+* `nil` may now be used as a Selector value. This allows calls to Cocoa methods
+ that accept `nil` selectors.
+
+* `[]` and `[:]` can now be used as the empty array and dictionary literal,
+ respectively. Because these carry no information about their element types,
+ they may only be used in a context that provides this information through type
+ inference (e.g. when passing a function argument).
+
+* Properties defined in classes are now dynamically dispatched and can be
+ overridden with `@override`. Currently `@override` only works with computed properties
+ overriding other computed properties, but this will be enhanced in coming weeks.
+
+
+2014-03-12
+----------
+
+* The `didSet` accessor of an observing property now gets passed in the old value,
+ so you can easily implement an action for when a property changes value. For
+ example:
+
+ ```swift
+ class MyAwesomeView : UIView {
+ var enabled : Bool = false {
+ didSet(oldValue):
+ if oldValue != enabled {
+ self.needsDisplay = true
+ }
+ }
+ ...
+ }
+ ```
+
+* The implicit argument name for set and willSet property specifiers has been
+ renamed from `(value)` to `(newValue)`. For example:
+
+ ```swift
+ var i : Int {
+ get {
+ return 42
+ }
+ set { // defaults to (newValue) instead of (value)
+ print(newValue)
+ }
+ }
+ ```
+
+* The magic identifier `__FUNCTION__` can now be used to get the name of the
+ current function as a string. Like `__FILE__` and `__LINE__`, if
+ `__FUNCTION__` is used as a default argument, the function name of the caller
+ is passed as the argument.
+
+ ```swift
+ func malkovich() {
+ println(__FUNCTION__)
+ }
+ malkovich() // prints "malkovich"
+
+ func nameCaller(name: String = __FUNCTION__) -> String {
+ return name
+ }
+
+ func foo() {
+ println(nameCaller()) // prints "foo"
+ }
+
+ func foo(x: Int) bar(y: Int) {
+ println(nameCaller()) // prints "foo:bar:"
+ }
+ ```
+
+ At top level, `__FUNCTION__` gives the module name:
+
+ ```swift
+ println(nameCaller()) // prints your module name
+ ```
+
+* Selector-style methods can now be referenced without applying arguments
+ using member syntax `foo.bar:bas:`, for instance, to test for the availability
+ of an optional protocol method:
+
+ ```swift
+ func getFrameOfObjectValueForColumn(ds: NSTableViewDataSource,
+ tableView: NSTableView,
+ column: NSTableColumn,
+ row: Int) -> AnyObject? {
+ if let getObjectValue = ds.tableView:objectValueForTableColumn:row: {
+ return getObjectValue(tableView, column, row)
+ }
+ return nil
+ }
+ ```
+
+* The compiler now warns about cases where a variable is inferred to have
+ `AnyObject`, `AnyClass`, or `()` type, since type inference can turn a simple
+ mistake (e.g. failing to cast an `AnyObject` when you meant to) into something
+ with ripple effects. Here is a simple example:
+
+ ```
+ t.swift:4:5: warning: variable 'fn' inferred to have type '()', which may be unexpected
+ var fn = abort()
+ ^
+ t.swift:4:5: note: add an explicit type annotation to silence this warning
+ var fn = abort()
+ ^
+ : ()
+ ```
+
+ If you actually did intend to declare a variable of one of these types, you
+ can silence this warning by adding an explicit type (indicated by the Fixit).
+ See **rdar://15263687 and rdar://16252090** for more rationale.
+
+* `x.type` has been renamed to `x.dynamicType`, and you can use `type` as a
+ regular identifier again.
+
+2014-03-05
+----------
+
+* C macros that expand to a single constant string are now imported as global
+ constants. Normal string literals are imported as `CString`; `NSString` literals
+ are imported as `String`.
+
+* All values now have a `self` property, exactly equivalent to the value
+ itself:
+
+ ```swift
+ let x = 0
+ let x2 = x.self
+ ```
+
+ Types also have a `self` property that is the type object for that
+ type:
+
+ ```swift
+ let theClass = NSObject.self
+ let theObj = theClass()
+ ```
+
+ References to type names are now disallowed outside of a constructor call
+ or member reference; to get a type object as a value, `T.self` is required.
+ This prevents the mistake of intending to construct an instance of a
+ class but forgetting the parens and ending up with the class object instead:
+
+ ```swift
+ let x = MyObject // oops, I meant MyObject()...
+ return x.description() // ...and I accidentally called +description
+ // instead of -description
+ ```
+
+* Initializers are now classified as **designated initializers**, which
+ are responsible for initializing the current class object and
+ chaining via `super.init`, and **convenience initializers**, which
+ delegate to another initializer and can be inherited. For example:
+
+ ```swift
+ class A {
+ var str: String
+
+ init() -> Self { // convenience initializer
+ self.init(withString: "hello")
+ }
+
+ init withString(str: String) { // designated initializer
+ self.str = str
+ }
+ }
+ ```
+
+ When a subclass overrides all of its superclass's designated
+ initializers, the convenience initializers are inherited:
+
+ ```swift
+ class B {
+ init withString(str: String) { // designated initializer
+ super.init(withString: str)
+ }
+
+ // inherits A.init()
+ }
+ ```
+
+ Objective-C classes that provide `NS_DESIGNATED_INITIALIZER`
+ annotations will have their init methods mapped to designated
+ initializers or convenience initializers as appropriate; Objective-C
+ classes without `NS_DESIGNATED_INITIALIZER` annotations have all of
+ their `init` methods imported as designated initializers, which is
+ safe (but can be verbose for subclasses). Note that the syntax and
+ terminology is still somewhat in flux.
+
+* Initializers can now be marked as `required` with an attribute,
+ meaning that every subclass is required to provide that initializer
+ either directly or by inheriting it from a superclass. To construct
+
+ ```swift
+ class View {
+ @required init withFrame(frame: CGRect) { ... }
+ }
+
+ func buildView(subclassObj: View.Type, frame: CGRect) -> View {
+ return subclassObj(withFrame: frame)
+ }
+
+ class MyView : View {
+ @required init withFrame(frame: CGRect) {
+ super.init(withFrame: frame)
+ }
+ }
+
+ class MyOtherView : View {
+ // error: must override init withFrame(CGRect).
+ }
+ ```
+
+* Properties in Objective-C protocols are now correctly imported as properties.
+ (Previously the getter and setter were imported as methods.)
+
+* Simple enums with no payloads, including `NS_ENUM`s imported
+ from Cocoa, now implicitly conform to the Equatable and Hashable protocols.
+ This means they can be compared with the `==` and `!=` operators and can
+ be used as `Dictionary` keys:
+
+ ```swift
+ enum Flavor {
+ case Lemon, Banana, Cherry
+ }
+
+ assert(Flavor.Lemon == .Lemon)
+ assert(Flavor.Banana != .Lemon)
+
+ struct Profile {
+ var sweet, sour: Bool
+ }
+
+ let flavorProfiles: Dictionary = [
+ .Lemon: Profile(sweet: false, sour: true ),
+ .Banana: Profile(sweet: true, sour: false),
+ .Cherry: Profile(sweet: true, sour: true ),
+ ]
+ assert(flavorProfiles[.Lemon].sour)
+ ```
+
+* `val` has been removed. Long live `let`!
+
+* Values whose names clash with Swift keywords, such as Cocoa methods or
+ properties named `class`, `protocol`, `type`, etc., can now be defined and
+ accessed by wrapping reserved keywords in backticks to suppress their builtin
+ meaning:
+
+ ```swift
+ let `class` = 0
+ let `type` = 1
+ let `protocol` = 2
+ println(`class`)
+ println(`type`)
+ println(`protocol`)
+
+ func foo(Int) `class`(Int) {}
+ foo(0, `class`: 1)
+ ```
+
+2014-02-26
+----------
+
+* The `override` attribute is now required when overriding a method,
+ property, or subscript from a superclass. For example:
+
+ ```swift
+ class A {
+ func foo() { }
+ }
+
+ class B : A {
+ @override func foo() { } // 'override' is required here
+ }
+ ```
+
+* We're renaming `val` back to `let`. The compiler accepts both for this week,
+ next week it will just accept `let`. Please migrate your code this week, sorry
+ for the back and forth on this.
+
+* Swift now supports `#if`, `#else` and `#endif` blocks, along with target
+ configuration expressions, to allow for conditional compilation within
+ declaration and statement contexts.
+
+ Target configurations represent certain static information about the
+ compile-time build environment. They are implicit, hard-wired into the
+ compiler, and can only be referenced within the conditional expression of an
+ `#if` block.
+
+ Target configurations are tested against their values via a pseudo-function
+ invocation expression, taking a single argument expressed as an identifier.
+ The argument represents certain static build-time information.
+
+ There are currently two supported target configurations:
+ `os`, which can have the values `OSX` or `iOS`
+ `arch`, which can have the values `i386`, `x86_64`, `arm` and `arm64`
+
+ Within the context of an `#if` block's conditional expression, a target
+ configuration expression can evaluate to either `true` or `false`.
+
+ For example:
+
+ ```swift
+ #if arch(x86_64)
+ println("Building for x86_64")
+ #else
+ println("Not building for x86_64")
+ #endif
+
+ class C {
+ #if os(OSX)
+ func foo() {
+ // OSX stuff goes here
+ }
+ #else
+ func foo() {
+ // non-OSX stuff goes here
+ }
+ #endif
+ }
+ ```
+
+ The conditional expression of an `#if` block can be composed of one or more of
+ the following expression types:
+ - A unary expression, using `!`
+ - A binary expression, using `&&` or `||`
+ - A parenthesized expression
+ - A target configuration expression
+
+ For example:
+
+ ```swift
+ #if os(iOS) && !arch(I386)
+ ...
+ #endif
+ ```
+
+ Note that `#if`/`#else`/`#endif` blocks do not constitute a preprocessor, and
+ must form valid and complete expressions or statements. Hence, the following
+ produces a parser error:
+
+ ```swift
+ class C {
+
+ #if os(iOS)
+ func foo() {}
+ }
+ #else
+ func bar() {}
+ func baz() {}
+ }
+ #endif
+ ```
+
+ Also note that "active" code will be parsed, typechecked and emitted, while
+ "inactive" code will only be parsed. This is why code in an inactive `#if` or
+ `#else` block will produce parser errors for malformed code. This allows the
+ compiler to detect basic errors in inactive regions.
+
+ This is the first step to getting functionality parity with the important
+ subset of the C preprocessor. Further refinements are planned for later.
+
+* Swift now has both fully-closed ranges, which include their endpoint, and
+ half-open ranges, which don't.
+
+ ```swift
+ (swift) for x in 0...5 { print(x) } ; print('\n') // half-open range
+ 01234
+ (swift) for x in 0..5 { print(x) } ; print('\n') // fully-closed range
+ 012345
+ ```
+
+* Property accessors have a new brace-based syntax, instead of using the former
+ "label like" syntax. The new syntax is:
+
+ ```swift
+ var computedProperty: Int {
+ get {
+ return _storage
+ }
+ set {
+ _storage = value
+ }
+ }
+
+ var implicitGet: Int { // This form still works.
+ return 42
+ }
+
+ var storedPropertyWithObservingAccessors: Int = 0 {
+ willSet { ... }
+ didSet { ... }
+ }
+ ```
+
+* Properties and subscripts now work in protocols, allowing you to do things
+ like:
+
+ ```swift
+ protocol Subscriptable {
+ subscript(idx1: Int, idx2: Int) -> Int { get set }
+ var prop: Int { get }
+ }
+
+ func foo(s: Subscriptable) {
+ return s.prop + s[42, 19]
+ }
+ ```
+
+ These can be used for generic algorithms now as well.
+
+* The syntax for referring to the type of a type, `T.metatype`, has been
+ changed to `T.Type`. The syntax for getting the type of a value, `typeof(x)`,
+ has been changed to `x.type`.
+
+* `DynamicSelf` is now called `Self`; the semantics are unchanged.
+
+* `destructor` has been replaced with `deinit`, to emphasize that it
+ is related to `init`. We will refer to these as
+ `deinitializers`. We've also dropped the parentheses, i.e.:
+
+ ```swift
+ class MyClass {
+ deinit {
+ // release any resources we might have acquired, etc.
+ }
+ }
+ ```
+
+* Class methods defined within extensions of Objective-C classes can
+ now refer to `self`, including using `instancetype` methods. As a
+ result, `NSMutableString`, `NSMutableArray`, and `NSMutableDictionary`
+ objects can now be created with their respective literals, i.e.,
+
+ ```swift
+ var dict: NSMutableDictionary = ["a" : 1, "b" : 2]
+ ```
+
+2014-02-19
+----------
+
+* The `Stream` protocol has been renamed back to `Generator,` which is
+ precedented in other languages and causes less confusion with I/O
+ streaming.
+
+* The `type` keyword was split into two: `static` and `class`. One can define
+ static functions and static properties in structs and enums like this:
+
+ ```swift
+ struct S {
+ static func foo() {}
+ static var bar: Int = 0
+ }
+ enum E {
+ static func foo() {}
+ }
+ ```
+
+ `class` keyword allows one to define class properties and class methods in
+ classes and protocols:
+
+ ```swift
+ class C {
+ class func foo() {}
+ class var bar: Int = 0
+ }
+ protocol P {
+ class func foo() {}
+ class var bar: Int = 0
+ }
+ ```
+
+ When using `class` and `static` in the extension, the choice of keyword
+ depends on the type being extended:
+
+ ```swift
+ extension S {
+ static func baz() {}
+ }
+ extension C {
+ class func baz() {}
+ }
+ ```
+
+* The `let` keyword is no longer recognized. Please move to `val`.
+
+* The standard library has been renamed to `Swift` (instead of `swift`) to be
+ more consistent with other modules on our platforms.
+
+* `NSInteger` and other types that are layout-compatible with Swift standard
+ library types are now imported directly as those standard library types.
+
+* Optional types now support a convenience method named "cache" to cache the
+ result of a closure. For example:
+
+ ```swift
+ class Foo {
+ var _lazyProperty: Int?
+ var property: Int {
+ return _lazyProperty.cache { computeLazyProperty() }
+ }
+ }
+ ```
+
+2014-02-12
+----------
+
+* We are experimenting with a new message send syntax. For example:
+
+ ```swift
+ SKAction.colorizeWithColor(SKColor.whiteColor()) colorBlendFactor(1.0) duration(0.0)
+ ```
+
+ When the message send is too long to fit on a single line, subsequent lines
+ must be indented from the start of the statement or declaration. For
+ example, this is a single message send:
+
+ ```swift
+ SKAction.colorizeWithColor(SKColor.whiteColor())
+ colorBlendFactor(1.0)
+ duration(0.0)
+ ```
+
+ while this is a message send to colorizeWithColor: followed by calls
+ to `colorBlendFactor` and `duration` (on self or to a global function):
+
+ ```swift
+ SKAction.colorizeWithColor(SKColor.whiteColor())
+ colorBlendFactor(1.0) // call to 'colorBlendFactor'
+ duration(0.0) // call to 'duration'
+ ```
+
+* We are renaming the `let` keyword to `val`. The `let` keyword didn't work
+ out primarily because it is not a noun, so "defining a let" never sounded
+ right. We chose `val` over `const` and other options because `var` and `val`
+ have similar semantics (making syntactic similarity useful), because `const`
+ has varied and sordid connotations in C that we don't want to bring over, and
+ because we don't want to punish the "preferred" case with a longer keyword.
+
+ For migration purposes, the compiler now accepts `let` and `val` as synonyms,
+ `let` will be removed next week.
+
+* Selector arguments in function arguments with only a type are now implicitly
+ named after the selector chunk that contains them. For example, instead of:
+
+ ```swift
+ func addIntsWithFirst(first : Int) second(second : Int) -> Int {
+ return first+second
+ }
+ ```
+
+ you can now write:
+
+ ```swift
+ func addIntsWithFirst(first : Int) second(Int) -> Int {
+ return first+second
+ }
+ ```
+
+ if you want to explicitly want to ignore an argument, it is recommended that
+ you continue to use the `_` to discard it, as in:
+
+ ```swift
+ func addIntsWithFirst(first : Int) second(_ : Int) -> Int {...}
+ ```
+
+* The `@inout` attribute in argument lists has been promoted to a
+ context-sensitive keyword. Where before you might have written:
+
+ ```swift
+ func swap(a : @inout T, b : @inout T) {
+ (a,b) = (b,a)
+ }
+ ```
+
+ You are now required to write:
+
+ ```swift
+ func swap(inout a : T, inout b : T) {
+ (a,b) = (b,a)
+ }
+ ```
+
+ We made this change because `inout` is a fundamental part of the type
+ system, which attributes are a poor match for. The inout keyword is
+ also orthogonal to the `var` and `let` keywords (which may be specified in
+ the same place), so it fits naturally there.
+
+* The `@mutating` attribute (which can be used on functions in structs,
+ enums, and protocols) has been promoted to a context-sensitive keyword.
+ Mutating struct methods are now written as:
+
+ ```swift
+ struct SomeStruct {
+ mutating func f() {}
+ }
+ ```
+
+* Half-open ranges (those that don't include their endpoint) are now
+ spelled with three `.`s instead of two, for consistency with Ruby.
+
+ ```swift
+ (swift) for x in 0...5 { print(x) } ; print('\n') // new syntax
+ 01234
+ ```
+
+ Next week, we'll introduce a fully-closed range which does include
+ its endpoint. This will provide:
+
+ ```swift
+ (swift) for x in 0..5 { print(x) } ; print('\n') // coming soon
+ 012345
+ ```
+
+ These changes are being released separately so that users have a
+ chance to update their code before its semantics changes.
+
+* Objective-C properties with custom getters/setters are now imported
+ into Swift as properties. For example, the Objective-C property
+
+ ```swift
+ @property (getter=isEnabled) BOOL enabled;
+ ```
+
+ was previously imported as getter (`isEnabled`) and setter
+ (`setEnabled`) methods. Now, it is imported as a property (`enabled`).
+
+* `didSet`/`willSet` properties may now have an initial value specified:
+
+ ```swift
+ class MyAwesomeView : UIView {
+ var enabled : Bool = false { // Initial value.
+ didSet: self.needsDisplay = true
+ }
+ ...
+ }
+ ```
+
+ they can also be used as non-member properties now, e.g. as a global
+ variable or a local variable in a function.
+
+* Objective-C instancetype methods are now imported as methods that
+ return Swift's `DynamicSelf` type. While `DynamicSelf` is not
+ generally useful for defining methods in Swift, importing to it
+ eliminates the need for casting with the numerous `instancetype` APIs,
+ e.g.,
+
+ ```swift
+ let tileNode: SKSpriteNode = SKSpriteNode.spriteNodeWithTexture(tileAtlas.textureNamed("tile\(tileNumber).png"))!
+ ```
+
+ becomes
+
+ ```swift
+ let tileNode = SKSpriteNode.spriteNodeWithTexture(tileAtlas.textureNamed("tile\(tileNumber).png"))
+ ```
+
+ `DynamicSelf` will become more interesting in the coming weeks.
+
+2014-02-05
+----------
+
+* `if` and `while` statements can now conditionally bind variables. If the
+ condition of an `if` or `while` statement is a `let` declaration, then the
+ right-hand expression is evaluated as an `Optional` value, and control flow
+ proceeds by considering the binding to be `true` if the `Optional` contains a
+ value, or `false` if it is empty, and the variables are available in the true
+ branch. This allows for elegant testing of dynamic types, methods, nullable
+ pointers, and other Optional things:
+
+ ```swift
+ class B : NSObject {}
+ class D : B {
+ func foo() { println("we have a D") }
+ }
+ var b: B = D()
+ if let d = b as D {
+ d.foo()
+ }
+ var id: AnyObject = D()
+ if let foo = id.foo {
+ foo()
+ }
+ ```
+
+* When referring to a member of an `AnyObject` (or `AnyClass`) object
+ and using it directly (such as calling it, subscripting, or
+ accessing a property on it), one no longer has to write the `?` or
+ `!`. The run-time check will be performed implicitly. For example:
+
+ ```swift
+ func doSomethingOnViews(views: NSArray) {
+ for view in views {
+ view.updateLayer() // no '!' needed
+ }
+ }
+ ```
+
+ Note that one can still test whether the member is available at
+ runtime using `?`, testing the optional result, or conditionally
+ binding a variable to the resulting member.
+
+* The `swift` command line tool can now create executables and libraries
+ directly, just like Clang. Use `swift main.swift` to create an executable and
+ `swift -emit-library -o foo.dylib foo.swift` to create a library.
+
+* Object files emitted by Swift are not debuggable on their own, even if you
+ compiled them with the `-g` option. This was already true if you had multiple
+ files in your project. To produce a debuggable Swift binary from the command
+ line, you must compile and link in a single step with `swift`, or pass object
+ files AND swiftmodule files back into `swift` after compilation.
+ (Or use Xcode.)
+
+* `import` will no longer import other source files, only built modules.
+
+* The current directory is no longer implicitly an import path. Use `-I .` if
+ you have modules in your current directory.
+
+
+2014-01-29
+----------
+
+* Properties in structs and classes may now have `willSet:` and `didSet:`
+ observing accessors defined on them:
+
+ For example, where before you may have written something like this in a class:
+
+ ```swift
+ class MyAwesomeView : UIView {
+ var _enabled : Bool // storage
+ var enabled : Bool { // computed property
+ get:
+ return _enabled
+ set:
+ _enabled = value
+ self.needDisplay = true
+ }
+ ...
+ }
+ ```
+
+ you can now simply write:
+
+ ```swift
+ class MyAwesomeView : UIView {
+ var enabled : Bool { // Has storage & observing methods
+ didSet: self.needDisplay = true
+ }
+ ...
+ }
+ ```
+
+ Similarly, if you want notification before the value is stored, you can use
+ `willSet`, which gets the incoming value before it is stored:
+
+ ```swift
+ var x : Int {
+ willSet(value): // value is the default and may be elided, as with set:
+ println("changing from \(x) to \(value)")
+ didSet:
+ println("we've got a value of \(x) now.\n")
+ }
+ ```
+
+ The `willSet`/`didSet` observers are triggered on any store to the property,
+ except stores from `init()`, destructors, or from within the observers
+ themselves.
+
+ Overall, a property now may either be "stored" (the default), "computed"
+ (have a `get:` and optionally a `set:` specifier), or an observed
+ (`willSet`/`didSet`) property. It is not possible to have a custom getter
+ or setter on an observed property, since they have storage.
+
+ Two known-missing bits are:
+ - **(rdar://problem/15920332) didSet/willSet variables need to allow initializers**
+ - **(rdar://problem/15922884) support non-member didset/willset properties**
+
+ Because of the first one, for now, you need to explicitly store an initial
+ value to the property in your `init()` method.
+
+* Objective-C properties with custom getter or setter names are (temporarily)
+ not imported into Swift; the getter and setter will be imported individually
+ as methods instead. Previously, they would appear as properties within the
+ Objective-C class, but attempting to use the accessor with the customized
+ name would result in a crash.
+
+ The long-term fix is tracked as **(rdar://problem/15877160)**.
+
+* Computed 'type' properties (that is, properties of types, rather
+ than of values of the type) are now permitted on classes, on generic
+ structs and enums, and in extensions. Stored 'type' properties in
+ these contexts remain unimplemented.
+
+ The implementation of stored 'type' properties is tracked as
+ **(rdar://problem/15915785)** (for classes) and **(rdar://problem/15915867)**
+ (for generic types).
+
+* The following command-line flags have been deprecated in favor of new
+ spellings. The old spellings will be removed in the following week's build:
+
+ | Old Spelling | New Spelling |
+ |--------------------------|-------------------------------|
+ | `-emit-llvm` | `-emit-ir` |
+ | `-triple` | `-target` |
+ | `-serialize-diagnostics` | `-serialize-diagnostics-path` |
+
+* Imported `NS_OPTIONS` types now have a default initializer which produces a
+ value with no options set. They can also be initialized to the empty set with
+ `nil`. These are equivalent:
+
+ ```swift
+ var x = NSMatchingOptions()
+ var y: NSMatchingOptions = nil
+ ```
+
+
+2014-01-22
+----------
+
+* The swift binary no longer has an SDK set by default. Instead, you must do
+ one of the following:
+ - pass an explicit `-sdk /path/to/sdk`
+ - set `SDKROOT` in your environment
+ - run `swift` through `xcrun`, which sets `SDKROOT` for you
+
+* `let` declarations can now be used as struct/class properties. A `let`
+ property is mutable within `init()`, and immutable everywhere else.
+
+ ```swift
+ class C {
+ let x = 42
+ let y : Int
+ init(y : Int) {
+ self.y = y // ok, self.y is mutable in init()
+ }
+
+ func test() {
+ y = 42 // error: 'y' isn't mutable
+ }
+ }
+ ```
+
+* The immutability model for structs and enums is complete, and arguments are
+ immutable by default. This allows the compiler to reject mutations of
+ temporary objects, catching common bugs. For example, this is rejected:
+
+ ```swift
+ func setTo4(a : Double[]) {
+ a[10] = 4.0 // error: 'a' isn't mutable
+ }
+ ...
+ setTo4(someArray)
+ ```
+
+ since `a` is semantically a copy of the array passed into the function. The
+ proper fix in this case is to mark the argument is `@inout`, so the effect is
+ visible in the caller:
+
+ ```swift
+ func setTo4(a : @inout Double[]) {
+ a[10] = 4.0 // ok: 'a' is a mutable reference
+ }
+ ...
+ setTo4(&someArray)
+ ```
+
+ Alternatively, if you really just want a local copy of the argument, you can
+ mark it `var`. The effects aren't visible in the caller, but this can be
+ convenient in some cases:
+
+ ```swift
+ func doStringStuff(var s : String) {
+ s += "foo"
+ print(s)
+ }
+ ```
+
+* Objective-C instance variables are no longer imported from headers written in
+ Objective-C. Previously, they would appear as properties within the
+ Objective-C class, but trying to access them would result in a crash.
+ Additionally, their names can conflict with property names, which confuses
+ the Swift compiler, and there are no patterns in our frameworks that expect
+ you to access a parent or other class's instance variables directly. Use
+ properties instead.
+
+* The `NSObject` protocol is now imported under the name
+ `NSObjectProtocol` (rather than `NSObjectProto`).
+
+2014-01-15
+----------
+
+* Improved deallocation of Swift classes that inherit from Objective-C
+ classes: Swift destructors are implemented as `-dealloc` methods that
+ automatically call the superclass's `-dealloc`. Stored properties are
+ released right before the object is deallocated (using the same
+ mechanism as ARC), allowing properties to be safely used in
+ destructors.
+
+* Subclasses of `NSManagedObject` are now required to provide initial
+ values for each of their stored properties. This permits
+ initialization of these stored properties directly after +alloc to
+ provide memory safety with CoreData's dynamic subclassing scheme.
+
+* `let` declarations are continuing to make slow progress. Curried
+ and selector-style arguments are now immutable by default, and
+ `let` declarations now get proper debug information.
+
+2014-01-08
+----------
+
+* The `static` keyword changed to `type`. One can now define "type
+ functions" and "type variables" which are functions and variables
+ defined on a type (rather than on an instance of the type), e.g.,
+
+ ```swift
+ class X {
+ type func factory() -> X { ... }
+
+ type var version: Int
+ }
+ ```
+
+ The use of `static` was actively misleading, since type methods
+ on classes are dynamically dispatched (the same as Objective-C
+ `+` methods).
+
+ Note that `type` is a context-sensitive keyword; it can still be
+ used as an identifier.
+
+* Strings have a new native UTF-16 representation that can be
+ converted back and forth to `NSString` at minimal cost. String
+ literals are emitted as UTF-16 for string types that support it
+ (including Swift's `String`).
+
+* Initializers can now delegate to other initializers within the same
+ class by calling `self.init`. For example:
+
+ ```swift
+ class A { }
+
+ class B : A {
+ var title: String
+
+ init() {
+ // note: cannot access self before delegating
+ self.init(withTitle: "My Title")
+ }
+
+ init withTitle(title: String) {
+ self.title = title
+ super.init()
+ }
+ }
+ ```
+
+* Objective-C protocols no longer have the `Proto` suffix unless there
+ is a collision with a class name. For example, `UITableViewDelegate` is
+ now imported as `UITableViewDelegate` rather than
+ `UITableViewDelegateProto`. Where there is a conflict with a class,
+ the protocol will be suffixed with `Proto`, as in `NSObject` (the
+ class) and `NSObjectProto` (the protocol).
+
+2014-01-01
+----------
+
+* Happy New Year
+
+* Division and remainder arithmetic now trap on overflow. Like with the other
+ operators, one can use the "masking" alternatives to get non-trapping
+ behavior. The behavior of the non-trapping masking operators is defined:
+
+ ```swift
+ x &/ 0 == 0
+ x &% 0 == 0
+ SIGNED_MIN_FOR_TYPE &/ -1 == -1 // i.e. Int8: -0x80 / -1 == -0x80
+ SIGNED_MIN_FOR_TYPE &% -1 == 0
+ ```
+
+* Protocol conformance checking for `@mutating` methods is now implemented: an
+ `@mutating` struct method only fulfills a protocol requirement if the protocol
+ method was itself marked `@mutating`:
+
+ ```swift
+ protocol P {
+ func nonmutating()
+ @mutating
+ func mutating()
+ }
+
+ struct S : P {
+ // Error, @mutating method cannot implement non-@mutating requirement.
+ @mutating
+ func nonmutating() {}
+
+ // Ok, mutating allowed, but not required.
+ func mutating() {}
+ }
+ ```
+
+ As before, class methods never need to be marked `@mutating` (and indeed, they
+ aren't allowed to be marked as such).
+
+
+2013-12-25
+----------
+
+* Merry Christmas
+
+* The setters of properties on value types (structs/enums) are now `@mutating` by
+ default. To mark a setter non-mutating, use the `@!mutating` attribute.
+
+* Compiler inserts calls to `super.init()` into the class initializers that do
+ not call any initializers explicitly.
+
+* A `map` method with the semantics of Haskell's `fmap` was added to
+ `Array`. Map applies a function `f: T->U` to the values stored in
+ the array and returns an Array. So,
+
+ ```swift
+ (swift) func names(x: Int[]) -> String[] {
+ return x.map { "<" + String($0) + ">" }
+ }
+ (swift) names(Array())
+ // r0 : String[] = []
+ (swift) names([3, 5, 7, 9])
+ // r1 : String[] = ["<3>", "<5>", "<7>", "<9>"]
+ ```
+
+2013-12-18
+----------
+
+* Global variables and static properties are now lazily initialized on first
+ use. Where you would use `dispatch_once` to lazily initialize a singleton
+ object in Objective-C, you can simply declare a global variable with an
+ initializer in Swift. Like `dispatch_once`, this lazy initialization is thread
+ safe.
+
+ Unlike C++ global variable constructors, Swift global variables and
+ static properties now never emit static constructors (and thereby don't
+ raise build warnings). Also unlike C++, lazy initialization naturally follows
+ dependency order, so global variable initializers that cross module
+ boundaries don't have undefined behavior or fragile link order dependencies.
+
+* Swift has the start of an immutability model for value types. As part of this,
+ you can now declare immutable value bindings with a new `let` declaration,
+ which is semantically similar to defining a get-only property:
+
+ ```swift
+ let x = foo()
+ print(x) // ok
+ x = bar() // error: cannot modify an immutable value
+ swap(&x, &y) // error: cannot pass an immutable value as @inout parameter
+ x.clear() // error: cannot call mutating method on immutable value
+ getX().clear() // error: cannot mutate a temporary
+ ```
+
+ In the case of bindings of class type, the bound object itself is still
+ mutable, but you cannot change the binding.
+
+ ```swift
+ let r = Rocket()
+ r.blastOff() // Ok, your rocket is mutable.
+ r = Rocket() // error: cannot modify an immutable binding.
+ ```
+
+ In addition to the `let` declaration itself, `self` on classes, and a few
+ other minor things have switched to immutable bindings.
+
+ A pivotal part of this is that methods of value types (structs and enums) need
+ to indicate whether they can mutate self - mutating methods need to be
+ disallowed on let values (and get-only property results, temporaries, etc) but
+ non-mutating methods need to be allowed. The default for a method is that it
+ does not mutate `self`, though you can opt into mutating behavior with a new
+ `@mutating` attribute:
+
+ ```swift
+ struct MyWeirdCounter {
+ var count : Int
+
+ func empty() -> Bool { return count == 0 }
+
+ @mutating
+ func reset() {
+ count = 0
+ }
+ ...
+ }
+
+ let x = MyWeirdCounter()
+ x.empty() // ok
+ x.reset() // error, cannot mutate immutable 'let' value
+ ```
+
+ One missing piece is that the compiler does not yet reject mutations of self
+ in a method that isn't marked `@mutating`. That will be coming soon. Related
+ to methods are properties. Getters and setters can be marked mutating as
+ well:
+
+ ```swift
+ extension MyWeirdCounter {
+ var myproperty : Int {
+ get:
+ return 42
+
+ @mutating
+ set:
+ count = value*2
+ }
+ }
+ ```
+
+ The intention is for setters to default to mutating, but this has not been
+ implemented yet. There is more to come here.
+
+* A `map` method with the semantics of Haskell's `fmap` was added to
+ `Optional`. Map applies a function `f: T->U` to any value stored in
+ an `Optional`, and returns an `Optional`. So,
+
+ ```swift
+ (swift) func nameOf(x: Int?) -> String? {
+ return x.map { "<" + String($0) + ">" }
+ }
+ (swift)
+ (swift) var no = nameOf(.None) // Empty optional in...
+ // no : String? =
+ (swift) no ? "yes" : "no" // ...empty optional out
+ // r0 : String = "no"
+ (swift)
+ (swift) nameOf(.Some(42)) // Non-empty in
+ // r1 : String? =
+ (swift) nameOf(.Some(42))! // Non-empty out
+ // r2 : String = "<42>"
+ ```
+
+* Cocoa types declared with the `NS_OPTIONS` macro are now available in Swift.
+ Like `NS_ENUM` types, their values are automatically shortened based
+ on the common prefix of the value names in Objective-C, and the name can
+ be elided when type context provides it. They can be used in `if` statements
+ using the `&`, `|`, `^`, and `~` operators as in C:
+
+ ```swift
+ var options: NSJSONWritingOptions = .PrettyPrinted
+ if options & .PrettyPrinted {
+ println("pretty-printing enabled")
+ }
+ ```
+
+ We haven't yet designed a convenient way to author `NS_OPTIONS`-like types
+ in Swift.
+
+2013-12-11
+----------
+
+* Objective-C `id` is now imported as `AnyObject` (formerly known as
+ `DynamicLookup`), Objective-C `Class` is imported as `AnyClass`.
+
+* The casting syntax `x as T` now permits both implicit conversions
+ (in which case it produces a value of type `T`) and for
+ runtime-checked casts (in which case it produces a value of type `T?`
+ that will be `.Some(casted x)` on success and `.None` on failure). An
+ example:
+
+ ```swift
+ func f(x: AnyObject, y: NSControl) {
+ var view = y as NSView // has type 'NSView'
+ var maybeView = x as NSView // has type NSView?
+ }
+ ```
+
+* The precedence levels of binary operators has been redefined, with a much
+ simpler model than C's. This is with a goal to define away classes of bugs
+ such as those caught by Clang's `-Wparentheses` warnings, and to make it
+ actually possible for normal humans to reason about the precedence
+ relationships without having to look them up.
+
+ We ended up with 6 levels, from tightest binding to loosest:
+ ```
+ exponentiative: <<, >>
+ multiplicative: *, /, %, &
+ additive: +, -, |, ^
+ comparative: ==, !=, <, <=, >=, >
+ conjunctive: &&
+ disjunctive: ||
+ ```
+
+* The `Enumerable` protocol has been renamed `Sequence`.
+
+* The `Char` type has been renamed `UnicodeScalar`. The preferred
+ unit of string fragments for users is called `Character`.
+
+* Initialization semantics for classes, structs and enums init methods are now
+ properly diagnosed by the compiler. Instance variables now follow the same
+ initialization rules as local variables: they must be defined before use. The
+ initialization model requires that all properties with storage in the current
+ class be initialized before `super.init` is called (or, in a root class, before
+ any method is called on `self,` and before the final return).
+
+ For example, this will yield an error:
+
+ ```swift
+ class SomeClass : SomeBase {
+ var x : Int
+
+ init() {
+ // error: property 'self.x' not initialized at super.init call
+ super.init()
+ }
+ }
+ ```
+
+ A simple fix for this is to change the property definition to `var x = 0`,
+ or to explicitly assign to it before calling `super.init()`.
+
+* Relatedly, the compiler now diagnoses incorrect calls to `super.init()`. It
+ validates that any path through an initializer calls `super.init()` exactly once,
+ that all ivars are defined before the call to super.init, and that any uses
+ which require the entire object to be initialized come after the `super.init`
+ call.
+
+* Type checker performance has improved considerably (but we still
+ have much work to do here).
+
+2013-12-04
+----------
+
+* The "slice" versus "array" subtlety is now dead. `Slice` has been folded
+ into `Array` and `T[]` is just sugar for `Array`.
+
+
+2013-11-20
+----------
+* Unreachable code warning has been added:
+
+ ```swift
+ var y: Int = 1
+ if y == 1 { // note: condition always evaluates to true
+ return y
+ }
+ return 1 // warning: will never be executed
+ ```
+
+* Overflows on integer type conversions are now detected at runtime and, when
+ dealing with constants, at compile time:
+
+ ```swift
+ var i: Int = -129
+ var i8 = Int8(i)
+ // error: integer overflows when converted from 'Int' to 'Int8'
+
+ var si = Int8(-1)
+ var ui = UInt8(si)
+ // error: negative integer cannot be converted to unsigned type 'UInt8'
+ ```
+
+* `def` keyword was changed back to `func`.
+
+2013-11-13
+----------
+
+* Objective-C-compatible protocols can now contain optional
+ requirements, indicated by the `@optional` attribute:
+
+ ```swift
+ @class_protocol @objc protocol NSWobbling {
+ @optional def wobble()
+ }
+ ```
+
+ A class that conforms to the `NSWobbling` protocol above can (but does
+ not have to) implement `wobble`. When referring to the `wobble`
+ method for a value of type `NSWobbling` (or a value of generic type
+ that is bounded by `NSWobbling`), the result is an optional value
+ indicating whether the underlying object actually responds to the
+ given selector, using the same mechanism as messaging `id`. One can
+ use `!` to assume that the method is always there, `?` to chain the
+ optional, or conditional branches to handle each case distinctly:
+
+ ```swift
+ def tryToWobble(w : NSWobbling) {
+ w.wobble() // error: cannot call a value of optional type
+ w.wobble!() // okay: calls -wobble, but fails at runtime if not there
+ w.wobble?() // okay: calls -wobble only if it's there, otherwise no-op
+ if w.wobble {
+ // okay: we know -wobble is there
+ } else {
+ // okay: we know -wobble is not there
+ }
+ }
+ ```
+
+* Enums from Cocoa that are declared with the `NS_ENUM` macro are now imported
+ into Swift as Swift enums. Like all Swift enums, the constants of the Cocoa
+ enum are scoped as members of the enum type, so the importer strips off the
+ common prefix of all of the constant names in the enum when forming the Swift
+ interface. For example, this Objective-C declaration:
+
+ ```objc
+ typedef NS_ENUM(NSInteger, NSComparisonResult) {
+ NSOrderedAscending,
+ NSOrderedSame,
+ NSOrderedDescending,
+ };
+ ```
+
+ shows up in Swift as:
+
+ ```swift
+ enum NSComparisonResult : Int {
+ case Ascending, Same, Descending
+ }
+ ```
+
+ The `enum` cases can then take advantage of type inference from context.
+ In Objective-C, you would write:
+
+ ```objc
+ NSNumber *foo = [NSNumber numberWithInt: 1];
+ NSNumber *bar = [NSNumber numberWithInt: 2];
+
+ switch ([foo compare: bar]) {
+ case NSOrderedAscending:
+ NSLog(@"ascending\n");
+ break;
+ case NSOrderedSame:
+ NSLog(@"same\n");
+ break;
+ case NSOrderedDescending:
+ NSLog(@"descending\n");
+ break;
+ }
+ ```
+
+ In Swift, this becomes:
+
+ ```swift
+ var foo: NSNumber = 1
+ var bar: NSNumber = 2
+
+ switch foo.compare(bar) {
+ case .Ascending:
+ println("ascending")
+ case .Same:
+ println("same")
+ case .Descending:
+ println("descending")
+ }
+ ```
+
+* Work has begun on implementing static properties. Currently they are supported
+ for nongeneric structs and enums.
+
+ ```swift
+ struct Foo {
+ static var foo: Int = 2
+ }
+ enum Bar {
+ static var bar: Int = 3
+ }
+ println(Foo.foo)
+ println(Bar.bar)
+ ```
+
+2013-11-06
+----------
+
+* `func` keyword was changed to `def`.
+
+* Implicit conversions are now allowed from an optional type `T?` to another
+ optional type `U?` if `T` is implicitly convertible to `U`. For example,
+ optional subclasses convert to their optional base classes:
+
+ ```swift
+ class Base {}
+ class Derived : Base {}
+
+ var d: Derived? = Derived()
+ var b: Base? = d
+ ```
+
+2013-10-30
+----------
+
+* Type inference for variables has been improved, allowing any
+ variable to have its type inferred from its initializer, including
+ global and instance variables:
+
+ ```swift
+ class MyClass {
+ var size = 0 // inferred to Int
+ }
+
+ var name = "Swift"
+ ```
+
+ Additionally, the arguments of a generic type can also be inferred
+ from the initializer:
+
+ ```swift
+ // infers Dictionary
+ var dict: Dictionary = ["Hello": 1, "World": 2]
+ ```
+
+
+2013-10-23
+----------
+
+* Missing return statement from a non-`Void` function is diagnosed as an error.
+
+* `Vector` has been replaced with `Array`. This is a complete rewrite to use
+ value-semantics and copy-on-write behavior. The former means that you never
+ need to defensively copy again (or remember to attribute a property as "copy")
+ and the latter yields better performance than defensive copying. `Dictionary`
+ is next.
+
+* `switch` can now pattern-match into structs and classes, using the syntax
+ `case Type(property1: pattern1, property2: pattern2, ...):`.
+
+ ```swift
+ struct Point { var x, y: Double }
+ struct Size { var w, h: Double }
+ struct Rect { var origin: Point; var size: Size }
+
+ var square = Rect(Point(0, 0), Size(10, 10))
+
+ switch square {
+ case Rect(size: Size(w: var w, h: var h)) where w == h:
+ println("square")
+ case Rect(size: Size(w: var w, h: var h)) where w > h:
+ println("long rectangle")
+ default:
+ println("tall rectangle")
+ }
+ ```
+
+ Currently only stored properties ("ivars" in ObjC terminology) are
+ supported by the implementation.
+
+* Array and dictionary literals allow an optional trailing comma:
+
+ ```swift
+ var a = [ 1, 2, ]
+ var d = [ "a": 1, "b": 2, ]
+ ```
+
+2013-10-16
+----------
+* Unlike in Objective-C, objects of type `id` in Swift do not
+ implicitly convert to any class type. For example, the following
+ code is ill-formed:
+
+ ```swift
+ func getContentViewBounds(window : NSWindow) -> NSRect {
+ var view : NSView = window.contentView() // error: 'id' doesn't implicitly convert to NSView
+ return view.bounds()
+ }
+ ```
+
+ because `contentView()` returns an `id`. One can now use the postfix
+ `!` operator to allow an object of type `id` to convert to any class
+ type, e.g.,
+
+ ```swift
+ func getContentViewBounds(window : NSWindow) -> NSRect {
+ var view : NSView = window.contentView()! // ok: checked conversion to NSView
+ return view.bounds()
+ }
+ ```
+
+ The conversion is checked at run-time, and the program will fail if
+ the object is not an NSView. This is shorthand for
+
+ ```swift
+ var view : NSView = (window.contentView() as NSView)!
+ ```
+
+ which checks whether the content view is an `NSView` (via the `as
+ NSView`). That operation returns an optional `NSView` (written
+ `NSView?`) and the `!` operation assumes that the cast succeeded,
+ i.e., that the optional has a value in it.
+
+* The unconditional checked cast syntax `x as! T` has been removed. Many cases
+ where conversion from `id` is necessary can now be handled by postfix `!`
+ (see above). Fully general unconditional casts can still be expressed using
+ `as` and postfix `!` together, `(x as T)!`.
+
+* The old "square bracket" attribute syntax has been removed.
+
+* Overflows on construction of integer and floating point values from integer
+ literals that are too large to fit the type are now reported by the compiler.
+ Here are some examples:
+
+ ```swift
+ var x = Int8(-129)
+ // error: integer literal overflows when stored into 'Int8'
+
+ var y : Int = 0xFFFF_FFFF_FFFF_FFFF_F
+ // error: integer literal overflows when stored into 'Int'
+ ```
+
+ Overflows in constant integer expressions are also reported by the compiler.
+
+ ```swift
+ var x : Int8 = 125
+ var y : Int8 = x + 125
+ // error: arithmetic operation '125 + 125' (on type 'Int8') results in
+ // an overflow
+ ```
+
+* Division by zero in constant expressions is now detected by the compiler:
+
+ ```swift
+ var z: Int = 0
+ var x = 5 / z // error: division by zero
+ ```
+
+* Generic structs with type parameters as field types are now fully supported.
+
+ ```swift
+ struct Pair {
+ var first: T
+ var second: U
+ }
+ ```
+
+2013-10-09
+----------
+* Autorelease pools can now be created using the `autoreleasepool` function.
+
+ ```swift
+ autoreleasepool {
+ // code
+ }
+ ```
+
+ Note that the wrapped code is a closure, so constructs like `break` and
+ `continue` and `return` do not behave as they would inside an Objective-C
+ `@autoreleasepool` statement.
+
+* Enums can now declare a "raw type", and cases can declare "raw values",
+ similar to the integer underlying type of C enums:
+
+ ```swift
+ // Declare the underlying type as in Objective-C or C++11, with
+ // ': Type'
+ enum AreaCode : Int {
+ // Assign explicit values to cases with '='
+ case SanFrancisco = 415
+ case EastBay = 510
+ case Peninsula = 650
+ case SanJose = 408
+ // Values are also assignable by implicit auto-increment
+ case Galveston // = 409
+ case Baltimore // = 410
+ }
+ ```
+
+ This introduces `fromRaw` and `toRaw` methods on the enum to perform
+ conversions from and to the raw type:
+
+ ```swift
+ /* As if declared:
+ extension AreaCode {
+ // Take a raw value, and produce the corresponding enum value,
+ // or None if there is no corresponding enum value
+ static func fromRaw(raw:Int) -> AreaCode?
+
+
+ // Return the corresponding raw value for 'self'
+ func toRaw() -> Int
+ }
+ */
+
+ AreaCode.fromRaw(415) // => .Some(.SanFrancisco)
+ AreaCode.fromRaw(111) // => .None
+ AreaCode.SanJose.toRaw() // => 408
+ ```
+
+ Raw types are not limited to integer types--they can additionally be
+ character, floating-point, or string values:
+
+ ```swift
+ enum State : String {
+ case CA = "California"
+ case OR = "Oregon"
+ case WA = "Washington"
+ }
+
+ enum SquareRootOfInteger : Float {
+ case One = 1.0
+ case Two = 1.414
+ case Three = 1.732
+ case Four = 2.0
+ }
+ ```
+
+ Raw types are currently limited to simple C-like enums with no payload cases.
+ The raw values are currently restricted to simple literal values; expressions
+ such as `1 + 1` or references to other enum cases are not yet supported.
+ Raw values are also currently required to be unique for each case in an enum.
+
+ Enums with raw types implicitly conform to the `RawRepresentable` protocol,
+ which exposes the fromRaw and toRaw methods to generics:
+
+ ```swift
+ protocol RawRepresentable {
+ typealias RawType
+ static func fromRaw(raw: RawType) -> Self?
+ func toRaw() -> RawType
+ }
+ ```
+
+* Attribute syntax has been redesigned (see **(rdar://10700853)** and
+ **(rdar://14462729)**) so that attributes now precede the declaration and use
+ the `@` character to signify them. Where before you might have written:
+
+ ```swift
+ func [someattribute=42] foo(a : Int) {}
+ ```
+
+ you now write:
+
+ ```swift
+ @someattribute=42
+ func foo(a : Int) {}
+ ```
+
+ This flows a lot better (attributes don't push the name for declarations away),
+ and means that square brackets are only used for array types, collection
+ literals, and subscripting operations.
+
+* The `for` loop now uses the Generator protocol instead of the `Enumerator`
+ protocol to iterate a sequence. This protocol looks like this:
+
+ ```swift
+ protocol Generator {
+ typealias Element
+ func next() -> Element?
+ }
+ ```
+
+ The single method `next()` advances the generator and returns an
+ Optional, which is either `.Some(value)`, wrapping the next value out
+ of the underlying sequence, or `.None` to signal that there are no
+ more elements. This is an improvement over the previous Enumerator
+ protocol because it eliminates the separate `isEmpty()` query and
+ better reflects the semantics of ephemeral sequences like
+ un-buffered input streams.
+
+2013-10-02
+----------
+* The `[byref]` attribute has been renamed to `[inout]`. When applied to a logical
+ property, the getter is invoked before a call and the setter is applied to
+ write back the result. `inout` conveys this better and aligns with existing
+ Objective-C practice better.
+
+* `[inout]` arguments can now be captured into closures. The semantics of a
+ inout capture are that the captured variable is an independent local variable
+ of the callee, and the inout is updated to contain the value of that local
+ variable at function exit.
+
+ In the common case, most closure arguments do not outlive the duration of
+ their callee, and the observable behavior is unchanged. However, if the
+ captured variable outlives the function, you can observe this. For example,
+ this code:
+
+ ```swift
+ func foo(x : [inout] Int) -> () -> Int {
+ func bar() -> Int {
+ x += 1
+ return x
+ }
+ // Call 'bar' once while the inout is active.
+ bar()
+ return bar
+ }
+
+ var x = 219
+ var f = foo(&x)
+ // x is updated to the value of foo's local x at function exit.
+ println("global x = \(x)")
+ // These calls only update the captured local 'x', which is now independent
+ // of the inout parameter.
+ println("local x = \(f())")
+ println("local x = \(f())")
+ println("local x = \(f())")
+
+ println("global x = \(x)")
+ ```
+
+ will print:
+
+ ```
+ global x = 220
+ local x = 221
+ local x = 222
+ local x = 223
+ global x = 220
+ ```
+
+ In no case will you end up with a dangling pointer or other unsafe construct.
+
+* `x as T` now performs a checked cast to `T?`, producing `.Some(t)` if the
+ cast succeeds, or `.None` if the cast fails.
+
+* The ternary expression (`x ? y : z`) now requires whitespace between the
+ first expression and the question mark. This permits `?` to be used
+ as a postfix operator.
+
+* A significant new piece of syntactic sugar has been added to ease working
+ with optional values. The `?` postfix operator is analogous to `!`, but
+ instead of asserting on None, it causes all the following postfix
+ operators to get skipped and return `None`.
+
+ In a sense, this generalizes (and makes explicit) the Objective-C behavior
+ where message sends to `nil` silently produce the zero value of the result.
+
+ For example, this code
+
+ ```swift
+ object?.parent.notifyChildEvent?(object!, .didExplode)
+ ```
+
+ first checks whether `object` has a value; if so, it drills to its
+ parent and checks whether that object implements the `notifyChildEvent`
+ method; if so, it calls that method. (Note that we do not yet have
+ generalized optional methods.)
+
+ This code:
+
+ ```swift
+ var titleLength = object?.title.length
+ ```
+
+ checks whether `object` has a value and, if so, asks for the length of
+ its title. `titleLength` will have type `Int?`, and if `object` was
+ missing, the variable will be initialized to None.
+
+* Objects with type `id` can now be used as the receiver of property
+ accesses and subscript operations to get (but not set) values. The
+ result is of optional type. For example, for a variable `obj` of
+ type `id`, the expression
+
+ ```swift
+ obj[0]
+ ```
+
+ will produce a value of type `id`, which will either contain the
+ result of the message send objectAtIndexedSubscript(0) (wrapped in an
+ optional type) or, if the object does not respond to
+ `objectAtIndexedSubscript:`, an empty optional. The same approach
+ applies to property accesses.
+
+* `_` can now be used not only in `var` bindings, but in assignments as well,
+ to ignore elements of a tuple assignment, or to explicitly ignore values.
+
+ ```swift
+ var a = (1, 2.0, 3)
+ var x = 0, y = 0
+ _ = a // explicitly load and discard 'a'
+ (x, _, y) = a // assign a.0 to x and a.2 to y
+ ```
+
+2013-09-24
+----------
+* The `union` keyword has been replaced with `enum`. Unions and enums
+ are semantically identical in swift (the former just has data
+ associated with its discriminators) and `enum` is the vastly more
+ common case. For more rationale, please see
+ [docs/proposals/Enums.rst](https://github.com/apple/swift/blob/master/docs/proposals/Enums.rst)
+
+* The Optional type `T?` is now represented as an `enum`:
+
+ ```swift
+ enum Optional {
+ case None
+ case Some(T)
+ }
+ ```
+
+ This means that, in addition to the existing Optional APIs, it can be
+ pattern-matched with switch:
+
+ ```swift
+ var x : X?, y : Y?
+ switch (x, y) {
+ // Both are present
+ case (.Some(var a), .Some(var b)):
+ println("both")
+
+ // One is present
+ case (.Some, .None):
+ case (.None, .Some):
+ println("one")
+
+ // Neither is present
+ case (.None, .None):
+ println("neither")
+ }
+ ```
+
+* Enums now allow multiple cases to be declared in a comma-separated list
+ in a single `case` declaration:
+
+ ```swift
+ enum Color {
+ case Red, Green, Blue
+ }
+ ```
+
+* The Objective-C `id` and `Class` types now support referring to
+ methods declared in any class or protocol without a downcast. For
+ example, given a variable `sender` of type `id`, one can refer to
+ `-isEqual: with:`
+
+ ```swift
+ sender.isEqual
+ ```
+
+ The actual object may or may not respond to `-isEqual`, so this
+ expression returns result of optional type whose value is determined via a
+ compiler-generated `-respondsToSelector` send. When it succeeds, the
+ optional contains the method; when it fails, the optional is empty.
+
+ To safely test the optional, one can use, e.g.,
+
+ ```swift
+ var senderIsEqual = sender.isEqual
+ if senderIsEqual {
+ // this will never trigger an "unrecognized selector" failure
+ var equal = senderIsEqual!(other)
+ } else {
+ // sender does not respond to -isEqual:
+ }
+ ```
+
+ When you *know* that the method is there, you can use postfix `!` to
+ force unwrapping of the optional, e.g.,
+
+ ```swift
+ sender.isEqual!(other)
+ ```
+
+ This will fail at runtime if in fact sender does not respond to `-isEqual:`.
+ We have some additional syntactic optimizations planned for testing
+ an optional value and handling both the success and failure cases
+ concisely. Watch this space.
+
+* Weak references now always have optional type. If a weak variable
+ has an explicit type, it must be an optional type:
+
+ ```swift
+ var [weak] x : NSObject?
+ ```
+
+ If the variable is not explicitly typed, its type will still be
+ inferred to be an optional type.
+
+* There is now an implicit conversion from `T` to `T?`.
+
+2013-09-17
+----------
+* Constructor syntax has been improved to align better with
+ Objective-C's `init` methods. The `constructor` keyword has been
+ replaced with `init`, and the selector style of declaration used for
+ func declarations is now supported. For example:
+
+ ```swift
+ class Y : NSObject {
+ init withInt(i : Int) string(s : String) {
+ super.init() // call superclass initializer
+ }
+ }
+ ```
+
+ One can use this constructor to create a `Y` object with, e.g.,
+
+ ```swift
+ Y(withInt:17, string:"Hello")
+ ```
+
+ Additionally, the rules regarding the selector corresponding to such
+ a declaration have been revised. The selector for the above
+ initializer is `initWithInt:string:`; the specific rules are
+ described in the documentation.
+
+ Finally, Swift initializers now introduce Objective-C entry points,
+ so a declaration such as:
+
+ ```swift
+ class X : NSObject {
+ init() {
+ super.init()
+ }
+ }
+ ```
+
+ Overrides `NSObject`'s `-init` method (which it calls first) as well
+ as introducing the 'allocating' entry point so that one can create a
+ new `X` instance with the syntax `X()`.
+
+* Variables in top-level code (i.e. scripts, but not global variables in
+ libraries) that lack an initializer now work just like local variables:
+ they must be explicitly assigned-to sometime before any use, instead of
+ being default constructed. Instance variables are still on the TODO
+ list.
+
+* Generic unions with a single payload case and any number of empty cases
+ are now implemented, for example:
+
+ ```swift
+ union Maybe {
+ case Some(T)
+ case None
+ }
+
+ union Tristate {
+ case Initialized(T)
+ case Initializing
+ case Uninitialized
+ }
+ ```
+
+ Generic unions with multiple payload cases are still not yet implemented.
+
+2013-09-11
+----------
+* The implementation now supports partial application of class and struct
+ methods:
+
+ ```swift
+ (swift) class B { func foo() { println("B") } }
+ (swift) class D : B { func foo() { println("D") } }
+ (swift) var foo = B().foo
+ // foo : () -> () =
+ (swift) foo()
+ B
+ (swift) foo = D().foo
+ (swift) foo()
+ D
+ ```
+
+ Support for partial application of Objective-C class methods and methods in
+ generic contexts is still incomplete.
+
+2013-09-04
+----------
+* Local variable declarations without an initializer are no longer implicitly
+ constructed. The compiler now verifies that they are initialized on all
+ paths leading to a use of the variable. This means that constructs like this
+ are now allowed:
+
+ ```swift
+ var p : SomeProtocol
+ if whatever {
+ p = foo()
+ } else {
+ p = bar()
+ }
+ ```
+
+ where before, the compiler would reject the definition of `p` saying that it
+ needed an initializer expression.
+
+ Since all local variables must be initialized before use, simple things like
+ this are now rejected as well:
+
+ ```swift
+ var x : Int
+ print(x)
+ ```
+
+ The fix is to initialize the value on all paths, or to explicitly default
+ initialize the value in the declaration, e.g. with `var x = 0` or with
+ `var x = Int()` (which works for any default-constructible type).
+
+* The implementation now supports unions containing protocol types and weak
+ reference types.
+
+* The type annotation syntax, `x as T`, has been removed from the language.
+ The checked cast operations `x as! T` and `x is T` still remain.
+
+2013-08-28
+----------
+* `this` has been renamed to `self`. Similarly, `This` has been renamed to
+ `Self`.
+
+* Swift now supports unions. Unlike C unions, Swift's `union` is type-safe
+ and always knows what type it contains at runtime. Union members are labeled
+ using `case` declarations; each case may have a different set of
+ types or no type:
+
+ ```swift
+ union MaybeInt {
+ case Some(Int)
+ case None
+ }
+
+ union HTMLTag {
+ case A(href:String)
+ case IMG(src:String, alt:String)
+ case BR
+ }
+ ```
+
+ Each `case` with a type defines a static constructor function for the union
+ type. `case` declarations without types become static members:
+
+ ```swift
+ var br = HTMLTag.BR
+ var a = HTMLTag.A(href:"http://www.apple.com/")
+ // 'HTMLTag' scope deduced for '.IMG' from context
+ var img : HTMLTag = .IMG(src:"http://www.apple.com/mac-pro.png",
+ alt:"The new Mac Pro")
+ ```
+
+ Cases can be pattern-matched using `switch`:
+
+ ```swift
+ switch tag {
+ case .BR:
+ println("
")
+ case .IMG(var src, var alt):
+ println("
")
+ case .A(var href):
+ println("")
+ }
+ ```
+
+ Due to implementation limitations, recursive unions are not yet supported.
+
+* Swift now supports autolinking, so importing frameworks or Swift libraries
+ should no longer require adding linker flags or modifying your project file.
+
+2013-08-14
+----------
+* Swift now supports weak references by applying the `[weak]` attribute to a
+ variable declaration.
+
+ ```swift
+ (swift) var x = NSObject()
+ // x : NSObject =
+ (swift) var [weak] w = x
+ // w : NSObject =
+ (swift) w == nil
+ // r2 : Bool = false
+ (swift) x = NSObject()
+ (swift) w == nil
+ // r3 : Bool = true
+ ```
+
+ Swift also supports a special form of weak reference, called `[unowned]`, for
+ references that should never be nil but are required to be weak to break
+ cycles, such as parent or sibling references. Accessing an `[unowned]`
+ reference asserts that the reference is still valid and implicitly promotes
+ the loaded reference to a strong reference, so it does not need to be loaded
+ and checked for nullness before use like a true `[weak]` reference.
+
+ ```swift
+ class Parent {
+ var children : Array
+
+ func addChild(c:Child) {
+ c.parent = this
+ children.append(c)
+ }
+ }
+
+ class Child {
+ var [unowned] parent : Parent
+ }
+ ```
+
+2013-07-31
+----------
+* Numeric literals can now use underscores as separators. For example:
+
+ ```swift
+ var billion = 1_000_000_000
+ var crore = 1_00_00_000
+ var MAXINT = 0x7FFF_FFFF_FFFF_FFFF
+ var SMALLEST_DENORM = 0x0.0000_0000_0000_1p-1022
+ ```
+
+* Types conforming to protocols now must always declare the conformance in
+ their inheritance clause.
+
+* The build process now produces serialized modules for the standard library,
+ greatly improving build times.
+
+2013-07-24
+----------
+* Arithmetic operators `+`, `-`, `*`, and `/` on integer types now do
+ overflow checking and trap on overflow. A parallel set of masking operators,
+ `&+`, `&-`, `&*`, and `&/`, are defined to perform two's complement wrapping
+ arithmetic for all signed and unsigned integer types.
+
+* Debugger support. Swift has a `-g` command line switch that turns on
+ debug info for the compiled output. Using the standard lldb debugger
+ this will allow single-stepping through Swift programs, printing
+ backtraces, and navigating through stack frames; all in sync with
+ the corresponding Swift source code. An unmodified lldb cannot
+ inspect any variables.
+
+ Example session:
+
+ ```
+ $ echo 'println("Hello World")' >hello.swift
+ $ swift hello.swift -c -g -o hello.o
+ $ ld hello.o "-dynamic" "-arch" "x86_64" "-macosx_version_min" "10.9.0" \
+ -framework Foundation lib/swift/libswift_stdlib_core.dylib \
+ lib/swift/libswift_stdlib_posix.dylib -lSystem -o hello
+ $ lldb hello
+ Current executable set to 'hello' (x86_64).
+ (lldb) b top_level_code
+ Breakpoint 1: where = hello`top_level_code + 26 at hello.swift:1, addre...
+ (lldb) r
+ Process 38592 launched: 'hello' (x86_64)
+ Process 38592 stopped
+ * thread #1: tid = 0x1599fb, 0x0000000100000f2a hello`top_level_code + ...
+ frame #0: 0x0000000100000f2a hello`top_level_code + 26 at hello.shi...
+ -> 1 println("Hello World")
+ (lldb) bt
+ * thread #1: tid = 0x1599fb, 0x0000000100000f2a hello`top_level_code + ...
+ frame #0: 0x0000000100000f2a hello`top_level_code + 26 at hello.shi...
+ frame #1: 0x0000000100000f5c hello`main + 28
+ frame #2: 0x00007fff918605fd libdyld.dylib`start + 1
+ frame #3: 0x00007fff918605fd libdyld.dylib`start + 1
+ ```
+
+ Also try `s`, `n`, `up`, `down`.
+
+2013-07-17
+----------
+* Swift now has a `switch` statement, supporting pattern matching of
+ multiple values with variable bindings, guard expressions, and range
+ comparisons. For example:
+
+ ```swift
+ func classifyPoint(point:(Int, Int)) {
+ switch point {
+ case (0, 0):
+ println("origin")
+
+ case (_, 0):
+ println("on the x axis")
+
+ case (0, _):
+ println("on the y axis")
+
+ case (var x, var y) where x == y:
+ println("on the y = x diagonal")
+
+ case (var x, var y) where -x == y:
+ println("on the y = -x diagonal")
+
+ case (-10..10, -10..10):
+ println("close to the origin")
+
+ case (var x, var y):
+ println("length \(sqrt(x*x + y*y))")
+ }
+ }
+ ```
+
+2013-07-10
+----------
+* Swift has a new closure syntax. The new syntax eliminates the use of
+ pipes. Instead, the closure signature is written the same way as a
+ function type and is separated from the body by the `in`
+ keyword. For example:
+
+ ```swift
+ sort(fruits) { (lhs : String, rhs : String) -> Bool in
+ return lhs > rhs
+ }
+ ```
+
+ When the types are omitted, one can also omit the parentheses, e.g.,
+
+ ```swift
+ sort(fruits) { lhs, rhs in lhs > rhs }
+ ```
+
+ Closures with no parameters or that use the anonymous parameters
+ (`$0`, `$1`, etc.) don't need the `in`, e.g.,
+
+ ```swift
+ sort(fruits) { $0 > $1 }
+ ```
+
+* `nil` can now be used without explicit casting. Previously, `nil` had
+ type `NSObject`, so one would have to write (e.g.) `nil as! NSArray`
+ to create a `nil` `NSArray`. Now, `nil` picks up the type of its
+ context.
+
+* `POSIX.EnvironmentVariables` and `swift.CommandLineArguments` global variables
+ were merged into a `swift.Process` variable. Now you can access command line
+ arguments with `Process.arguments`. In order to access environment variables
+ add `import POSIX` and use `Process.environmentVariables`.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0acafae8e4864..8a96d44f4c37e 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -44,9 +44,9 @@ option(SWIFT_BUILD_STATIC_STDLIB
"Build static variants of the Swift standard library and SDK overlay"
FALSE)
-option(SWIFT_INCLUDE_BENCHMARKS
- "Create targets for running swift benchmarks"
- TRUE)
+option(SWIFT_BUILD_PERF_TESTSUITE
+ "Create targets for swift performance benchmarks."
+ FALSE)
option(SWIFT_INCLUDE_TESTS "Create targets for building/running tests." TRUE)
@@ -54,10 +54,6 @@ option(SWIFT_INCLUDE_DOCS
"Create targets for building docs."
TRUE)
-option(SWIFT_ENABLE_TARGET_LINUX
- "Enable compiler support for targeting Linux"
- TRUE)
-
set(SWIFT_VERSION "2.2" CACHE STRING
"The user-visible version of the Swift compiler")
set(SWIFT_VENDOR "" CACHE STRING
@@ -73,7 +69,7 @@ set(SWIFT_ENABLE_GOLD_LINKER FALSE CACHE BOOL
"Enable using the gold linker when available")
set(_SWIFT_KNOWN_INSTALL_COMPONENTS
- "compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;stdlib;stdlib-experimental;sdk-overlay;editor-integration;tools;testsuite-tools;dev;sourcekit-xpc-service;sourcekit-inproc")
+ "compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;stdlib;stdlib-experimental;sdk-overlay;editor-integration;tools;testsuite-tools;dev;license;sourcekit-xpc-service;sourcekit-inproc")
# Set the SWIFT_INSTALL_COMPONENTS variable to the default value if it is not passed in via -D
set(SWIFT_INSTALL_COMPONENTS "${_SWIFT_KNOWN_INSTALL_COMPONENTS}" CACHE STRING
@@ -153,6 +149,9 @@ option(SWIFT_RUNTIME_CRASH_REPORTER_CLIENT
"Whether to enable CrashReporter integration"
FALSE)
+set(SWIFT_DARWIN_XCRUN_TOOLCHAIN "XcodeDefault" CACHE STRING
+ "The name of the toolchain to pass to 'xcrun'")
+
set(SWIFT_DARWIN_ICU_INCLUDE_PATH "" CACHE STRING
"Path to the directory where the ICU headers are located")
@@ -208,11 +207,7 @@ set(SWIFT_EXPERIMENTAL_EXTRA_REGEXP_FLAGS "" CACHE STRING
"A list of [module_regexp1;flags1;module_regexp2;flags2,...] which can be used to apply specific flags to modules that match a cmake regexp. It always applies the first regexp that matches.")
set(SWIFT_EXPERIMENTAL_EXTRA_NEGATIVE_REGEXP_FLAGS "" CACHE STRING
- "A list of [module_regexp1;flags1;module_regexp2;flags2,...] which can be used to apply specific flags to modules that do not match a cmake regexp. It always applies the first regexp that does not matche. The reason this is necessary is that cmake does not provide negative matches in the regex. Instead you have to use NOT in the if statement requiring a separate variable.")
-
-option(SWIFT_RUNTIME_ENABLE_DTRACE
- "Should the runtime be built with dtrace instrumentation enabled"
- FALSE)
+ "A list of [module_regexp1;flags1;module_regexp2;flags2,...] which can be used to apply specific flags to modules that do not match a cmake regexp. It always applies the first regexp that does not match. The reason this is necessary is that cmake does not provide negative matches in the regex. Instead you have to use NOT in the if statement requiring a separate variable.")
option(SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
"Should the runtime be built with support for non-thread-safe leak detecting entrypoints"
@@ -250,9 +245,6 @@ endif()
option(SWIFT_BUILD_SOURCEKIT
"Build SourceKit"
${SWIFT_BUILD_SOURCEKIT_default})
-# Force updating the cache, remove the following after a couple of weeks or so.
-set(SWIFT_BUILD_SOURCEKIT ${SWIFT_BUILD_SOURCEKIT_default}
- CACHE BOOL "Build SourceKit" FORCE)
#
# Include CMake modules
@@ -313,7 +305,7 @@ if(NOT EXISTS "${CLANG_MAIN_INCLUDE_DIR}/clang/AST/Decl.h")
endif()
# This could be computed using ${CMAKE_CFG_INTDIR} if we want to link Swift
-# against a mathing LLVM build configuration. However, we usually want to be
+# against a matching LLVM build configuration. However, we usually want to be
# flexible and allow linking a debug Swift against optimized LLVM.
set(LLVM_RUNTIME_OUTPUT_INTDIR "${LLVM_BINARY_DIR}")
set(LLVM_LIBRARY_OUTPUT_INTDIR "${LLVM_LIBRARY_DIR}")
@@ -419,27 +411,63 @@ if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
"Deployment OS for Swift host tools (the compiler) [linux].")
set(SWIFT_HOST_VARIANT_SDK "LINUX")
- set(SWIFT_HOST_VARIANT_ARCH "x86_64")
- set(swift_can_crosscompile_stdlib TRUE)
+ set(SWIFT_PRIMARY_VARIANT_SDK_default "LINUX")
- is_sdk_requested(LINUX swift_build_linux)
- if(swift_build_linux)
- configure_sdk_unix(LINUX "Linux" "linux" "linux" "x86_64" "x86_64-unknown-linux-gnu")
- set(SWIFT_PRIMARY_VARIANT_SDK_default "LINUX")
- set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
- endif()
+ # FIXME: This will not work while trying to cross-compile.
+ if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
+ set(SWIFT_HOST_VARIANT_ARCH "x86_64")
+ set(swift_can_crosscompile_stdlib TRUE)
- is_sdk_requested(ANDROID swift_build_android)
- if(swift_build_android AND ${swift_can_crosscompile_stdlib})
- if("${SWIFT_ANDROID_NDK_PATH}" STREQUAL "")
- message(FATAL_ERROR "environmental variable ANDROID_NDK_HOME not set")
+ is_sdk_requested(LINUX swift_build_linux)
+ if(swift_build_linux)
+ configure_sdk_unix(LINUX "Linux" "linux" "linux" "x86_64" "x86_64-unknown-linux-gnu")
+ set(SWIFT_PRIMARY_VARIANT_SDK_default "LINUX")
+ set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
endif()
- configure_sdk_unix(ANDROID "Android" "android" "android" "armv7" "armv7-none-linux-androideabi")
- set(SWIFT_SDK_ANDROID_PATH "${SWIFT_ANDROID_NDK_PATH}/platforms/android-16/arch-arm")
- set(SWIFT_PRIMARY_VARIANT_SDK_default "ANDROID")
+ is_sdk_requested(ANDROID swift_build_android)
+ if(swift_build_android AND ${swift_can_crosscompile_stdlib})
+ if("${SWIFT_ANDROID_NDK_PATH}" STREQUAL "")
+ message(FATAL_ERROR "environmental variable ANDROID_NDK_HOME not set")
+ endif()
+ configure_sdk_unix(ANDROID "Android" "android" "android" "armv7" "armv7-none-linux-androideabi")
+ set(SWIFT_SDK_ANDROID_PATH "${SWIFT_ANDROID_NDK_PATH}/platforms/android-16/arch-arm")
+
+ set(SWIFT_PRIMARY_VARIANT_SDK_default "ANDROID")
+ set(SWIFT_PRIMARY_VARIANT_ARCH_default "armv7")
+ endif()
+ # FIXME: This only matches ARMv7l (by far the most common variant).
+ elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l")
+ configure_sdk_unix(LINUX "Linux" "linux" "linux" "armv7" "armv7-unknown-linux-gnueabihf")
+ set(SWIFT_HOST_VARIANT_ARCH "armv7")
set(SWIFT_PRIMARY_VARIANT_ARCH_default "armv7")
+ elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")
+ configure_sdk_unix(LINUX "Linux" "linux" "linux" "aarch64" "aarch64-unknown-linux-gnu")
+ set(SWIFT_HOST_VARIANT_ARCH "aarch64")
+ set(SWIFT_PRIMARY_VARIANT_ARCH_default "aarch64")
+ else()
+ message(FATAL_ERROR "Unknown or unsupported architecture: ${CMAKE_SYSTEM_PROCESSOR}")
endif()
+
+elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD")
+ # FIXME: Using the host OS version won't produce correct results for
+ # cross-compilation.
+ string(REPLACE "[-].*" "" FREEBSD_SYSTEM_VERSION ${CMAKE_SYSTEM_VERSION})
+ message(STATUS "FreeBSD Version: ${FREEBSD_SYSTEM_VERSION}")
+ configure_sdk_unix(FREEBSD "FreeBSD" "freebsd" "freebsd" "x86_64"
+ "x86_64-unknown-freebsd${FREEBSD_SYSTEM_VERSION}")
+
+ set(CMAKE_EXECUTABLE_FORMAT "ELF")
+
+ set(SWIFT_HOST_VARIANT "freebsd" CACHE STRING
+ "Deployment OS for Swift host tools (the compiler) [freebsd].")
+
+ set(SWIFT_HOST_VARIANT_SDK "FREEBSD")
+ set(SWIFT_HOST_VARIANT_ARCH "x86_64")
+ set(swift_can_crosscompile_stdlib TRUE)
+
+ set(SWIFT_PRIMARY_VARIANT_SDK_default "FREEBSD")
+ set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
# Set defaults.
@@ -472,7 +500,7 @@ elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
endif()
if(XCODE)
- # FIXME: Can not cross-compile stdlib using Xcode. Xcode insists on
+ # FIXME: Cannot cross-compile stdlib using Xcode. Xcode insists on
# passing -mmacosx-version-min to the compiler, and we want to pass
# -mios-version-min. Clang sees both options and complains.
set(swift_can_crosscompile_stdlib FALSE)
@@ -644,7 +672,7 @@ if(SWIFT_BUILD_TOOLS)
endif()
add_subdirectory(utils)
add_subdirectory(stdlib)
-if(SWIFT_INCLUDE_BENCHMARKS)
+if(SWIFT_BUILD_PERF_TESTSUITE)
add_subdirectory(benchmark)
endif()
if(SWIFT_INCLUDE_TESTS)
@@ -655,6 +683,10 @@ if(SWIFT_INCLUDE_DOCS)
add_subdirectory(docs)
endif()
+swift_install_in_component(license
+ FILES "LICENSE.txt"
+ DESTINATION "share/swift")
+
# Add a documentation target so that documentation shows up in the
# Xcode project.
if(XCODE)
diff --git a/CODE_OWNERS.TXT b/CODE_OWNERS.TXT
index 44dec800ed348..1079da5537579 100644
--- a/CODE_OWNERS.TXT
+++ b/CODE_OWNERS.TXT
@@ -46,7 +46,7 @@ D: ClangImporter, Serialization, (Objective-)C printer, Driver
N: Nadav Rotem
E: nrotem@apple.com
-D: SILAnalysis, SILPasses
+D: SILOptimizer
N: Anna Zaks
E: ganna@apple.com
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000000..e36bf969f0cb9
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,10 @@
+By submitting a pull request, you represent that you have the right to license
+your contribution to Apple and the community, and agree by submitting the patch
+that your contributions are licensed under the [Swift
+license](https://swift.org/LICENSE.txt).
+
+---
+
+Before submitting the pull request, please make sure you have tested your
+changes and that they follow the Swift project [guidelines for contributing
+code](https://swift.org/contributing/#contributing-code).
diff --git a/README.md b/README.md
index 92453e38082f0..070dd10827e2d 100644
--- a/README.md
+++ b/README.md
@@ -1,37 +1,33 @@
+
# Swift Programming Language
**Welcome to Swift!**
Swift is a high-performance system programming language. It has a clean
-and modern syntax, and offers seamless access to existing C and Objective-C code
+and modern syntax, offers seamless access to existing C and Objective-C code
and frameworks, and is memory safe (by default).
Although inspired by Objective-C and many other languages, Swift is not itself a
C-derived language. As a complete and independent language, Swift packages core
features like flow control, data structures, and functions, with high-level
-constructs like objects, protocols, closures, and generics. Swift embraces
+constructs like objects, protocols, closures, and generics. Swift embraces
modules, eliminating the need for headers and the code duplication they entail.
## Documentation
-To read the documentation, start by installing the Sphinx documentation
-generator tool (http://sphinx-doc.org, just run `easy_install -U Sphinx` from
-the command line and you're good to go). Once you have that, you can build the
-Swift documentation by going into `docs` and typing `make`. This compiles
-the `.rst` files in the `docs` directory into HTML in the `docs/_build/html`
-directory.
-
-Once built, the best place to start is with the Swift white paper, which gives a
-tour of the language (in `docs/_build/html/whitepaper/index.html`).
-Another potentially useful document is `docs/LangRef`, which gives a low level
-tour of how the language works from the implementation perspective.
+To read the documentation, start by installing the
+[Sphinx](http://sphinx-doc.org) documentation generator tool (just run
+`easy_install -U Sphinx` from the command line and you're good to go). Once you
+ have that, you can build the Swift documentation by going into `docs` and
+typing `make`. This compiles the `.rst` files in the `docs` directory into
+HTML in the `docs/_build/html` directory.
Many of the docs are out of date, but you can see some historical design
documents in the `docs` directory.
Another source of documentation is the standard library itself, located in
-`stdlib`. Much of the language is actually implemented in the library
+`stdlib`. Much of the language is actually implemented in the library
(including `Int`), and the standard library gives some examples of what can be
expressed today.
@@ -39,7 +35,7 @@ expressed today.
## Getting Started
These instructions give the most direct path to a working Swift
-development environment. Options for doing things differently are
+development environment. Options for doing things differently are
discussed below.
@@ -52,7 +48,7 @@ For OS X, you need [the latest Xcode](https://developer.apple.com/xcode/download
For Ubuntu, you'll need the following development dependencies:
- sudo apt-get install git cmake ninja-build clang uuid-dev libicu-dev icu-devtools libbsd-dev libedit-dev libxml2-dev libsqlite3-dev swig libpython-dev libncurses5-dev pkg-config
+ sudo apt-get install git cmake ninja-build clang python uuid-dev libicu-dev icu-devtools libbsd-dev libedit-dev libxml2-dev libsqlite3-dev swig libpython-dev libncurses5-dev pkg-config
Note: LLDB currently requires at least swig-1.3.40 but will successfully build
with version 2 shipped with Ubuntu.
@@ -60,37 +56,25 @@ with version 2 shipped with Ubuntu.
If you are building on Ubuntu 14.04 LTS, you'll need to upgrade your clang
compiler for C++14 support and create a symlink:
- sudo apt-get install clang-3.6
- sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100
- sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100
+ sudo apt-get install clang-3.6
+ sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100
+ sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100
### Getting Sources for Swift and Related Projects
- For those checking out sources as read-only:
-
- git clone https://github.com/apple/swift.git swift
- git clone https://github.com/apple/swift-llvm.git llvm
- git clone https://github.com/apple/swift-clang.git clang
- git clone https://github.com/apple/swift-lldb.git lldb
- git clone https://github.com/apple/swift-cmark.git cmark
- git clone https://github.com/apple/swift-llbuild.git llbuild
- git clone https://github.com/apple/swift-package-manager.git swiftpm
- git clone https://github.com/apple/swift-corelibs-xctest.git
- git clone https://github.com/apple/swift-corelibs-foundation.git
-
- For those who plan on regular making direct commits, cloning over
- SSH may provide a better experience (which requires uploading
- SSH keys to GitHub):
-
- git clone git@github.com:apple/swift.git swift
- git clone git@github.com:apple/swift-llvm.git llvm
- git clone git@github.com:apple/swift-clang.git clang
- git clone git@github.com:apple/swift-lldb.git lldb
- git clone git@github.com:apple/swift-cmark.git cmark
- git clone git@github.com:apple/swift-llbuild.git llbuild
- git clone git@github.com:apple/swift-package-manager.git swiftpm
- git clone git@github.com:apple/swift-corelibs-xctest.git
- git clone git@github.com:apple/swift-corelibs-foundation.git
+**Via HTTPS** For those checking out sources as read-only, HTTPS works best:
+
+ git clone https://github.com/apple/swift.git
+ cd swift
+ ./utils/update-checkout --clone
+
+**Via SSH** For those who plan on regularly making direct commits,
+cloning over SSH may provide a better experience (which requires
+uploading SSH keys to GitHub):
+
+ git clone git@github.com:apple/swift.git
+ cd swift
+ ./utils/update-checkout --clone-with-ssh
[CMake](http://cmake.org) is the core infrastructure used to configure builds of
Swift and its companion projects; at least version 2.8.12.2 is required. Your
@@ -106,7 +90,11 @@ for building Swift and is the default configuration generated by CMake. If
you're on OS X or don't install it as part of your Linux distribution, clone
it next to the other projects and it will be bootstrapped automatically:
- git clone git@github.com:martine/ninja.git
+ git clone https://github.com/ninja-build/ninja.git
+
+or
+
+ git clone git@github.com:ninja-build/ninja.git
You can also install CMake and Ninja on OS X using a third-party
packaging tool like [Homebrew](http://brew.sh)…
diff --git a/apinotes/README.md b/apinotes/README.md
index f5d8858d4dedf..f954eeb7c551d 100644
--- a/apinotes/README.md
+++ b/apinotes/README.md
@@ -25,7 +25,7 @@ Swift signatures of imported Objective-C APIs. Compiled API notes
files reside in the Swift module directory, i.e., the same directory
where the `.swiftmodule` file would reside for the Swift overlay of
that module. For system modules, the path depends on the platform
-and architecture
+and architecture.
Platform | Path
:------------- | :-------------
diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt
index 1f274ff04b08d..7ef0477f168db 100644
--- a/benchmark/CMakeLists.txt
+++ b/benchmark/CMakeLists.txt
@@ -1,16 +1,10 @@
-option(SWIFT_INCLUDE_PERF_TESTSUITE "Create targets for swift performance benchmarks." NO)
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
# Performance test harness only builds on Darwin.
- if (SWIFT_INCLUDE_PERF_TESTSUITE)
- set(PERF_TESTSUITE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/PerfTestSuite" CACHE STRING "Path to swift performance testsuite repo.")
- if(EXISTS ${PERF_TESTSUITE_DIR}/CMakeLists.txt)
- add_subdirectory(${PERF_TESTSUITE_DIR})
- else()
- message(FATAL_ERROR "Can't find the Swift performance suite at ${PERF_TESTSUITE_DIR}/.")
- endif()
- add_custom_target(benchmark-swift
- DEPENDS benchmark-swift PerfTests_Onone PerfTests_O
- PerfTests_Ounchecked)
+ set(PERF_TESTSUITE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/PerfTestSuite" CACHE STRING "Path to swift performance testsuite repo.")
+ if(EXISTS ${PERF_TESTSUITE_DIR}/CMakeLists.txt)
+ add_subdirectory(${PERF_TESTSUITE_DIR})
+ else()
+ message(FATAL_ERROR "Can't find the Swift performance suite at ${PERF_TESTSUITE_DIR}/.")
endif()
endif()
diff --git a/bindings/xml/comment-xml-schema.rng b/bindings/xml/comment-xml-schema.rng
index 6ee793715ff33..468efa042537e 100644
--- a/bindings/xml/comment-xml-schema.rng
+++ b/bindings/xml/comment-xml-schema.rng
@@ -767,6 +767,9 @@
+
+
+
diff --git a/cmake/modules/AddSwift.cmake b/cmake/modules/AddSwift.cmake
index 14a5b68c6a524..64f6659fbdade 100644
--- a/cmake/modules/AddSwift.cmake
+++ b/cmake/modules/AddSwift.cmake
@@ -14,6 +14,15 @@ function(_list_add_string_suffix input_list suffix result_var_name)
set("${result_var_name}" "${result}" PARENT_SCOPE)
endfunction()
+function(_list_escape_for_shell input_list result_var_name)
+ set(result "")
+ foreach(element ${input_list})
+ string(REPLACE " " "\\ " element "${element}")
+ set(result "${result}${element} ")
+ endforeach()
+ set("${result_var_name}" "${result}" PARENT_SCOPE)
+endfunction()
+
function(add_dependencies_multiple_targets)
cmake_parse_arguments(
ADMT # prefix
@@ -163,6 +172,8 @@ function(_add_variant_link_flags
if("${sdk}" STREQUAL "LINUX")
list(APPEND result "-lpthread" "-ldl" "${BSD_LIBRARIES}")
+ elseif("${sdk}" STREQUAL "FREEBSD")
+ # No extra libraries required.
elseif("${sdk}" STREQUAL "ANDROID")
list(APPEND result
"-Wl,-Bsymbolic"
@@ -1107,18 +1118,19 @@ function(_add_swift_library_single target name)
set(PLIST_INFO_BUILD_VERSION)
endif()
- # On Linux add the linker script that coalesces protocol conformance
- # sections. This wouldn't be necessary if the link was done by the swift
- # binary: rdar://problem/19007002
- if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
+ # On Linux and FreeBSD add the linker script that coalesces protocol
+ # conformance sections. This wouldn't be necessary if the link was done by
+ # the swift binary: rdar://problem/19007002
+ if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux" OR
+ "${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD")
list(APPEND link_flags
"-Xlinker" "-T"
"-Xlinker" "${SWIFTLIB_DIR}/${SWIFTLIB_SINGLE_SUBDIR}/swift.ld")
endif()
# Convert variables to space-separated strings.
- string(REPLACE ";" " " c_compile_flags "${c_compile_flags}")
- string(REPLACE ";" " " link_flags "${link_flags}")
+ _list_escape_for_shell("${c_compile_flags}" c_compile_flags)
+ _list_escape_for_shell("${link_flags}" link_flags)
# Set compilation and link flags.
set_property(TARGET "${target}" APPEND_STRING PROPERTY
@@ -1686,8 +1698,8 @@ function(_add_swift_executable_single name)
llvm_update_compile_flags("${name}")
# Convert variables to space-separated strings.
- string(REPLACE ";" " " c_compile_flags "${c_compile_flags}")
- string(REPLACE ";" " " link_flags "${link_flags}")
+ _list_escape_for_shell("${c_compile_flags}" c_compile_flags)
+ _list_escape_for_shell("${link_flags}" link_flags)
set_property(TARGET ${name} APPEND_STRING PROPERTY
COMPILE_FLAGS " ${c_compile_flags}")
@@ -1854,37 +1866,3 @@ function(add_swift_executable name)
${SWIFTEXE_DONT_STRIP_NON_MAIN_SYMBOLS_FLAG}
${SWIFTEXE_DISABLE_ASLR_FLAG})
endfunction()
-
-function(add_swift_llvm_loadable_module name)
- add_llvm_loadable_module(${name} ${ARGN})
- set(sdk "${SWIFT_HOST_VARIANT_SDK}")
- set(arch "${SWIFT_HOST_VARIANT_ARCH}")
-
- # Determine compiler flags.
- set(c_compile_flags)
- _add_variant_c_compile_flags(
- "${sdk}"
- "${arch}"
- "${CMAKE_BUILD_TYPE}"
- "${LLVM_ENABLE_ASSERTIONS}"
- FALSE
- c_compile_flags)
-
- set(link_flags)
- _add_variant_link_flags(
- "${sdk}"
- "${arch}"
- "${CMAKE_BUILD_TYPE}"
- "${LLVM_ENABLE_ASSERTIONS}"
- FALSE
- link_flags)
-
- # Convert variables to space-separated strings.
- string(REPLACE ";" " " c_compile_flags "${c_compile_flags}")
- string(REPLACE ";" " " link_flags "${link_flags}")
-
- set_property(TARGET ${name} APPEND_STRING PROPERTY
- COMPILE_FLAGS " ${c_compile_flags}")
- set_property(TARGET ${name} APPEND_STRING PROPERTY
- LINK_FLAGS " ${link_flags}")
-endfunction()
diff --git a/cmake/modules/SwiftSetIfArchBitness.cmake b/cmake/modules/SwiftSetIfArchBitness.cmake
index 22617ff68399e..83d80533f6792 100644
--- a/cmake/modules/SwiftSetIfArchBitness.cmake
+++ b/cmake/modules/SwiftSetIfArchBitness.cmake
@@ -12,7 +12,8 @@ function(set_if_arch_bitness var_name)
"${SIA_ARCH}" STREQUAL "armv7s")
set("${var_name}" "${SIA_CASE_32_BIT}" PARENT_SCOPE)
elseif("${SIA_ARCH}" STREQUAL "x86_64" OR
- "${SIA_ARCH}" STREQUAL "arm64")
+ "${SIA_ARCH}" STREQUAL "arm64" OR
+ "${SIA_ARCH}" STREQUAL "aarch64")
set("${var_name}" "${SIA_CASE_64_BIT}" PARENT_SCOPE)
else()
message(FATAL_ERROR "Unknown architecture: ${SIA_ARCH}")
diff --git a/docs/ABI.rst b/docs/ABI.rst
index 30f570f91dd32..dd34104149dc5 100644
--- a/docs/ABI.rst
+++ b/docs/ABI.rst
@@ -743,15 +743,17 @@ Globals
global ::= 'PA' .* // partial application forwarder
global ::= 'PAo' .* // ObjC partial application forwarder
global ::= 'w' value-witness-kind type // value witness
- global ::= 'WV' type // value witness table
- global ::= 'Wo' entity // witness table offset
- global ::= 'Wv' directness entity // field offset
- global ::= 'WP' protocol-conformance // protocol witness table
global ::= 'Wa' protocol-conformance // protocol witness table accessor
+ global ::= 'WG' protocol-conformance // generic protocol witness table
+ global ::= 'WI' protocol-conformance // generic protocol witness table instantiation function
global ::= 'Wl' type protocol-conformance // lazy protocol witness table accessor
global ::= 'WL' protocol-conformance // lazy protocol witness table cache variable
- global ::= 'WD' protocol-conformance // dependent proto witness table generator
- global ::= 'Wd' protocol-conformance // dependent proto witness table template
+ global ::= 'Wo' entity // witness table offset
+ global ::= 'WP' protocol-conformance // protocol witness table
+ global ::= 'Wt' protocol-conformance identifier // associated type metadata accessor
+ global ::= 'WT' protocol-conformance identifier nominal-type // associated type witness table accessor
+ global ::= 'Wv' directness entity // field offset
+ global ::= 'WV' type // value witness table
global ::= entity // some identifiable thing
global ::= 'TO' global // ObjC-as-swift thunk
global ::= 'To' global // swift-as-ObjC thunk
@@ -770,6 +772,7 @@ Globals
funcsigspecializationarginfo ::= 'd' // Dead argument
funcsigspecializationarginfo ::= 'g' 's'? // Owned => Guaranteed and Exploded if 's' present.
funcsigspecializationarginfo ::= 's' // Exploded
+ funcsigspecializationarginfo ::= 'k' // Exploded
funcsigspecializationconstantpropinfo ::= 'fr' mangled-name
funcsigspecializationconstantpropinfo ::= 'g' mangled-name
funcsigspecializationconstantpropinfo ::= 'i' 64-bit-integer
@@ -938,6 +941,7 @@ Types
nominal-type-kind ::= 'C' // class
nominal-type-kind ::= 'O' // enum
nominal-type-kind ::= 'V' // struct
+ declaration-name ::= context decl-name
archetype ::= 'Q' index // archetype with depth=0, idx=N
archetype ::= 'Qd' index index // archetype with depth=M+1, idx=N
archetype ::= associated-type
@@ -1088,6 +1092,7 @@ TODO: document these
value-witness-kind ::= 'tT' // initializeArrayWithTakeBackToFront
value-witness-kind ::= 'ug' // getEnumTag
value-witness-kind ::= 'up' // destructiveProjectEnumData
+ value-witness-kind ::= 'ui' // destructiveInjectEnumTag
```` differentiates the kinds of value
witness functions for a type.
@@ -1173,12 +1178,12 @@ for the first time. The first argument type will mangle in long form,
``CC3zim4zang4zung``, and in doing so, ``zim`` will acquire substitution ``S_``,
``zim.zang`` will acquire substitution ``S0_``, and ``zim.zang.zung`` will
acquire ``S1_``. The second argument is the same as the first and will mangle
-using its substitution, ``CS1_``. The
+using its substitution, ``S1_``. The
third argument type will mangle using the substitution for ``zim``,
``CS_7zippity``. (It also acquires substitution ``S2_`` which would be used
if it mangled again.) The result type will mangle using the substitution for
-``zim.zang``, ``CS0_zoo`` (and acquire substitution ``S3_``). The full
-function type thus mangles as ``fTCC3zim4zang4zungCS1_CS_7zippity_CS0_zoo``.
+``zim.zang``, ``CS0_3zoo`` (and acquire substitution ``S3_``). The full
+function type thus mangles as ``fTCC3zim4zang4zungS1_CS_7zippity_CS0_3zoo``.
::
diff --git a/docs/ARCOptimization.rst b/docs/ARCOptimization.rst
index 5cf08d88d7160..bb88d61ae5a1a 100644
--- a/docs/ARCOptimization.rst
+++ b/docs/ARCOptimization.rst
@@ -15,7 +15,6 @@ Reference Counting Instructions
===============================
- strong_retain
-- strong_retain_autoreleased
- strong_release
- strong_retain_unowned
- unowned_retain
@@ -151,7 +150,7 @@ referent. Consider the following sequence of rules:
is deallocated.
(3) A different source-level variable pointing at the same referent
- must not be changed/invalidated by such a call
+ must not be changed/invalidated by such a call.
(4) If such a variable exists, the compiler must guarantee the
refcount is > 1 going into the call.
@@ -229,3 +228,22 @@ These builtins perform an implicit cast to NativeObject before
checking uniqueness. There’s no way at SIL level to cast the address
of a reference, so we need to encapsulate this operation as part of
the builtin.
+
+Semantic Tags
+=============
+
+ARC takes advantage of certain semantic tags. This section documents these
+semantics and their meanings.
+
+arc.programtermination_point
+----------------------------
+
+If this semantic tag is applied to a function, then we know that:
+
+- The function does not touch any reference counted objects.
+- After the function is executed, all reference counted objects are leaked
+ (most likely in preparation for program termination).
+
+This allows one, when performing ARC code motion, to ignore blocks that contain
+an apply to this function as long as the block does not have any other side
+effect having instructions.
diff --git a/docs/AccessControl.rst b/docs/AccessControl.rst
index eb45010656ab8..d0005c54fa737 100644
--- a/docs/AccessControl.rst
+++ b/docs/AccessControl.rst
@@ -90,7 +90,7 @@ Protocols
A protocol may have any access level less than or equal to the access levels
of the protocols it refines. That is, a ``private`` ExtendedWidget protocol can
-refine an ``public`` Widget protocol, but not the other way around.
+refine a ``public`` Widget protocol, but not the other way around.
The access level of a requirement is the access level of the enclosing
protocol, even when the protocol is ``public``. Currently, requirements may not
@@ -154,7 +154,7 @@ elements. A function type's access level is the minimum of the access levels of
its input and return types.
A typealias may have any access level up to the access level of the type it
-aliases. That is, a ``private`` typealias can refer to an ``public`` type, but
+aliases. That is, a ``private`` typealias can refer to a ``public`` type, but
not the other way around. This includes associated types used to satisfy
protocol conformances.
diff --git a/docs/AccessControlInStdlib.rst b/docs/AccessControlInStdlib.rst
index 20f857bba48d7..9bf32bc54a97e 100644
--- a/docs/AccessControlInStdlib.rst
+++ b/docs/AccessControlInStdlib.rst
@@ -6,7 +6,7 @@ Scope and introduction
This document defines the policy for applying access control modifiers and
related naming conventions for the Swift standard library and overlays.
-In this document, “stdlib” refers to the core standard library and
+In this document, "stdlib" refers to the core standard library and
overlays for system frameworks written in Swift.
Swift has three levels of access control --- private, internal
@@ -49,7 +49,7 @@ To document the reason for marking symbols public, we use comments:
* symbols that are SPIs for the module X::
public // SPI(X)
- public _foo() { ... }
+ func _foo() { ... }
`internal`
==========
@@ -60,7 +60,7 @@ explicitly everywhere in the stdlib to avoid confusion.
.. Note:: No declaration should omit an access
-To create a “single point of truth” about whether a name is intended
+To create a "single point of truth" about whether a name is intended
for user consumption, the following names should all use the `leading
underscore rule`_:
@@ -77,7 +77,7 @@ underscore rule`_:
`private`
=========
-The `private` modifier can not be used in the stdlib at least until
+The `private` modifier cannot be used in the stdlib at least until
rdar://17631278 is fixed.
Leading Underscore Rule
diff --git a/docs/DebuggingTheCompiler.rst b/docs/DebuggingTheCompiler.rst
index 5f453f7781c4f..52cc8d405d053 100644
--- a/docs/DebuggingTheCompiler.rst
+++ b/docs/DebuggingTheCompiler.rst
@@ -37,13 +37,13 @@ Here is how to dump the IR after the main phases of the swift compiler
#. **Performance SIL passes**. To print the SIL after the complete SIL
optimization pipeline::
- swiftc -emit-sil -O file-swift
+ swiftc -emit-sil -O file.swift
#. **IRGen**. To print the LLVM IR after IR generation::
swiftc -emit-ir -Xfrontend -disable-llvm-optzns -O file.swift
-4. **LLVM passes**. To print the LLVM IR afer LLVM passes::
+4. **LLVM passes**. To print the LLVM IR after LLVM passes::
swiftc -emit-ir -O file.swift
@@ -136,7 +136,7 @@ and check for the function name in the breakpoint condition::
(lldb) br set -c 'hasName("_TFC3nix1Xd")' -f SILFunction.cpp -l 91
-Sometimes you want to know which optimization does insert, remove or move a
+Sometimes you may want to know which optimization inserts, removes or moves a
certain instruction. To find out, set a breakpoint in
``ilist_traits::addNodeToList`` or
``ilist_traits::removeNodeFromList``, which are defined in
diff --git a/docs/DriverInternals.rst b/docs/DriverInternals.rst
index 24c6fd407aa3e..041d3c09d38b2 100644
--- a/docs/DriverInternals.rst
+++ b/docs/DriverInternals.rst
@@ -114,7 +114,7 @@ Analysis` for more information.
The Compilation's TaskQueue controls the low-level aspects of managing
subprocesses. Multiple Jobs may execute simultaneously, but communication with
the parent process (the driver) is handled on a single thread. The level of
-parellelism may be controlled by a compiler flag.
+parallelism may be controlled by a compiler flag.
If a Job does not finish successfully, the Compilation needs to record which
jobs have failed, so that they get rebuilt next time the user tries to build
diff --git a/docs/ErrorHandling.rst b/docs/ErrorHandling.rst
index 0b2424a25d571..547af4def253a 100644
--- a/docs/ErrorHandling.rst
+++ b/docs/ErrorHandling.rst
@@ -256,7 +256,7 @@ Throwing an error
-----------------
The ``throw`` statement begins the propagation of an error. It always
-take an argument, which can be any value that conforms to the
+takes an argument, which can be any value that conforms to the
``ErrorType`` protocol (described below).
::
@@ -680,7 +680,7 @@ can be overloaded on whether its argument closure throws; the
overload that takes a throwing closures would itself throw.
There is one minor usability problem here, though. If the closure
-contains throwing expressions, those expression must be explicitly
+contains throwing expressions, those expressions must be explicitly
marked within the closure with ``try``. However, from the compiler's
perspective, the call to ``autoreleasepool`` is also a call that
can throw, and so it must also be marked with ``try``::
diff --git a/docs/ErrorHandlingRationale.rst b/docs/ErrorHandlingRationale.rst
index 8714409f5f33b..c5fa599ac67c5 100644
--- a/docs/ErrorHandlingRationale.rst
+++ b/docs/ErrorHandlingRationale.rst
@@ -26,7 +26,7 @@ The most important dimensions of variation are:
errors or not; such a language has **typed propagation**.
* Whether, in a language with typed propagation, the default rule is
- that that a function can produce an error or that it can't; this
+ that a function can produce an error or that it can't; this
is the language's **default propagation rule**.
* Whether, in a language with typed propagation, the language enforces
@@ -173,7 +173,7 @@ be quite amazing for us to assert that code shouldn't be written that
way, understanding nothing else about it. As long as programmers do
face these issues, the language has some responsibility to help them.
-Therefore, in my judgement, promoting the use of universal errors is
+Therefore, in my judgment, promoting the use of universal errors is
highly problematic. They undermine the easy comprehension of code,
and they undermine the language's ability to help the programmer
reason about errors. This design will instead focus on explicitly
@@ -389,7 +389,7 @@ options as a programmer:
function called by your function.
- You can carefully arrange your function so that there are no
- critical sections where an universal error can leave things in an
+ critical sections where a universal error can leave things in an
unwanted state.
There are techniques for making the second more palatable. Chiefly,
@@ -430,7 +430,7 @@ Here's another example of an out-parameter:
.. code-block:: objc
- - (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
+ - (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
Out-parameters have some nice advantages. First, they're a reliable
source of marking; even if the actual propagation gets separated from
@@ -577,7 +577,7 @@ they produce, and so many errors just end up falling into broad
buckets. Different libraries end up with their own library-specific
general error classes, and exceptions list end up just restating the
library's own dependencies or wrapping the underlying errors in ways
-that loses criticial information.
+that loses critical information.
Tradeoffs of typed propagation
@@ -741,8 +741,8 @@ This approach is therefore relatively even-handed about the error
vs. the non-error path, although it requires some care in order to
minimize code-size penalties for parallel error paths.
-``setjmp`` / ``longmp``
-~~~~~~~~~~~~~~~~~~~~~~~
+``setjmp`` / ``longjmp``
+~~~~~~~~~~~~~~~~~~~~~~~~
Another strategy to is to dynamically maintain a thread-local stack of
interesting frames. A function with an interesting frame must save
@@ -768,7 +768,7 @@ not free:
which on our platforms means a function call because we're not
willing to commit to anything more specific in the ABI.
-* Jumping across arbitary frames invalidates the callee-save
+* Jumping across arbitrary frames invalidates the callee-save
registers, so the registering frame must save them all eagerly. In
calling conventions with many callee-save registers, this can be
very expensive. However, this is only necessary when it's possible
@@ -812,7 +812,7 @@ in a very unsafe way that does not behave well in the presence of
inlining.
Overall, this approach requires a lot of work in the non-error path
-of functions with interesting frames. Given that we expects functions
+of functions with interesting frames. Given that we expect functions
with interesting frames to be very common in Swift, this is not
an implementation approach we would consider in the abstract. However,
it is the implementation approach for C++/ObjC exceptions on iOS/ARM32,
@@ -955,7 +955,7 @@ This allows the defer action to be written near the code it
"balances", allowing the reader to immediately see that the required
clean-up will be done (but this has drawbacks, as discussed above).
It's very compact, which is nice as most defer actions are short. It
-also allow multiple actions to pile up without adding awkward nesting.
+also allows multiple actions to pile up without adding awkward nesting.
However, the function-exit semantics exacerbate the problem of
searching for intervening clean-up actions, and they introduce
semantic and performance problems with capturing the values of local
@@ -1396,7 +1396,7 @@ same glance. The keyword appears before the arrow for the simple
reason that the arrow is optional (along with the rest of the return
type) in function and initializer declarations; having the keyword
appear in slightly different places based on the presence of a return
-type would be silly and would making adding a non-void return type
+type would be silly and would make adding a non-void return type
feel awkward. The keyword itself should be descriptive, and it's
particularly nice for it to be a form of the verb used by the throwing
expression, conjugated as if performed by the function itself. Thus,
@@ -1687,7 +1687,7 @@ might want to investigate closer, and you can easily imagine codebases
that expect uses of it to always be explained in comments. But more
importantly, just like ``!`` it's only *statically* unsafe, and it
will reliably fail when the programmer is wrong. Therefore, while you
-can easily imagine (and demonstrate) uncautious programmers flailing
+can easily imagine (and demonstrate) incautious programmers flailing
around with it to appease the type-checker, that's not actually a
tenable position for the overall program: eventually the programmer
will have to learn how to use the feature, or else their program
diff --git a/docs/Failable Initializers.rst b/docs/Failable Initializers.rst
index b6fcfb59caae6..b6cbf0679948f 100644
--- a/docs/Failable Initializers.rst
+++ b/docs/Failable Initializers.rst
@@ -173,7 +173,7 @@ a new hidden stored property to each class that directly defines failing
initializers. The bit is set if this slice of the instance has been
initialized.
-Note that unlike partailDeinit, if a class does not have failing initializers,
+Note that unlike partialDeinit, if a class does not have failing initializers,
it does not need this bit, even if its initializer delegates to a failing
initializer in a superclass.
diff --git a/docs/Generics.rst b/docs/Generics.rst
index 49854392c0d4b..2fa9c7ca76252 100644
--- a/docs/Generics.rst
+++ b/docs/Generics.rst
@@ -579,7 +579,7 @@ OrderedCollection>) are just sugar for a where clause. For example, the
above find() signature is equivalent to::
func find(
- collection : C, value : C.Element)-> Int
+ collection : C, value : C.Element) -> Int
Note that find is shorthand for (and equivalent to) find, since
every type conforms to the Any protocol composition.
@@ -594,7 +594,7 @@ lets us describe an iteration of values of some given value type::
func next() -> Element
}
-Now, we want to express the notion of an enumerable collection, which provides a
+Now, we want to express the notion of an enumerable collection, which provides
iteration, which we do by adding requirements into the protocol::
protocol EnumerableCollection : Collection {
@@ -814,7 +814,7 @@ because code like this::
will essentially parse the type as::
- identifier operator Int operator
+ identifier operator identifier operator
and verify that the operators are '<' and '>', respectively. Cases
involving <> are more interesting, because the type of::
diff --git a/docs/GitWorkflows.rst b/docs/GitWorkflows.rst
index 7cb2ff8174e64..1b803ba0ebc0b 100644
--- a/docs/GitWorkflows.rst
+++ b/docs/GitWorkflows.rst
@@ -43,7 +43,7 @@ to perform a simple repo setup for the Swift repository::
$ git config --global user.name ""
$ git config --global user.email ""
- $ mkdir swift-source && cd swift-soure
+ $ mkdir swift-source && cd swift-source
$ git clone
$ git clone
$ git clone
@@ -114,7 +114,7 @@ By default when updating, Git will attempt to merge the remote changes and your
local changes. Ignoring what that sentence means, this is not an SVN-esque
model. Instead we want any local changes that we have to be applied on top of
any new remote changes. The 'branch.autosetuprebase' flag causes this to be done
-automatically when ever one updates the local repository.
+automatically whenever one updates the local repository.
Update
------
@@ -261,7 +261,7 @@ command::
$ git log
-To see a oneline summary that includes just the title of the commit and its
+To see an oneline summary that includes just the title of the commit and its
hash, pass the '--oneline' command::
$ git log --oneline
diff --git a/docs/HighLevelSILOptimizations.rst b/docs/HighLevelSILOptimizations.rst
index 35ca6e4b53d0e..1e1988cab6144 100644
--- a/docs/HighLevelSILOptimizations.rst
+++ b/docs/HighLevelSILOptimizations.rst
@@ -13,7 +13,7 @@ Abstract
This document describes the high-level abstraction of built-in Swift
data structures in SIL that is used by the optimizer. You need to read
this document if you wish to understand the early stages of the Swift
-optimizer or if you are working on one of the containers in the
+optimizer or if you are working on one of the containers in the
standard library.
@@ -33,22 +33,22 @@ Any Swift developer could identify the redundancy in the code sample above.
Storing two values into the same key in the dictionary is inefficient.
However, optimizing compilers are unaware of the special semantics that the
Swift dictionary has and can't perform this optimization. Traditional
-compilers would start optimizing this code by inlining the subscript
+compilers would start optimizing this code by inlining the subscript
function call and try to analyze the sequence of load/store instructions.
This approach is not very effective because the compiler has to be very
-conservative when optimizing general code with pointers.
+conservative when optimizing general code with pointers.
On the other hand, compilers for high-level languages usually have special
bytecode instructions that allow them to perform high-level optimizations.
However, unlike high-level languages such as JavaScript or Python, Swift
containers are implemented in Swift itself. Moreover, it is beneficial to
be able to inline code from the container into the user program and optimize
-them together, especially for code that uses Generics.
+them together, especially for code that uses Generics.
In order to perform both high-level optimizations, that are common in
high-level languages, and low-level optimizations we annotate parts of the
standard library and describe the semantics of a domain-specific high-level
-operations on data types in the Swift standard library.
+operations on data types in the Swift standard library.
Annotation of code in the standard library
------------------------------------------
@@ -78,7 +78,7 @@ operations in the semantic model. One for checking the bounds and
another one for accessing the elements. With this abstraction the
optimizer can remove the ``checkSubscript`` instruction and keep the
getElement instruction::
-
+
@public subscript(index: Int) -> Element {
get {
checkSubscript(index)
@@ -88,7 +88,7 @@ getElement instruction::
@_semantics("array.check_subscript") func checkSubscript(index: Int) {
...
}
-
+
@_semantics("array.get_element") func getElement(index: Int) -> Element {
return _buffer[index]
}
@@ -131,8 +131,8 @@ Array
The following semantic tags describe Array operations. The operations
are first described in terms of the Array "state". Relations between the
-operations are formally defined below. 'Array' referes to the standard library
-Array, ContigousArray, and ArraySlice data-structures.
+operations are formally defined below. 'Array' refers to the standard library
+Array, ContiguousArray, and ArraySlice data-structures.
We consider the array state to consist of a set of disjoint elements
and a storage descriptor that encapsulates nonelement data such as the
@@ -166,9 +166,9 @@ array.uninitialized(count: Builtin.Word) -> (Array, Builtin.RawPointer)
array.props.isCocoa/needsElementTypeCheck -> Bool
Reads storage descriptors properties (isCocoa, needsElementTypeCheck).
This is not control dependent or guarded. The optimizer has
- semantic knowledge of the state transfer those properties can not make:
- An array that is not ``isCocoa`` can not transfer to ``isCocoa``.
- An array that is not ``needsElementTypeCheck`` can not transfer to
+ semantic knowledge of the state transfer those properties cannot make:
+ An array that is not ``isCocoa`` cannot transfer to ``isCocoa``.
+ An array that is not ``needsElementTypeCheck`` cannot transfer to
``needsElementTypeCheck``.
array.get_element(index: Int) -> Element
@@ -236,7 +236,7 @@ array.mutate_unknown
To complete the semantics understood by the optimizer, we define these relations:
interferes-with
-
+
Given idempotent ``OpA``, the sequence "``OpA, OpB, OpA``" is
semantically equivalent to the sequence "``OpA, OpB``" *iff* ``OpB``
does not interfere with ``OpA``.
@@ -262,7 +262,7 @@ check_subscript guards get_element, get_element_address
make_mutable interferes-with props.isCocoa/needsElementTypeCheck
get_elt_addr interferes-with get_element, get_element_address,
props.isCocoa/needsElementTypeCheck
-mutate_unknown itereferes-with get_element, check_subscript, get_count,
+mutate_unknown interferes-with get_element, check_subscript, get_count,
get_capacity, get_element_address,
props.isCocoa/needsElementTypeCheck
================ =============== ==========================================
@@ -282,18 +282,18 @@ String
~~~~~~
string.concat(lhs: String, rhs: String) -> String
-
+
Performs concatenation of two strings. Operands are not mutated.
This operation can be optimized away in case of both operands
being string literals. In this case, it can be replaced by
a string literal representing a concatenation of both operands.
-
+
string.makeUTF8(start: RawPointer, byteSize: Word, isASCII: Int1) -> String
-
+
Converts a built-in UTF8-encoded string literal into a string.
-
+
string.makeUTF16(start: RawPointer, numberOfCodeUnits: Word) -> String
-
+
Converts a built-in UTF16-encoded string literal into a string.
Dictionary
@@ -323,7 +323,7 @@ readnone
readonly
- function has no side effects, but is dependent on the global
+ function has no side effects, but is dependent on the global
state of the program. Calls to readonly functions can be
eliminated, but cannot be reordered or folded in a way that would
move calls to the readnone function across side effects.
@@ -335,13 +335,13 @@ readwrite
Optimize semantics attribute
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The optimize attribute adds function-sepcific directives to the optimizer.
+The optimize attribute adds function-specific directives to the optimizer.
The optimize attribute supports the following tags:
sil.never
- The sil optimizer should not optimize this funciton.
+ The sil optimizer should not optimize this function.
Example:
@_semantics("optimize.sil.never")
@@ -358,4 +358,3 @@ The availability attribute supports the following tags:
availability.osversion(major: Builtin.Word, minor: Builtin.Word, patch: Builtin.Word) -> Builtin.Int1
Returns true if the OS version matches the parameters.
-
diff --git a/docs/IndexInvalidation.rst b/docs/IndexInvalidation.rst
index 97dd1dc016d9c..aaa2de169a49b 100644
--- a/docs/IndexInvalidation.rst
+++ b/docs/IndexInvalidation.rst
@@ -97,7 +97,7 @@ user:
This rule does not imply that indices should be cheap to convert to actual
integers. The offsets for consecutive elements could be non-consecutive
(e.g., in a hash table with open addressing), or consist of multiple
- offsets so that the conversion to an integer is non-trival (e.g., in a
+ offsets so that the conversion to an integer is non-trivial (e.g., in a
tree).
Note that this rule, like all other rules, is an "as if" rule. As long as
@@ -128,7 +128,7 @@ Consequences:
any indices. Indices are composites of offsets, so replacing the value does
not change the shape of the data structure and preserves offsets.
-- A value type mutable linked list can not conform to
+- A value type mutable linked list cannot conform to
``MutableCollectionType``. An index for a linked list has to be implemented
as a pointer to the list node to provide O(1) element access. Mutating an
element of a non-uniquely referenced linked list will create a copy of the
diff --git a/docs/Literals.rst b/docs/Literals.rst
index 57473e765d91f..8c596be873c85 100644
--- a/docs/Literals.rst
+++ b/docs/Literals.rst
@@ -36,12 +36,16 @@ The StringLiteralConvertible Protocol
-------------------------------------
Here is the StringLiteralConvertible protocol as defined in the standard
-library's Policy.swift::
+library's CompilerProtocols.swift::
// NOTE: the compiler has builtin knowledge of this protocol
- protocol StringLiteralConvertible {
+ // Conforming types can be initialized with arbitrary string literals.
+ public protocol StringLiteralConvertible
+ : ExtendedGraphemeClusterLiteralConvertible {
+
typealias StringLiteralType : _BuiltinStringLiteralConvertible
- class func convertFromStringLiteral(value : StringLiteralType) -> Self
+ // Create an instance initialized to `value`.
+ init(stringLiteral value: StringLiteralType)
}
Curiously, the protocol is not defined in terms of primitive types, but in
@@ -58,13 +62,16 @@ points could be constructed...which may be what's desired in some cases.)
The _BuiltinStringLiteralConvertible Protocol
---------------------------------------------
-Policy.swift contains a second protocol::
+CompilerProtocols.swift contains a second protocol::
// NOTE: the compiler has builtin knowledge of this protocol
- protocol _BuiltinStringLiteralConvertible {
- class func _convertFromBuiltinStringLiteral(value : Builtin.RawPointer,
- byteSize : Builtin.Int64,
- isASCII: Builtin.Int1) -> Self
+ public protocol _BuiltinStringLiteralConvertible
+ : _BuiltinExtendedGraphemeClusterLiteralConvertible {
+
+ init(
+ _builtinStringLiteral start: Builtin.RawPointer,
+ byteSize: Builtin.Word,
+ isASCII: Builtin.Int1)
}
The use of builtin types makes it clear that this is *only* for use in the
diff --git a/docs/MutationModel.rst b/docs/MutationModel.rst
index dae65de7431d2..8a3e802fe9b8c 100644
--- a/docs/MutationModel.rst
+++ b/docs/MutationModel.rst
@@ -37,7 +37,7 @@ Consider::
}
var w = Window()
- w.title += " (parenthesized remark)”
+ w.title += " (parenthesized remark)"
What do we do with this? Since ``+=`` has an ``inout`` first
argument, we detect this situation statically (hopefully one day we’ll
@@ -101,14 +101,14 @@ Otherwise, it is considered **read-only**.
The implicit ``self`` parameter of a struct or enum method is semantically an
``inout`` parameter if and only if the method is attributed with
-``mutating``. Read-only methods do not “write back” onto their target
+``mutating``. Read-only methods do not "write back" onto their target
objects.
A program that applies the ``mutating`` to a method of a
class—or of a protocol attributed with ``@class_protocol``—is
ill-formed. [Note: it is logically consistent to think of all methods
of classes as read-only, even though they may in fact modify instance
-variables, because they never “write back” onto the source reference.]
+variables, because they never "write back" onto the source reference.]
Mutating Operations
-------------------
diff --git a/docs/OptimizationTips.rst b/docs/OptimizationTips.rst
index a8c66e01eb8fc..26f9476f3f5d4 100644
--- a/docs/OptimizationTips.rst
+++ b/docs/OptimizationTips.rst
@@ -176,7 +176,7 @@ Advice: Use value types in Array
In Swift, types can be divided into two different categories: value types
(structs, enums, tuples) and reference types (classes). A key distinction is
-that value types can not be included inside an NSArray. Thus when using value
+that value types cannot be included inside an NSArray. Thus when using value
types, the optimizer can remove most of the overhead in Array that is necessary
to handle the possibility of the array being backed an NSArray.
@@ -265,7 +265,7 @@ Swift eliminates integer overflow bugs by checking for overflow when performing
normal arithmetic. These checks are not appropriate in high performance code
where one knows that no memory safety issues can result.
-Advice: Use unchecked integer arithmetic when you can prove that overflow can not occur
+Advice: Use unchecked integer arithmetic when you can prove that overflow cannot occur
---------------------------------------------------------------------------------------
In performance-critical code you can elide overflow checks if you know it is
@@ -446,7 +446,7 @@ argument drops from being O(n), depending on the size of the tree to O(1).
::
- struct tree : P {
+ struct Tree : P {
var node : [P?]
init() {
node = [ thing ]
diff --git a/docs/OptimizerDesign.md b/docs/OptimizerDesign.md
index 39a5e13d3f31e..79bfb2de16311 100644
--- a/docs/OptimizerDesign.md
+++ b/docs/OptimizerDesign.md
@@ -9,23 +9,23 @@ knowledge of compiler optimizations is required.
### Optimization pipeline overview
-The Swift compiler translates textual swift programs into LLVM-IR and uses
+The Swift compiler translates textual Swift programs into LLVM-IR and uses
multiple representations in between. The Swift frontend is responsible for
-translating textual swift program into well-formed and type-checked programs
+translating textual Swift programs into well-formed and type-checked programs
that are encoded in the SIL intermediate representation. The frontend emits SIL
-in a phase that's called SILGen (stands for SIL-generation). Next, the swift
+in a phase that's called SILGen (stands for SIL-generation). Next, the Swift
compiler performs a sequence of transformations, such as inlining and constant
-propagation that allow the swift compiler to emit diagnostic messages (such as
+propagation that allow the Swift compiler to emit diagnostic messages (such as
warnings for uninitialized variables or arithmetic overflow). Next, the Swift
optimizer transforms the code to make it faster. The optimizer removes redundant
reference counting operations, devirtualizes function calls, and specializes
generics and closures. This phase of the compiler is the focus of this
document. Finally, the SIL intermediate representation is passed on to the IRGen
-phase (stands for intermediate representation generationphase) that lowers SIL
+phase (stands for intermediate representation generation phase) that lowers SIL
into LLVM IR. The LLVM backend optimizes and emits binary code for the compiled
program.
-Please refer to the document “Swift Intermediate Language (SIL)” for more
+Please refer to the document "Swift Intermediate Language (SIL)" for more
details about the SIL IR.
The compiler optimizer is responsible for optimizing the program using the
@@ -40,7 +40,7 @@ opaque calls, and the LLVM-optimizer can't do anything about it.
The goal of the Swift optimizer is not to reimplement optimizations that
already exist in the LLVM optimizer. The goal is to implement optimizations that
can't be implemented in LLVM-IR because the high-level semantic information is
-lost. The swift optimizer does have some optimizations that are similar to LLVM
+lost. The Swift optimizer does have some optimizations that are similar to LLVM
optimizations, like SSA-construction and function inlining. These optimizations
are implemented at the SIL-level because they are required for exposing other
higher-level optimizations. For example, the ARC optimizer and devirtualizer
@@ -50,7 +50,7 @@ prerequisite to the array optimizations.
### The Swift Pass Manager
The Swift pass manager is the unit that executes optimization
-passes on the functions in the swift module. Unlike the LLVM optimizer, the
+passes on the functions in the Swift module. Unlike the LLVM optimizer, the
Swift pass manager does not schedule analysis or optimization passes. The pass
manager simply runs optimization passes on the functions in the module.
The order of the optimizations is statically defined in the file "Passes.cpp".
@@ -60,7 +60,7 @@ development.
The pass manager scans the module and creates a list of functions that are
organized at a bottom-up order. This means that the optimizer first optimizes
-callees, and later optimizes the callers. This means that when optimizing a some
+callees, and later optimizes the callers. This means that when optimizing some
caller function, the optimizer had already optimized all of its callees and the
optimizer can inspect the callee for side effects and inline it into the caller.
@@ -125,8 +125,8 @@ The mechanism that swift uses to invalidate analysis is broadcast-invalidation.
Passes ask the pass manager to invalidate specific traits. For example, a pass
like simplify-cfg will ask the pass manager to announce that it modified some
branches in the code. The pass manager will send a message to all of the
-available analysis that says “please invalidate yourself if you care about
-branches for function F“. The dominator tree would then invalidate the dominator
+available analysis that says "please invalidate yourself if you care about
+branches for function F". The dominator tree would then invalidate the dominator
tree for function F because it knows that changes to branches can mean that the
dominator tree was modified.
@@ -153,7 +153,7 @@ the cache for the function that was modified.
}
```
-The invalidation traits that passes can invalidate are are:
+The invalidation traits that passes can invalidate are:
1. Instructions - some instructions were added, deleted or moved.
2. Calls - some call sites were added or deleted.
3. Branches - branches in the code were added, deleted or modified.
@@ -189,7 +189,47 @@ functions with the @_semantics attribute until after all of the data-structure
specific optimizations are done. Unfortunately, this lengthens our optimization
pipeline.
-Please refer to the document “High-Level SIL Optimizations” for more details.
+Please refer to the document "High-Level SIL Optimizations" for more details.
+
+
+### Instruction Invalidation in SIL
+
+Swift Passes and Analysis often keep instruction pointers in internal data
+structures such as Map or Set. A good example of such data structure is a list
+of visited instructions, or a map between a SILValue and the memory aliasing
+effects of the value.
+
+Passes and utilities delete instructions in many different places in the
+optimizer. When instructions are deleted pointers that are saved inside maps in
+the different data structures become invalid. These pointers point to
+deallocated memory locations. In some cases malloc allocates new instructions
+with the same address as the freed instruction. Instruction reallocation bugs
+are often difficult to detect because hash maps return values that are logically
+incorrect.
+
+LLVM handles this problem by keeping ValueHandles, which are a kind of smart
+pointers that handle instruction deletion and replaceAllUsesWith events.
+ValueHandles are special uses of LLVM values. One problem with this approach is
+that value handles require additional memory per-value and require doing extra
+work when working with values.
+
+The Swift optimizer approach is to let the Context (currently a part of the
+SILModule) handle the invalidation of instructions. When instructions are
+deleted the context notifies a list of listeners. The invalidation mechanism is
+relatively efficient and incurs a cost only when instructions are deleted. Every
+time an instruction is deleted the context notifies all of the listeners that
+requested to be notified. A typical notifications list is very short and is made
+of the registered Analysis and the currently executed Pass.
+
+Passes and Analysis are registered by the PassManager to receive instruction
+deletion notifications. Passes and Analysis simply need to implement the
+following virtual method:
+
+```
+ virtual void handleNotification(swift::ValueBase *Value) override {
+ llvm::errs()<<"SILCombine Deleting: " << Value<<"\n";
+ }
+```
### Debugging the optimizer
@@ -201,4 +241,4 @@ TODO.
### List of passes
-The updated list of passes is available in the file “Passes.def”.
+The updated list of passes is available in the file "Passes.def".
diff --git a/docs/Pattern Matching.rst b/docs/Pattern Matching.rst
index b3794de132a20..0875e7ee988c5 100644
--- a/docs/Pattern Matching.rst
+++ b/docs/Pattern Matching.rst
@@ -26,7 +26,7 @@ Swift has a pretty small set of types right now:
* Function types.
* Tuples. Heterogeneous fixed-length products. Swift's system
provides two basic kinds of element: positional and labelled.
-* Arrays. Homogenous fixed-length aggregates.
+* Arrays. Homogeneous fixed-length aggregates.
* Algebraic data types (ADTs), introduce by enum. Nominal closed
disjoint unions of heterogeneous types.
* Struct types. Nominal heterogeneous fixed-length products.
@@ -354,7 +354,7 @@ imperative language — in contrast to, say, a functional language where
you're in an expression and you need to produce a value — there's a
colorable argument that non-exhaustive matches should be okay. I
dislike this, however, and propose that it should be an error to
-make an non-exhaustive switch; people who want non-exhaustive matches
+make a non-exhaustive switch; people who want non-exhaustive matches
can explicitly put in default cases.
Exhaustiveness actually isn't that difficult to check, at least over
ADTs. It's also really the behavior that I would expect from the
@@ -689,13 +689,13 @@ interpreted according to what is found:
value must match the named type (according to the rules below for
'is' patterns). It is okay for this to be trivially true.
- In addition, there must be an non-empty arguments clause, and each
+ In addition, there must be a non-empty arguments clause, and each
element in the clause must have an identifier. For each element,
the identifier must correspond to a known property of the named
type, and the value of that property must satisfy the element
pattern.
-- If the name resolves to a enum element, then the dynamic type
+- If the name resolves to an enum element, then the dynamic type
of the matched value must match the enum type as discussed above,
and the value must be of the specified element. There must be
an arguments clause if and only if the element has a value type.
diff --git a/docs/Runtime.md b/docs/Runtime.md
new file mode 100644
index 0000000000000..be0026fb1b486
--- /dev/null
+++ b/docs/Runtime.md
@@ -0,0 +1,408 @@
+# The Swift Runtime
+
+This document describes the ABI interface to the Swift runtime, which provides
+the following core functionality for Swift programs:
+
+- memory management, including allocation and reference counting;
+- the runtime type system, including dynamic casting, generic instantiation,
+ and protocol conformance registration;
+
+It is intended to describe only the runtime interface that compiler-generated
+code should conform to, not details of how things are implemented.
+
+The final runtime interface is currently a work-in-progress; it is a goal of
+Swift 3 to stabilize it. This document attempts to describe both the current
+state of the runtime and the intended endpoint of the stable interface.
+Changes that are intended to be made before stabilization are marked with
+**ABI TODO**. Entry points that only exist on Darwin platforms with
+ObjC interop, and
+information that only pertains to ObjC interop, are marked **ObjC-only**.
+
+## Deprecated entry points
+
+Entry points in this section are intended to be removed or internalized before
+ABI stabilization.
+
+### Exported C++ symbols
+
+**ABI TODO**: Any exported C++ symbols are implementation details that are not
+intended to be part of the stable runtime interface.
+
+### swift\_ClassMirror\_count
+### swift\_ClassMirror\_quickLookObject
+### swift\_ClassMirror\_subscript
+### swift\_EnumMirror\_caseName
+### swift\_EnumMirror\_count
+### swift\_EnumMirror\_subscript
+### swift\_MagicMirrorData\_objcValue
+### swift\_MagicMirrorData\_objcValueType
+### swift\_MagicMirrorData\_summary
+### swift\_MagicMirrorData\_value
+### swift\_MagicMirrorData\_valueType
+### swift\_ObjCMirror\_count
+### swift\_ObjCMirror\_subscript
+### swift\_StructMirror\_count
+### swift\_StructMirror\_subscript
+### swift\_TupleMirror\_count
+### swift\_TupleMirror\_subscript
+### swift\_reflectAny
+
+**ABI TODO**: These functions are implementation details of the standard
+library `reflect` interface. They will be superseded by a low-level
+runtime reflection API.
+
+### swift\_stdlib\_demangleName
+
+```
+@convention(thin) (string: UnsafePointer,
+ length: UInt,
+ @out String) -> ()
+```
+
+Given a pointer to a Swift mangled symbol name as a byte string of `length`
+characters, returns the demangled name as a `Swift.String`.
+
+**ABI TODO**: Decouple from the standard library `Swift.String` implementation.
+Rename with a non-`stdlib` naming scheme.
+
+## Memory allocation
+
+### TODO
+
+```
+000000000001cb30 T _swift_allocBox
+000000000001c990 T _swift_allocObject
+000000000001ca60 T _swift_bufferAllocate
+000000000001ca70 T _swift_bufferAllocateOnStack
+000000000001ca80 T _swift_bufferDeallocateFromStack
+000000000001ca90 T _swift_bufferHeaderSize
+000000000001cd30 T _swift_deallocBox
+000000000001d490 T _swift_deallocClassInstance
+000000000001cd60 T _swift_deallocObject
+000000000001d4c0 T _swift_deallocPartialClassInstance
+000000000001d400 T _swift_rootObjCDealloc
+000000000001c960 T _swift_slowAlloc
+000000000001c980 T _swift_slowDealloc
+000000000001ce10 T _swift_projectBox
+000000000001ca00 T _swift_initStackObject
+```
+
+## Reference counting
+
+### TODO
+
+```
+0000000000027ba0 T _swift_bridgeObjectRelease
+0000000000027c50 T _swift_bridgeObjectRelease_n
+0000000000027b50 T _swift_bridgeObjectRetain
+0000000000027be0 T _swift_bridgeObjectRetain_n
+000000000001ce70 T _swift_release
+000000000001cee0 T _swift_release_n
+000000000001ce30 T _swift_retain
+000000000001ce50 T _swift_retain_n
+000000000001d140 T _swift_tryPin
+000000000001d240 T _swift_tryRetain
+0000000000027b10 T _swift_unknownRelease
+0000000000027a70 T _swift_unknownRelease_n
+0000000000027ad0 T _swift_unknownRetain
+0000000000027a10 T _swift_unknownRetain_n
+0000000000027d50 T _swift_unknownUnownedAssign
+00000000000280a0 T _swift_unknownUnownedCopyAssign
+0000000000027fd0 T _swift_unknownUnownedCopyInit
+0000000000027ed0 T _swift_unknownUnownedDestroy
+0000000000027cb0 T _swift_unknownUnownedInit
+0000000000027f20 T _swift_unknownUnownedLoadStrong
+00000000000281f0 T _swift_unknownUnownedTakeAssign
+0000000000028070 T _swift_unknownUnownedTakeInit
+0000000000027f70 T _swift_unknownUnownedTakeStrong
+00000000000282b0 T _swift_unknownWeakAssign
+0000000000028560 T _swift_unknownWeakCopyAssign
+00000000000284e0 T _swift_unknownWeakCopyInit
+00000000000283e0 T _swift_unknownWeakDestroy
+0000000000028270 T _swift_unknownWeakInit
+0000000000028420 T _swift_unknownWeakLoadStrong
+0000000000028610 T _swift_unknownWeakTakeAssign
+0000000000028520 T _swift_unknownWeakTakeInit
+0000000000028470 T _swift_unknownWeakTakeStrong
+000000000001d3c0 T _swift_unownedCheck
+000000000001cfb0 T _swift_unownedRelease
+000000000001d0a0 T _swift_unownedRelease_n
+000000000001cf70 T _swift_unownedRetain
+000000000001cf60 T _swift_unownedRetainCount
+000000000001d2b0 T _swift_unownedRetainStrong
+000000000001d310 T _swift_unownedRetainStrongAndRelease
+000000000001d060 T _swift_unownedRetain_n
+000000000001d1b0 T _swift_unpin
+000000000001ca20 T _swift_verifyEndOfLifetime
+000000000001d680 T _swift_weakAssign
+000000000001d830 T _swift_weakCopyAssign
+000000000001d790 T _swift_weakCopyInit
+000000000001d770 T _swift_weakDestroy
+000000000001d640 T _swift_weakInit
+000000000001d6d0 T _swift_weakLoadStrong
+000000000001d8b0 T _swift_weakTakeAssign
+000000000001d800 T _swift_weakTakeInit
+000000000001d710 T _swift_weakTakeStrong
+000000000002afe0 T _swift_isUniquelyReferencedNonObjC
+000000000002af50 T _swift_isUniquelyReferencedNonObjC_nonNull
+000000000002b060 T _swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject
+000000000002b200 T _swift_isUniquelyReferencedOrPinnedNonObjC_nonNull
+000000000002b130 T _swift_isUniquelyReferencedOrPinnedNonObjC_nonNull_bridgeObject
+000000000002b2f0 T _swift_isUniquelyReferencedOrPinned_native
+000000000002b290 T _swift_isUniquelyReferencedOrPinned_nonNull_native
+000000000002af00 T _swift_isUniquelyReferenced_native
+000000000002aea0 T _swift_isUniquelyReferenced_nonNull_native
+000000000001d280 T _swift_isDeallocating
+```
+
+**ABI TODO**: `_unsynchronized` r/r entry points
+
+## Error objects
+
+The `ErrorType` existential type uses a special single-word, reference-
+counted representation.
+
+**ObjC-only**: The representation is internal to the runtime in order
+to provide efficient bridging with the platform `NSError` and `CFError`
+implementations. On non-ObjC platforms this bridging is unnecessary, and
+the error object interface could be made more fragile.
+
+To preserve the encapsulation of the ErrorType representation, and
+allow for future representation optimizations, the runtime provides
+special entry points for allocating, projecting, and reference
+counting error values.
+
+
+```
+00000000000268e0 T _swift_allocError
+0000000000026d50 T _swift_bridgeErrorTypeToNSError
+0000000000026900 T _swift_deallocError
+0000000000027120 T _swift_errorRelease
+0000000000027100 T _swift_errorRetain
+0000000000026b80 T _swift_getErrorValue
+```
+
+**ABI TODO**: `_unsynchronized` r/r entry points
+
+**ABI TODO**: `_n` r/r entry points
+
+## Initialization
+
+### swift_once
+
+```
+@convention(thin) (Builtin.RawPointer, @convention(thin) () -> ()) -> ()
+```
+
+Used to lazily initialize global variables. The first parameter must
+point to a word-sized memory location that was initialized to zero at
+process start. It is undefined behavior to reference memory that has
+been initialized to something other than zero or written to by anything other
+than `swift_once` in the current process's lifetime. The function referenced by
+the second parameter will have been run exactly once in the time between
+process start and the function returns.
+
+## Dynamic casting
+
+```
+0000000000001470 T _swift_dynamicCast
+0000000000000a60 T _swift_dynamicCastClass
+0000000000000ae0 T _swift_dynamicCastClassUnconditional
+0000000000028750 T _swift_dynamicCastForeignClass
+000000000002ae20 T _swift_dynamicCastForeignClassMetatype
+000000000002ae30 T _swift_dynamicCastForeignClassMetatypeUnconditional
+0000000000028760 T _swift_dynamicCastForeignClassUnconditional
+00000000000011c0 T _swift_dynamicCastMetatype
+0000000000000cf0 T _swift_dynamicCastMetatypeToObjectConditional
+0000000000000d20 T _swift_dynamicCastMetatypeToObjectUnconditional
+00000000000012e0 T _swift_dynamicCastMetatypeUnconditional
+00000000000286c0 T _swift_dynamicCastObjCClass
+0000000000028bd0 T _swift_dynamicCastObjCClassMetatype
+0000000000028c00 T _swift_dynamicCastObjCClassMetatypeUnconditional
+0000000000028700 T _swift_dynamicCastObjCClassUnconditional
+0000000000028af0 T _swift_dynamicCastObjCProtocolConditional
+0000000000028a50 T _swift_dynamicCastObjCProtocolUnconditional
+0000000000028960 T _swift_dynamicCastTypeToObjCProtocolConditional
+00000000000287d0 T _swift_dynamicCastTypeToObjCProtocolUnconditional
+0000000000000de0 T _swift_dynamicCastUnknownClass
+0000000000000fd0 T _swift_dynamicCastUnknownClassUnconditional
+```
+
+## Debugging
+
+```
+0000000000027140 T _swift_willThrow
+```
+
+## Objective-C Bridging
+
+**ObjC-only**.
+
+**ABI TODO**: Decouple from the runtime as much as possible. Much of this
+should be implementable in the standard library now.
+
+```
+0000000000003b60 T _swift_bridgeNonVerbatimFromObjectiveC
+0000000000003c80 T _swift_bridgeNonVerbatimFromObjectiveCConditional
+00000000000037e0 T _swift_bridgeNonVerbatimToObjectiveC
+00000000000039c0 T _swift_getBridgedNonVerbatimObjectiveCType
+0000000000003d90 T _swift_isBridgedNonVerbatimToObjectiveC
+```
+
+## Code generation
+
+Certain common code paths are implemented in the runtime as a code size
+optimization.
+
+```
+0000000000023a40 T _swift_assignExistentialWithCopy
+000000000001dbf0 T _swift_copyPOD
+000000000001c560 T _swift_getEnumCaseMultiPayload
+000000000001be60 T _swift_getEnumCaseSinglePayload
+000000000001c400 T _swift_storeEnumTagMultiPayload
+000000000001bf90 T _swift_storeEnumTagSinglePayload
+```
+
+## Type metadata lookup
+
+These functions look up metadata for types that potentially require runtime
+instantiation or initialization, including structural types, generics, classes,
+and metadata for imported C and Objective-C types.
+
+**ABI TODO**: Instantiation APIs under flux as part of resilience work. For
+nominal types, `getGenericMetadata` is likely to become an implementation
+detail used to implement resilient per-type metadata accessor functions.
+
+```
+0000000000023230 T _swift_getExistentialMetatypeMetadata
+0000000000023630 T _swift_getExistentialTypeMetadata
+0000000000023b90 T _swift_getForeignTypeMetadata
+000000000001ef30 T _swift_getFunctionTypeMetadata
+000000000001eed0 T _swift_getFunctionTypeMetadata1
+000000000001f1f0 T _swift_getFunctionTypeMetadata2
+000000000001f250 T _swift_getFunctionTypeMetadata3
+000000000001e940 T _swift_getGenericMetadata
+000000000001e9c0 T _swift_getGenericMetadata1
+000000000001ea60 T _swift_getGenericMetadata2
+000000000001eb00 T _swift_getGenericMetadata3
+000000000001eba0 T _swift_getGenericMetadata4
+0000000000022fd0 T _swift_getMetatypeMetadata
+000000000001ec50 T _swift_getObjCClassMetadata
+000000000001e6b0 T _swift_getResilientMetadata
+0000000000022260 T _swift_getTupleTypeMetadata
+00000000000225a0 T _swift_getTupleTypeMetadata2
+00000000000225d0 T _swift_getTupleTypeMetadata3
+0000000000028bc0 T _swift_getInitializedObjCClass
+```
+
+**ABI TODO**: Fast entry points for `getExistential*TypeMetadata1-3`. Static
+metadata for `Any` and `AnyObject` is probably worth considering too.
+
+## Type metadata initialization
+
+Calls to these entry points are emitted when instantiating type metadata at
+runtime.
+
+**ABI TODO**: Initialization APIs under flux as part of resilience work.
+
+```
+000000000001e3e0 T _swift_allocateGenericClassMetadata
+000000000001e620 T _swift_allocateGenericValueMetadata
+0000000000022be0 T _swift_initClassMetadata_UniversalStrategy
+000000000001c100 T _swift_initEnumMetadataMultiPayload
+000000000001bd60 T _swift_initEnumValueWitnessTableSinglePayload
+0000000000022a20 T _swift_initStructMetadata_UniversalStrategy
+0000000000024230 T _swift_initializeSuperclass
+0000000000028b60 T _swift_instantiateObjCClass
+```
+
+## Metatypes
+
+```
+0000000000000b60 T _swift_getDynamicType
+0000000000022fb0 T _swift_getObjectType
+00000000000006f0 T _swift_getTypeName
+00000000000040c0 T _swift_isClassType
+0000000000003f50 T _swift_isClassOrObjCExistentialType
+0000000000004130 T _swift_isOptionalType
+00000000000279f0 T _swift_objc_class_usesNativeSwiftReferenceCounting
+000000000002b340 T _swift_objc_class_unknownGetInstanceExtents
+000000000002b350 T _swift_class_getInstanceExtents
+0000000000004080 T _swift_class_getSuperclass
+```
+
+**ABI TODO**: getTypeByName entry point.
+
+**ABI TODO**: Should have a `getTypeKind` entry point with well-defined enum
+constants to supersede `swift_is*Type`.
+
+**ABI TODO**: Rename class metadata queries with a consistent naming scheme.
+
+## Protocol conformance lookup
+
+```
+0000000000002ef0 T _swift_registerProtocolConformances
+0000000000003060 T _swift_conformsToProtocol
+```
+
+## Error reporting
+
+```
+000000000001c7d0 T _swift_reportError
+000000000001c940 T _swift_deletedMethodError
+```
+
+## Standard metadata
+
+The Swift runtime exports standard metadata objects for `Builtin` types
+as well as standard value witness tables that can be freely adopted by
+types with common layout attributes. Note that, unlike public-facing types,
+the runtime does not guarantee a 1:1 mapping of Builtin types to metadata
+objects, and will reuse metadata objects to represent builtins with the same
+layout characteristics.
+
+```
+000000000004faa8 S __TMBB
+000000000004fab8 S __TMBO
+000000000004f9f8 S __TMBb
+000000000004f9c8 S __TMBi128_
+000000000004f998 S __TMBi16_
+000000000004f9d8 S __TMBi256_
+000000000004f9a8 S __TMBi32_
+000000000004f9b8 S __TMBi64_
+000000000004f988 S __TMBi8_
+000000000004f9e8 S __TMBo
+000000000004fac8 S __TMT_
+000000000004f568 S __TWVBO
+000000000004f4b0 S __TWVBb
+000000000004f0a8 S __TWVBi128_
+000000000004eec8 S __TWVBi16_
+000000000004f148 S __TWVBi256_
+000000000004ef68 S __TWVBi32_
+000000000004f008 S __TWVBi64_
+000000000004ee28 S __TWVBi8_
+000000000004f1e8 S __TWVBo
+000000000004f778 S __TWVFT_T_
+000000000004f3f8 S __TWVMBo
+000000000004f8e8 S __TWVT_
+000000000004f830 S __TWVXfT_T_
+000000000004f620 S __TWVXoBO
+000000000004f2a0 S __TWVXoBo
+000000000004f6d8 S __TWVXwGSqBO_
+000000000004f358 S __TWVXwGSqBo_
+```
+
+## Tasks
+
+- Moving to per-type instantiation functions instead of using
+ `getGenericMetadata` directly
+
+- `swift_objc_` naming convention for ObjC
+
+- Alternative ABIs for retain/release
+
+- Unsynchronized retain/release
+
+- Nonnull retain/release
+
+- Decouple dynamic casting, bridging, and reflection from the standard library
diff --git a/docs/SIL.rst b/docs/SIL.rst
index 208c7146bb4c7..4d6116e873ae8 100644
--- a/docs/SIL.rst
+++ b/docs/SIL.rst
@@ -253,7 +253,7 @@ Consider a generic function like this:
::
- func generateArray(n : Int, generator : () -> T) -> T[]
+ func generateArray(n : Int, generator : () -> T) -> [T]
The function ``generator`` will be expected to store its result
indirectly into an address passed in an implicit parameter. There's
@@ -312,7 +312,7 @@ lowered using the pattern ``() -> T``, which eventually causes ``(Int,Int)
lowering it with the pattern ``U -> V``; the result is that ``g.fn``
has the following lowered type::
- @callee_owned () -> @owned @callee_owned (@out Float, @in (Int,Int)) -> ()``.
+ @callee_owned () -> @owned @callee_owned (@out Float, @in (Int,Int)) -> ().
As another example, suppose that ``h`` has type
``Generator<(Int, @inout Int) -> Float>``. Neither ``(Int, @inout Int)``
@@ -341,8 +341,6 @@ The type of a value in SIL shall be:
- the address of a legal SIL type, ``$*T``, or
-- the address of local storage of a legal SIL type, ``$*@local_storage T``.
-
A type ``T`` is a *legal SIL type* if:
- it is a function type which satisfies the constraints (below) on
@@ -386,22 +384,6 @@ type. Values of address type thus cannot be allocated, loaded, or stored
Addresses can be passed as arguments to functions if the corresponding
parameter is indirect. They cannot be returned.
-Local Storage Types
-```````````````````
-
-The *address of local storage for T* ``$*@local_storage T`` is a
-handle to a stack allocation of a variable of type ``$T``.
-
-For many types, the handle for a stack allocation is simply the
-allocated address itself. However, if a type is runtime-sized, the
-compiler must emit code to potentially dynamically allocate memory.
-SIL abstracts over such differences by using values of local-storage
-type as the first result of ``alloc_stack`` and the operand of
-``dealloc_stack``.
-
-Local-storage address types are not *first-class* in the same sense
-that address types are not first-class.
-
Box Types
`````````
@@ -424,7 +406,7 @@ number of ways:
- A SIL function type declares its conventional treatment of its
context value:
- - If it is ``@thin``, the function requires no context value.
+ - If it is ``@convention(thin)``, the function requires no context value.
- If it is ``@callee_owned``, the context value is treated as an
owned direct parameter.
@@ -449,8 +431,24 @@ number of ways:
the value held there.
- An ``@inout`` parameter is indirect. The address must be of an
- initialized object, and the function must leave an initialized
- object there upon exit.
+ initialized object. The memory must remain initialized for the duration
+ of the call until the function returns. The function may mutate the
+ pointee, and furthermore may weakly assume that there are no aliasing
+ reads from or writes to the argument, though must preserve a valid
+ value at the argument so that well-ordered aliasing violations do not
+ compromise memory safety. This allows for optimizations such as local
+ load and store propagation, introduction or elimination of temporary
+ copies, and promotion of the ``@inout`` parameter to an ``@owned`` direct
+ parameter and result pair, but does not admit "take" optimization out
+ of the parameter or other optimization that would leave memory in an
+ uninitialized state.
+
+ - An ``@inout_aliasable`` parameter is indirect. The address must be of an
+ initialized object. The memory must remain initialized for the duration
+ of the call until the function returns. The function may mutate the
+ pointee, and must assume that other aliases may mutate it as well. These
+ aliases however can be assumed to be well-typed and well-ordered; ill-typed
+ accesses and data races to the parameter are still undefined.
- An ``@out`` parameter is indirect. The address must be of an
uninitialized object; the function is responsible for initializing
@@ -495,9 +493,19 @@ throughout the execution of the call. This means that any
argument can be eliminated.
An autoreleased direct result must have a type with a retainable
-pointer representation. It may have been autoreleased, and the caller
-should take action to reclaim that autorelease with
-``strong_retain_autoreleased``.
+pointer representation. Autoreleased results are nominally transferred
+at +0, but the runtime takes steps to ensure that a +1 can be safely
+transferred, and those steps require precise code-layout control.
+Accordingly, the SIL pattern for an autoreleased convention looks exactly
+like the SIL pattern for an owned convention, and the extra runtime
+instrumentation is inserted on both sides when the SIL is lowered into
+LLVM IR. An autoreleased ``apply`` of a function that is defined with
+an autoreleased result has the effect of a +1 transfer of the result.
+An autoreleased ``apply`` of a function that is not defined with
+an autoreleased result has the effect of performing a strong retain in
+the caller. A non-autoreleased ``apply`` of a function that is defined
+with an autoreleased result has the effect of performing an
+autorelease in the callee.
- The @noescape declaration attribute on Swift parameters (which is valid only
on parameters of function type, and is implied by the @autoclosure attribute)
@@ -568,7 +576,7 @@ generic constraints:
* Non-class protocol types
* @weak types
- Values of address-only type (“address-only values”) must reside in
+ Values of address-only type ("address-only values") must reside in
memory and can only be referenced in SIL by address. Addresses of
address-only values cannot be loaded from or stored to. SIL provides
special instructions for indirectly manipulating address-only
@@ -578,7 +586,7 @@ Some additional meaningful categories of type:
- A *heap object reference* type is a type whose representation consists of a
single strong-reference-counted pointer. This includes all class types,
- the ``Builtin.ObjectPointer`` and ``Builtin.ObjCPointer`` types, and
+ the ``Builtin.NativeObject`` and ``Builtin.UnknownObject`` types, and
archetypes that conform to one or more class protocols.
- A *reference type* is more general in that its low-level representation may
include additional global pointers alongside a strong-reference-counted
@@ -773,7 +781,7 @@ are bound by the function's caller::
sil @foo : $(Int) -> Int {
bb0(%x : $Int):
- %1 = return %x : $Int
+ return %x : $Int
}
sil @bar : $(Int, Int) -> () {
@@ -782,7 +790,7 @@ are bound by the function's caller::
%1 = apply %foo(%x) : $(Int) -> Int
%2 = apply %foo(%y) : $(Int) -> Int
%3 = tuple ()
- %4 = return %3 : $()
+ return %3 : $()
}
Declaration References
@@ -838,16 +846,17 @@ partial application level. For a curried function declaration::
The declaration references and types for the different uncurry levels are as
follows::
- #example.foo!0 : $@thin (x:A) -> (y:B) -> (z:C) -> D
- #example.foo!1 : $@thin ((y:B), (x:A)) -> (z:C) -> D
- #example.foo!2 : $@thin ((z:C), (y:B), (x:A)) -> D
+ #example.foo!0 : $@convention(thin) (x:A) -> (y:B) -> (z:C) -> D
+ #example.foo!1 : $@convention(thin) ((y:B), (x:A)) -> (z:C) -> D
+ #example.foo!2 : $@convention(thin) ((z:C), (y:B), (x:A)) -> D
The deepest uncurry level is referred to as the **natural uncurry level**. In
this specific example, the reference at the natural uncurry level is
``#example.foo!2``. Note that the uncurried argument clauses are composed
right-to-left, as specified in the `calling convention`_. For uncurry levels
-less than the uncurry level, the entry point itself is ``@thin`` but returns a
-thick function value carrying the partially applied arguments for its context.
+less than the uncurry level, the entry point itself is ``@convention(thin)`` but
+returns a thick function value carrying the partially applied arguments for its
+context.
`Dynamic dispatch`_ instructions such as ``class method`` require their method
declaration reference to be uncurried to at least uncurry level 1 (which applies
@@ -981,9 +990,9 @@ implements the method for that class::
func bas()
}
- sil @A_foo : $@thin (@owned A) -> ()
- sil @A_bar : $@thin (@owned A) -> ()
- sil @A_bas : $@thin (@owned A) -> ()
+ sil @A_foo : $@convention(thin) (@owned A) -> ()
+ sil @A_bar : $@convention(thin) (@owned A) -> ()
+ sil @A_bas : $@convention(thin) (@owned A) -> ()
sil_vtable A {
#A.foo!1: @A_foo
@@ -995,7 +1004,7 @@ implements the method for that class::
func bar()
}
- sil @B_bar : $@thin (@owned B) -> ()
+ sil @B_bar : $@convention(thin) (@owned B) -> ()
sil_vtable B {
#A.foo!1: @A_foo
@@ -1007,7 +1016,7 @@ implements the method for that class::
func bas()
}
- sil @C_bas : $@thin (@owned C) -> ()
+ sil @C_bas : $@convention(thin) (@owned C) -> ()
sil_vtable C {
#A.foo!1: @A_foo
@@ -1166,8 +1175,8 @@ Calling Convention
This section describes how Swift functions are emitted in SIL.
-Swift Calling Convention @cc(swift)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Swift Calling Convention @convention(swift)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Swift calling convention is the one used by default for native Swift
functions.
@@ -1362,13 +1371,13 @@ gets lowered to SIL as::
sil @inout : $(@inout Int) -> () {
entry(%x : $*Int):
- %1 = integer_literal 1 : $Int
+ %1 = integer_literal $Int, 1
store %1 to %x
return
}
-Swift Method Calling Convention @cc(method)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Swift Method Calling Convention @convention(method)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The method calling convention is currently identical to the freestanding
function convention. Methods are considered to be curried functions, taking
@@ -1382,8 +1391,8 @@ passed last::
sil @Foo_method_1 : $((x : Int), @inout Foo) -> Int { ... }
-Witness Method Calling Convention @cc(witness_method)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Witness Method Calling Convention @convention(witness_method)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The witness method calling convention is used by protocol witness methods in
`witness tables`_. It is identical to the ``method`` calling convention
@@ -1394,8 +1403,8 @@ witnesses must be polymorphically dispatchable on their ``Self`` type,
the ``Self``-related metadata for a witness must be passed in a maximally
abstracted manner.
-C Calling Convention @cc(cdecl)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+C Calling Convention @convention(c)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Swift's C module importer, C types are always mapped to Swift types
considered trivial by SIL. SIL does not concern itself with platform
@@ -1405,8 +1414,8 @@ platform calling convention.
SIL (and therefore Swift) cannot currently invoke variadic C functions.
-Objective-C Calling Convention @cc(objc_method)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Objective-C Calling Convention @convention(objc_method)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Reference Counts
````````````````
@@ -1497,7 +1506,7 @@ return a class reference::
bb0(%0 : $MyClass):
%1 = class_method %0 : $MyClass, #MyClass.foo!1
- %2 = apply %1(%0) : $@cc(method) @thin (@guaranteed MyClass) -> @owned MyOtherClass
+ %2 = apply %1(%0) : $@convention(method) (@guaranteed MyClass) -> @owned MyOtherClass
// use of %2 goes here; no use of %1
strong_release %2 : $MyOtherClass
strong_release %1 : $MyClass
@@ -1532,8 +1541,8 @@ A value ``%1`` is said to be *value-dependent* on a value ``%0`` if:
- ``%1`` is the result of ``mark_dependence`` and ``%0`` is either of
the operands.
-- ``%1`` is the value address of an allocation instruction of which
- ``%0`` is the local storage token or box reference.
+- ``%1`` is the value address of a box allocation instruction of which
+ ``%0`` is the box reference.
- ``%1`` is the result of a ``struct``, ``tuple``, or ``enum``
instruction and ``%0`` is an operand.
@@ -1604,16 +1613,18 @@ alloc_stack
```````````
::
- sil-instruction ::= 'alloc_stack' sil-type
+ sil-instruction ::= 'alloc_stack' sil-type (',' debug-var-attr)*
%1 = alloc_stack $T
- // %1#0 has type $*@local_storage T
- // %1#1 has type $*T
+ // %1 has type $*T
Allocates uninitialized memory that is sufficiently aligned on the stack
-to contain a value of type ``T``. The first result of the instruction
-is a local-storage handle suitable for passing to ``dealloc_stack``.
-The second result of the instruction is the address of the allocated memory.
+to contain a value of type ``T``. The result of the instruction is the address
+of the allocated memory.
+
+If a type is runtime-sized, the compiler must emit code to potentially
+dynamically allocate memory. So there is no guarantee that the allocated
+memory is really located on the stack.
``alloc_stack`` marks the start of the lifetime of the value; the
allocation must be balanced with a ``dealloc_stack`` instruction to
@@ -1671,7 +1682,7 @@ alloc_box
`````````
::
- sil-instruction ::= 'alloc_box' sil-type
+ sil-instruction ::= 'alloc_box' sil-type (',' debug-var-attr)*
%1 = alloc_box $T
// %1 has two values:
@@ -1714,16 +1725,16 @@ dealloc_stack
sil-instruction ::= 'dealloc_stack' sil-operand
- dealloc_stack %0 : $*@local_storage T
- // %0 must be of a local-storage $*@local_storage T type
+ dealloc_stack %0 : $*T
+ // %0 must be of $*T type
Deallocates memory previously allocated by ``alloc_stack``. The
allocated value in memory must be uninitialized or destroyed prior to
being deallocated. This instruction marks the end of the lifetime for
the value created by the corresponding ``alloc_stack`` instruction. The operand
-must be the ``@local_storage`` of the shallowest live ``alloc_stack``
-allocation preceding the deallocation. In other words, deallocations must be
-in last-in, first-out stack order.
+must be the shallowest live ``alloc_stack`` allocation preceding the
+deallocation. In other words, deallocations must be in last-in, first-out
+stack order.
dealloc_box
```````````
@@ -1860,7 +1871,7 @@ debug_value
::
- sil-instruction ::= debug_value sil-operand
+ sil-instruction ::= debug_value sil-operand (',' debug-var-attr)*
debug_value %1 : $Int
@@ -1870,12 +1881,24 @@ the SILLocation attached to the debug_value instruction.
The operand must have loadable type.
+::
+
+ debug-var-attr ::= 'var'
+ debug-var-attr ::= 'let'
+ debug-var-attr ::= 'name' string-literal
+ debug-var-attr ::= 'argno' integer-literal
+
+There are a number of attributes that provide details about the source
+variable that is being described, including the name of the
+variable. For function and closure arguments ``argno`` is the number
+of the function argument starting with 1.
+
debug_value_addr
````````````````
::
- sil-instruction ::= debug_value_addr sil-operand
+ sil-instruction ::= debug_value_addr sil-operand (',' debug-var-attr)*
debug_value_addr %7 : $*SomeProtocol
@@ -2168,23 +2191,6 @@ strong_retain
Increases the strong retain count of the heap object referenced by ``%0``.
-strong_retain_autoreleased
-``````````````````````````
-::
-
- sil-instruction ::= 'strong_retain_autoreleased' sil-operand
-
- strong_retain_autoreleased %0 : $T
- // $T must have a retainable pointer representation
-
-Retains the heap object referenced by ``%0`` using the Objective-C ARC
-"autoreleased return value" optimization. The operand must be the result of an
-``apply`` instruction with an Objective-C method callee, and the
-``strong_retain_autoreleased`` instruction must be first use of the value after
-the defining ``apply`` instruction.
-
-TODO: Specify all the other strong_retain_autoreleased constraints here.
-
strong_release
``````````````
::
@@ -2371,8 +2377,8 @@ function_ref
sil-instruction ::= 'function_ref' sil-function-name ':' sil-type
- %1 = function_ref @function : $@thin T -> U
- // $@thin T -> U must be a thin function type
+ %1 = function_ref @function : $@convention(thin) T -> U
+ // $@convention(thin) T -> U must be a thin function type
// %1 has type $T -> U
Creates a reference to a SIL function.
@@ -2462,7 +2468,7 @@ class_method
sil-instruction ::= 'class_method' sil-method-attributes?
sil-operand ',' sil-decl-ref ':' sil-type
- %1 = class_method %0 : $T, #T.method!1 : $@thin U -> V
+ %1 = class_method %0 : $T, #T.method!1 : $@convention(thin) U -> V
// %0 must be of a class type or class metatype $T
// #T.method!1 must be a reference to a dynamically-dispatched method of T or
// of one of its superclasses, at uncurry level >= 1
@@ -2491,11 +2497,11 @@ super_method
sil-instruction ::= 'super_method' sil-method-attributes?
sil-operand ',' sil-decl-ref ':' sil-type
- %1 = super_method %0 : $T, #Super.method!1.foreign : $@thin U -> V
+ %1 = super_method %0 : $T, #Super.method!1.foreign : $@convention(thin) U -> V
// %0 must be of a non-root class type or class metatype $T
// #Super.method!1.foreign must be a reference to an ObjC method of T's
// superclass or of one of its ancestor classes, at uncurry level >= 1
- // %1 will be of type $@thin U -> V
+ // %1 will be of type $@convention(thin) U -> V
Looks up a method in the superclass of a class or class metatype instance.
Note that for native Swift methods, ``super.method`` calls are statically
@@ -2511,13 +2517,13 @@ witness_method
sil-type ',' sil-decl-ref ':' sil-type
%1 = witness_method $T, #Proto.method!1 \
- : $@thin @cc(witness_method) U -> V
+ : $@convention(witness_method) U -> V
// $T must be an archetype
// #Proto.method!1 must be a reference to a method of one of the protocol
// constraints on T
// U -> V must be the type of the referenced method,
// generic on Self
- // %1 will be of type $@thin U -> V
+ // %1 will be of type $@convention(thin) U -> V
Looks up the implementation of a protocol method for a generic type variable
constrained by that protocol. The result will be generic on the ``Self``
@@ -2532,20 +2538,20 @@ dynamic_method
sil-instruction ::= 'dynamic_method' sil-method-attributes?
sil-operand ',' sil-decl-ref ':' sil-type
- %1 = dynamic_method %0 : $P, #X.method!1 : $@thin U -> V
+ %1 = dynamic_method %0 : $P, #X.method!1 : $@convention(thin) U -> V
// %0 must be of a protocol or protocol composition type $P,
// where $P contains the Swift.DynamicLookup protocol
// #X.method!1 must be a reference to an @objc method of any class
// or protocol type
//
- // The "self" argument of the method type $@thin U -> V must be
- // Builtin.ObjCPointer
+ // The "self" argument of the method type $@convention(thin) U -> V must be
+ // Builtin.UnknownObject
Looks up the implementation of an Objective-C method with the same
selector as the named method for the dynamic type of the
value inside an existential container. The "self" operand of the result
function value is represented using an opaque type, the value for which must
-be projected out as a value of type ``Builtin.ObjCPointer``.
+be projected out as a value of type ``Builtin.UnknownObject``.
It is undefined behavior if the dynamic type of the operand does not
have an implementation for the Objective-C method with the selector to
@@ -2584,7 +2590,7 @@ apply
// %1, %2, etc. must be of the argument types $A, $B, etc.
// %r will be of the return type $R
- %r = apply %0(%1, %2, ...) : $(T, U, ...) -> R
+ %r = apply %0(%1, %2, ...) : $(T, U, ...) -> R
// %0 must be of a polymorphic function type $(T, U, ...) -> R
// %1, %2, etc. must be of the argument types after substitution $A, $B, etc.
// %r will be of the substituted return type $R'
@@ -2628,7 +2634,7 @@ partial_apply
// of the tail part of the argument tuple of %0
// %c will be of the partially-applied thick function type (Z...) -> R
- %c = partial_apply %0(%1, %2, ...) : $(Z..., T, U, ...) -> R
+ %c = partial_apply %0(%1, %2, ...) : $(Z..., T, U, ...) -> R
// %0 must be of a polymorphic function type $(T, U, ...) -> R
// %1, %2, etc. must be of the argument types after substitution $A, $B, etc.
// of the tail part of the argument tuple of %0
@@ -2664,28 +2670,30 @@ curried function in Swift::
emits curry thunks in SIL as follows (retains and releases omitted for
clarity)::
- func @foo : $@thin A -> B -> C -> D -> E {
+ func @foo : $@convention(thin) A -> B -> C -> D -> E {
entry(%a : $A):
- %foo_1 = function_ref @foo_1 : $@thin (B, A) -> C -> D -> E
- %thunk = partial_apply %foo_1(%a) : $@thin (B, A) -> C -> D -> E
+ %foo_1 = function_ref @foo_1 : $@convention(thin) (B, A) -> C -> D -> E
+ %thunk = partial_apply %foo_1(%a) : $@convention(thin) (B, A) -> C -> D -> E
return %thunk : $B -> C -> D -> E
}
- func @foo_1 : $@thin (B, A) -> C -> D -> E {
+ func @foo_1 : $@convention(thin) (B, A) -> C -> D -> E {
entry(%b : $B, %a : $A):
- %foo_2 = function_ref @foo_2 : $@thin (C, B, A) -> D -> E
- %thunk = partial_apply %foo_2(%b, %a) : $@thin (C, B, A) -> D -> E
+ %foo_2 = function_ref @foo_2 : $@convention(thin) (C, B, A) -> D -> E
+ %thunk = partial_apply %foo_2(%b, %a) \
+ : $@convention(thin) (C, B, A) -> D -> E
return %thunk : $(B, A) -> C -> D -> E
}
- func @foo_2 : $@thin (C, B, A) -> D -> E {
+ func @foo_2 : $@convention(thin) (C, B, A) -> D -> E {
entry(%c : $C, %b : $B, %a : $A):
- %foo_3 = function_ref @foo_3 : $@thin (D, C, B, A) -> E
- %thunk = partial_apply %foo_3(%c, %b, %a) : $@thin (D, C, B, A) -> E
+ %foo_3 = function_ref @foo_3 : $@convention(thin) (D, C, B, A) -> E
+ %thunk = partial_apply %foo_3(%c, %b, %a) \
+ : $@convention(thin) (D, C, B, A) -> E
return %thunk : $(C, B, A) -> D -> E
}
- func @foo_3 : $@thin (D, C, B, A) -> E {
+ func @foo_3 : $@convention(thin) (D, C, B, A) -> E {
entry(%d : $D, %c : $C, %b : $B, %a : $A):
// ... body of foo ...
}
@@ -2702,12 +2710,12 @@ following example::
lowers to an uncurried entry point and is curried in the enclosing function::
- func @bar : $@thin (Int, @box Int, *Int) -> Int {
+ func @bar : $@convention(thin) (Int, @box Int, *Int) -> Int {
entry(%y : $Int, %x_box : $@box Int, %x_address : $*Int):
// ... body of bar ...
}
- func @foo : $@thin Int -> Int {
+ func @foo : $@convention(thin) Int -> Int {
entry(%x : $Int):
// Create a box for the 'x' variable
%x_box = alloc_box $Int
@@ -2716,7 +2724,7 @@ lowers to an uncurried entry point and is curried in the enclosing function::
// Create the bar closure
%bar_uncurried = function_ref @bar : $(Int, Int) -> Int
%bar = partial_apply %bar_uncurried(%x_box#0, %x_box#1) \
- : $(Int, Builtin.ObjectPointer, *Int) -> Int
+ : $(Int, Builtin.NativeObject, *Int) -> Int
// Apply it
%1 = integer_literal $Int, 1
@@ -2754,8 +2762,8 @@ metatype
sil-instruction ::= 'metatype' sil-type
- %1 = metatype $T.metatype
- // %1 has type $T.metatype
+ %1 = metatype $T.Type
+ // %1 has type $T.Type
Creates a reference to the metatype object for type ``T``.
@@ -2765,9 +2773,9 @@ value_metatype
sil-instruction ::= 'value_metatype' sil-type ',' sil-operand
- %1 = value_metatype $T.metatype, %0 : $T
+ %1 = value_metatype $T.Type, %0 : $T
// %0 must be a value or address of type $T
- // %1 will be of type $T.metatype
+ // %1 will be of type $T.Type
Obtains a reference to the dynamic metatype of the value ``%0``.
@@ -2777,10 +2785,10 @@ existential_metatype
sil-instruction ::= 'existential_metatype' sil-type ',' sil-operand
- %1 = existential_metatype $P.metatype, %0 : $P
+ %1 = existential_metatype $P.Type, %0 : $P
// %0 must be a value of class protocol or protocol composition
// type $P, or an address of address-only protocol type $*P
- // %1 will be a $P.metatype value referencing the metatype of the
+ // %1 will be a $P.Type value referencing the metatype of the
// concrete value inside %0
Obtains the metatype of the concrete value
@@ -2980,16 +2988,16 @@ the enum is injected with an `inject_enum_addr`_ instruction::
sil @init_with_data : $(AddressOnlyType) -> AddressOnlyEnum {
entry(%0 : $*AddressOnlyEnum, %1 : $*AddressOnlyType):
// Store the data argument for the case.
- %2 = init_enum_data_addr %0 : $*AddressOnlyEnum, #AddressOnlyEnum.HasData
+ %2 = init_enum_data_addr %0 : $*AddressOnlyEnum, #AddressOnlyEnum.HasData!enumelt.1
copy_addr [take] %2 to [initialization] %1 : $*AddressOnlyType
// Inject the tag.
- inject_enum_addr %0 : $*AddressOnlyEnum, #AddressOnlyEnum.HasData
+ inject_enum_addr %0 : $*AddressOnlyEnum, #AddressOnlyEnum.HasData!enumelt.1
return
}
sil @init_without_data : $() -> AddressOnlyEnum {
// No data. We only need to inject the tag.
- inject_enum_addr %0 : $*AddressOnlyEnum, #AddressOnlyEnum.NoData
+ inject_enum_addr %0 : $*AddressOnlyEnum, #AddressOnlyEnum.NoData!enumelt
return
}
@@ -3000,7 +3008,7 @@ discriminator and is done with the `switch_enum`_ terminator::
sil @switch_foo : $(Foo) -> () {
entry(%foo : $Foo):
- switch_enum %foo : $Foo, case #Foo.A: a_dest, case #Foo.B: b_dest
+ switch_enum %foo : $Foo, case #Foo.A!enumelt.1: a_dest, case #Foo.B!enumelt.1: b_dest
a_dest(%a : $Int):
/* use %a */
@@ -3017,14 +3025,15 @@ projecting the enum value with `unchecked_take_enum_data_addr`_::
sil @switch_foo : $ (Foo) -> () {
entry(%foo : $*Foo):
- switch_enum_addr %foo : $*Foo, case #Foo.A: a_dest, case #Foo.B: b_dest
+ switch_enum_addr %foo : $*Foo, case #Foo.A!enumelt.1: a_dest, \
+ case #Foo.B!enumelt.1: b_dest
a_dest:
- %a = unchecked_take_enum_data_addr %foo : $*Foo, #Foo.A
+ %a = unchecked_take_enum_data_addr %foo : $*Foo, #Foo.A!enumelt.1
/* use %a */
b_dest:
- %b = unchecked_take_enum_data_addr %foo : $*Foo, #Foo.B
+ %b = unchecked_take_enum_data_addr %foo : $*Foo, #Foo.B!enumelt.1
/* use %b */
}
@@ -3034,8 +3043,8 @@ enum
sil-instruction ::= 'enum' sil-type ',' sil-decl-ref (',' sil-operand)?
- %1 = enum $U, #U.EmptyCase
- %1 = enum $U, #U.DataCase, %0 : $T
+ %1 = enum $U, #U.EmptyCase!enumelt
+ %1 = enum $U, #U.DataCase!enumelt.1, %0 : $T
// $U must be an enum type
// #U.DataCase or #U.EmptyCase must be a case of enum $U
// If #U.Case has a data type $T, %0 must be a value of type $T
@@ -3051,7 +3060,7 @@ unchecked_enum_data
sil-instruction ::= 'unchecked_enum_data' sil-operand ',' sil-decl-ref
- %1 = unchecked_enum_data %0 : $U, #U.DataCase
+ %1 = unchecked_enum_data %0 : $U, #U.DataCase!enumelt.1
// $U must be an enum type
// #U.DataCase must be a case of enum $U with data
// %1 will be of object type $T for the data type of case U.DataCase
@@ -3066,7 +3075,7 @@ init_enum_data_addr
sil-instruction ::= 'init_enum_data_addr' sil-operand ',' sil-decl-ref
- %1 = init_enum_data_addr %0 : $*U, #U.DataCase
+ %1 = init_enum_data_addr %0 : $*U, #U.DataCase!enumelt.1
// $U must be an enum type
// #U.DataCase must be a case of enum $U with data
// %1 will be of address type $*T for the data type of case U.DataCase
@@ -3088,7 +3097,7 @@ inject_enum_addr
sil-instruction ::= 'inject_enum_addr' sil-operand ',' sil-decl-ref
- inject_enum_addr %0 : $*U, #U.Case
+ inject_enum_addr %0 : $*U, #U.Case!enumelt
// $U must be an enum type
// #U.Case must be a case of enum $U
// %0 will be overlaid with the tag for #U.Case
@@ -3108,7 +3117,7 @@ unchecked_take_enum_data_addr
sil-instruction ::= 'unchecked_take_enum_data_addr' sil-operand ',' sil-decl-ref
- %1 = unchecked_take_enum_data_addr %0 : $*U, #U.DataCase
+ %1 = unchecked_take_enum_data_addr %0 : $*U, #U.DataCase!enumelt.1
// $U must be an enum type
// #U.DataCase must be a case of enum $U with data
// %1 will be of address type $*T for the data type of case U.DataCase
@@ -3135,8 +3144,8 @@ select_enum
':' sil-type
%n = select_enum %0 : $U, \
- case #U.Case1: %1, \
- case #U.Case2: %2, /* ... */ \
+ case #U.Case1!enumelt: %1, \
+ case #U.Case2!enumelt: %2, /* ... */ \
default %3 : $T
// $U must be an enum type
@@ -3149,8 +3158,8 @@ enum value. This is equivalent to a trivial `switch_enum`_ branch sequence::
entry:
switch_enum %0 : $U, \
- case #U.Case1: bb1, \
- case #U.Case2: bb2, /* ... */ \
+ case #U.Case1!enumelt: bb1, \
+ case #U.Case2!enumelt: bb2, /* ... */ \
default bb_default
bb1:
br cont(%1 : $T) // value for #U.Case1
@@ -3174,8 +3183,8 @@ select_enum_addr
':' sil-type
%n = select_enum_addr %0 : $*U, \
- case #U.Case1: %1, \
- case #U.Case2: %2, /* ... */ \
+ case #U.Case1!enumelt: %1, \
+ case #U.Case2!enumelt: %2, /* ... */ \
default %3 : $T
// %0 must be the address of an enum type $*U
@@ -3605,7 +3614,7 @@ ref_to_raw_pointer
sil-instruction ::= 'ref_to_raw_pointer' sil-operand 'to' sil-type
%1 = ref_to_raw_pointer %0 : $C to $Builtin.RawPointer
- // $C must be a class type, or Builtin.ObjectPointer, or Builtin.ObjCPointer
+ // $C must be a class type, or Builtin.NativeObject, or Builtin.UnknownObject
// %1 will be of type $Builtin.RawPointer
Converts a heap object reference to a ``Builtin.RawPointer``. The ``RawPointer``
@@ -3620,7 +3629,7 @@ raw_pointer_to_ref
sil-instruction ::= 'raw_pointer_to_ref' sil-operand 'to' sil-type
%1 = raw_pointer_to_ref %0 : $Builtin.RawPointer to $C
- // $C must be a class type, or Builtin.ObjectPointer, or Builtin.ObjCPointer
+ // $C must be a class type, or Builtin.NativeObject, or Builtin.UnknownObject
// %1 will be of type $C
Converts a ``Builtin.RawPointer`` back to a heap object reference. Casting
@@ -3787,10 +3796,10 @@ thick_to_objc_metatype
sil-instruction ::= 'thick_to_objc_metatype' sil-operand 'to' sil-type
- %1 = thick_to_objc_metatype %0 : $@thick T.metatype to $@objc_metatype T.metatype
- // %0 must be of a thick metatype type $@thick T.metatype
+ %1 = thick_to_objc_metatype %0 : $@thick T.Type to $@objc_metatype T.Type
+ // %0 must be of a thick metatype type $@thick T.Type
// The destination type must be the corresponding Objective-C metatype type
- // %1 will be of type $@objc_metatype T.metatype
+ // %1 will be of type $@objc_metatype T.Type
Converts a thick metatype to an Objective-C class metatype. ``T`` must
be of class, class protocol, or class protocol composition type.
@@ -3801,10 +3810,10 @@ objc_to_thick_metatype
sil-instruction ::= 'objc_to_thick_metatype' sil-operand 'to' sil-type
- %1 = objc_to_thick_metatype %0 : $@objc_metatype T.metatype to $@thick T.metatype
- // %0 must be of an Objective-C metatype type $@objc_metatype T.metatype
+ %1 = objc_to_thick_metatype %0 : $@objc_metatype T.Type to $@thick T.Type
+ // %0 must be of an Objective-C metatype type $@objc_metatype T.Type
// The destination type must be the corresponding thick metatype type
- // %1 will be of type $@thick T.metatype
+ // %1 will be of type $@thick T.Type
Converts an Objective-C class metatype to a thick metatype. ``T`` must
be of class, class protocol, or class protocol composition type.
@@ -3936,23 +3945,6 @@ will be the operand of this ``return`` instruction.
A function must not contain more than one ``return`` instruction.
-autorelease_return
-``````````````````
-::
-
- sil-terminator ::= 'autorelease_return' sil-operand
-
- autorelease_return %0 : $T
- // $T must be the return type of the current function, which must be of
- // class type
-
-Exits the current function and returns control to the calling function. The
-result of the ``apply`` instruction that invoked the current function will be
-the operand of this ``return`` instruction. The return value is autoreleased
-into the active Objective-C autorelease pool using the "autoreleased return
-value" optimization. The current function must use the ``@cc(objc_method)``
-calling convention.
-
throw
`````
::
@@ -4041,7 +4033,7 @@ select_value
sil-instruction ::= 'select_value' sil-operand sil-select-value-case*
(',' 'default' sil-value)?
':' sil-type
- sil-selct-value-case ::= 'case' sil-value ':' sil-value
+ sil-select-value-case ::= 'case' sil-value ':' sil-value
%n = select_value %0 : $U, \
@@ -4054,7 +4046,7 @@ select_value
// %r1, %r2, %r3, etc. must have type $T
// %n has type $T
-Selects one of the "case" or "default" operands based on the case of an
+Selects one of the "case" or "default" operands based on the case of a
value. This is equivalent to a trivial `switch_value`_ branch sequence::
entry:
@@ -4082,8 +4074,8 @@ switch_enum
(',' sil-switch-default)?
sil-switch-enum-case ::= 'case' sil-decl-ref ':' sil-identifier
- switch_enum %0 : $U, case #U.Foo: label1, \
- case #U.Bar: label2, \
+ switch_enum %0 : $U, case #U.Foo!enumelt: label1, \
+ case #U.Bar!enumelt: label2, \
..., \
default labelN
@@ -4117,12 +4109,12 @@ original enum value. For example::
sil @sum_of_foo : $Foo -> Int {
entry(%x : $Foo):
switch_enum %x : $Foo, \
- case #Foo.Nothing: nothing, \
- case #Foo.OneInt: one_int, \
- case #Foo.TwoInts: two_ints
+ case #Foo.Nothing!enumelt: nothing, \
+ case #Foo.OneInt!enumelt.1: one_int, \
+ case #Foo.TwoInts!enumelt.1: two_ints
nothing:
- %zero = integer_literal 0 : $Int
+ %zero = integer_literal $Int, 0
return %zero : $Int
one_int(%y : $Int):
@@ -4158,8 +4150,8 @@ switch_enum_addr
(',' sil-switch-enum-case)*
(',' sil-switch-default)?
- switch_enum_addr %0 : $*U, case #U.Foo: label1, \
- case #U.Bar: label2, \
+ switch_enum_addr %0 : $*U, case #U.Foo!enumelt: label1, \
+ case #U.Bar!enumelt: label2, \
..., \
default labelN
@@ -4316,7 +4308,7 @@ constant replacement but leave the function application to be serialized to
sil).
The compiler flag that influences the value of the ``assert_configuration``
-funtion application is the optimization flag: at ``-Onone` the application will
+function application is the optimization flag: at ``-Onone` the application will
be replaced by ``Debug`` at higher optimization levels the instruction will be
replaced by ``Release``. Optionally, the value to use for replacement can be
specified with the ``-AssertConf`` flag which overwrites the value selected by
diff --git a/docs/SequencesAndCollections.rst b/docs/SequencesAndCollections.rst
index f6272314b22e1..3478e89d62dee 100644
--- a/docs/SequencesAndCollections.rst
+++ b/docs/SequencesAndCollections.rst
@@ -60,8 +60,8 @@ As you can see, sequence does nothing more than deliver a generator.
To understand the need for generators, it's important to distinguish
the two kinds of sequences.
-* **Volatile** sequences like “stream of network packets,” carry
- their own traversal state, and are expected to be “consumed” as they
+* **Volatile** sequences like "stream of network packets," carry
+ their own traversal state, and are expected to be "consumed" as they
are traversed.
* **Stable** sequences, like arrays, should *not* be mutated by `for`\
@@ -215,7 +215,7 @@ that stability in generic code, we'll need another protocol.
Collections
===========
-A **collection** is a stable sequence with addressable “positions,”
+A **collection** is a stable sequence with addressable "positions,"
represented by an associated `Index` type::
protocol CollectionType : SequenceType {
diff --git a/docs/StdlibAPIGuidelines.rst b/docs/StdlibAPIGuidelines.rst
index 26004130fac61..230bac5ae3967 100644
--- a/docs/StdlibAPIGuidelines.rst
+++ b/docs/StdlibAPIGuidelines.rst
@@ -102,7 +102,7 @@ Subsequent Parameters
Other Differences
-----------------
-* We don't use namespace prefixes such as “`NS`”, relying instead on
+* We don't use namespace prefixes such as "`NS`", relying instead on
the language's own facilities.
* Names of types, protocols and enum cases are `UpperCamelCase`.
@@ -156,7 +156,7 @@ library, but are compatible with the Cocoa guidelines.
}
* Even unlabelled parameter names should be meaningful as they'll be
- referred to in comments and visible in “generated headers”
+ referred to in comments and visible in "generated headers"
(cmd-click in Xcode):
.. parsed-literal::
@@ -200,12 +200,12 @@ Acceptable Short or Non-Descriptive Names
func map(transformation: T->U) -> [U] // not this one
- func forEach(body: (S.Generator.Element)->())
+ func forEach(body: (S.Generator.Element) -> ())
Prefixes and Suffixes
---------------------
-* `Any` is used as a prefix to denote “type erasure,”
+* `Any` is used as a prefix to denote "type erasure,"
e.g. `AnySequence` wraps any sequence with element type `T`,
conforms to `SequenceType` itself, and forwards all operations to the
wrapped sequence. When handling the wrapper, the specific type of
diff --git a/docs/StdlibRationales.rst b/docs/StdlibRationales.rst
index 8669653885f91..6b90b80d14935 100644
--- a/docs/StdlibRationales.rst
+++ b/docs/StdlibRationales.rst
@@ -64,7 +64,7 @@ generally *should* use a keyword. For example, ``String(33, radix:
they're converting. Secondly, avoiding method or property syntax
provides a distinct context for code completion. Rather than
appearing in completions offered after ``.``, for example, the
- available conversions could show up whenever the user hit the “tab”
+ available conversions could show up whenever the user hit the "tab"
key after an expression.
Protocols with restricted conformance rules
@@ -159,7 +159,7 @@ functions don't return lazy collection wrappers that refer to users' closures.
The consequence is that all users' closures are ``@noescape``, except in an
explicitly lazy context.
-Based on this rule, we conclude that ``enumeraate()``, ``zip()`` and
+Based on this rule, we conclude that ``enumerate(), ``zip()`` and
``reverse()`` return lazy wrappers, but ``filter()`` and ``map()`` don't. For
the first three functions being lazy is the right default, since usually the
result is immediately consumed by for-in, so we don't want to allocate memory
diff --git a/docs/StringDesign.rst b/docs/StringDesign.rst
index 52fcfca9d8b6b..5e56ace9a7390 100644
--- a/docs/StringDesign.rst
+++ b/docs/StringDesign.rst
@@ -116,9 +116,9 @@ Goals
``String`` should:
* honor industry standards such as Unicode
-* when handling non-ASCII text, deliver “reasonably correct”
+* when handling non-ASCII text, deliver "reasonably correct"
results to users thinking only in terms of ASCII
-* when handling ASCII text, provide “expected behavior” to users
+* when handling ASCII text, provide "expected behavior" to users
thinking only in terms of ASCII
* be hard to use incorrectly
* be easy to use correctly
@@ -165,7 +165,7 @@ optimizations, including:
- In-place modification of uniquely-owned buffers
As a result, copying_ and slicing__ strings, in particular, can be
-viewed by most programmers as being “almost free.”
+viewed by most programmers as being "almost free."
__ sliceable_
@@ -197,7 +197,7 @@ Strings are **Value Types**
Distinct string variables have independent values: when you pass
someone a string they get a copy of the value, and when someone
passes you a string *you own it*. Nobody can change a string value
-“behind your back.”
+"behind your back."
.. parsed-literal::
|swift| class Cave {
@@ -231,18 +231,18 @@ Strings are **Unicode-Aware**
specifies requires careful justification. So far, we have found two
possible points of deviation for Swift ``String``:
- 1. The `Unicode Text Segmentation Specification`_ says, “`do not
- break between CR and LF`__.” However, breaking extended
+ 1. The `Unicode Text Segmentation Specification`_ says, "`do not
+ break between CR and LF`__." However, breaking extended
grapheme clusters between CR and LF may necessary if we wish
- ``String`` to “behave normally” for users of pure ASCII. This
+ ``String`` to "behave normally" for users of pure ASCII. This
point is still open for discussion.
__ http://www.unicode.org/reports/tr29/#GB2
2. The `Unicode Text Segmentation Specification`_ says,
- “`do not break between regional indicator symbols`__.” However, it also
- says “(Sequences of more than two RI characters should be separated
- by other characters, such as U+200B ZWSP).” Although the
+ "`do not break between regional indicator symbols`__." However, it also
+ says "(Sequences of more than two RI characters should be separated
+ by other characters, such as U+200B ZWSP)." Although the
parenthesized note probably has less official weight than the other
admonition, breaking pairs of RI characters seems like the right
thing for us to do given that Cocoa already forms strings with
@@ -278,7 +278,7 @@ Strings are **Locale-Agnostic**
Strings neither carry their own locale information, nor provide
behaviors that depend on a global locale setting. Thus, for any pair
-of strings ``s1`` and ``s2``, “``s1 == s2``” yields the same result
+of strings ``s1`` and ``s2``, "``s1 == s2``" yields the same result
regardless of system state. Strings *do* provide a suitable
foundation on which to build locale-aware interfaces.\ [#locales]_
@@ -316,8 +316,8 @@ Strings are Composed of ``Character``\ s
cluster**, as specified by a default or tailored Unicode segmentation
algorithm. This term is `precisely defined`__ by the Unicode
specification, but it roughly means `what the user thinks of when she
-hears “character”`__. For example, the pair of code points “LATIN
-SMALL LETTER N, COMBINING TILDE” forms a single grapheme cluster, “ñ”.
+hears "character"`__. For example, the pair of code points "LATIN
+SMALL LETTER N, COMBINING TILDE" forms a single grapheme cluster, "ñ".
__ http://www.unicode.org/glossary/#grapheme_cluster
__ http://useless-factor.blogspot.com/2007/08/unicode-implementers-guide-part-4.html
@@ -342,8 +342,8 @@ __ http://www.unicode.org/glossary/#extended_grapheme_cluster
__ http://www.unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table
This segmentation offers naïve users of English, Chinese, French, and
-probably a few other languages what we think of as the “expected
-results.” However, not every script_ can be segmented uniformly for
+probably a few other languages what we think of as the "expected
+results." However, not every script_ can be segmented uniformly for
all purposes. For example, searching and collation require different
segmentations in order to handle Indic scripts correctly. To that
end, strings support properties for more-specific segmentations:
@@ -386,9 +386,9 @@ Strings are **Sliceable**
.. parsed-literal::
|swift| s[r.start...r.end]
`// r2 : String = "awe"`
- |swift| s[\ :look1:`r.start...`\ ]\ :aside:`postfix slice operator means “through the end”`
+ |swift| s[\ :look1:`r.start...`\ ]\ :aside:`postfix slice operator means "through the end"`
`// r3 : String = "awesome"`
- |swift| s[\ :look1:`...r.start`\ ]\ :aside:`prefix slice operator means “from the beginning”`
+ |swift| s[\ :look1:`...r.start`\ ]\ :aside:`prefix slice operator means "from the beginning"`
`// r4 : String = "Strings are "`
|swift| :look1:`s[r]`\ :aside:`indexing with a range is the same as slicing`
`// r5 : String = "awe"`
@@ -579,7 +579,7 @@ How Would You Design It?
5. CodePoint substring search is just byte string search
6. Most programs that handle 8-bit files safely can handle UTF-8 safely
7. UTF-8 sequences sort in code point order.
- 8. UTF-8 has no “byte order.”
+ 8. UTF-8 has no "byte order."
__ http://research.swtch.com/2010/03/utf-8-bits-bytes-and-benefits.html
@@ -682,7 +682,7 @@ withRange:subrange]`` becomes ``str[subrange].doFoo(arg)``.
* Deprecated Cocoa APIs are not considered
- * A status of “*Remove*” below indicates a feature whose removal is
+ * A status of "*Remove*" below indicates a feature whose removal is
anticipated. Rationale is provided for these cases.
Indexing
@@ -806,18 +806,18 @@ Comparison
func **<=** (lhs: String, rhs: String) -> Bool
func **>=** (lhs: String, rhs: String) -> Bool
-``NSString`` comparison is “literal” by default. As the documentation
+``NSString`` comparison is "literal" by default. As the documentation
says of ``isEqualToString``,
- “Ö” represented as the composed character sequence “O” and umlaut
- would not compare equal to “Ö” represented as one Unicode character.
+ "Ö" represented as the composed character sequence "O" and umlaut
+ would not compare equal to "Ö" represented as one Unicode character.
By contrast, Swift string's primary comparison interface uses
Unicode's default collation_ algorithm, and is thus always
-“Unicode-correct.” Unlike comparisons that depend on locale, it is
+"Unicode-correct." Unlike comparisons that depend on locale, it is
also stable across changes in system state. However, *just like*
``NSString``\ 's ``isEqualToString`` and ``compare`` methods, it
-should not be expected to yield ideal (or even “proper”) results in
+should not be expected to yield ideal (or even "proper") results in
all contexts.
---------
@@ -940,7 +940,7 @@ Searching
:Swift:
.. parsed-literal::
- func **find**\ (match: (Character)->Bool) -> Range
+ func **find**\ (match: (Character) -> Bool) -> Range
.. Admonition:: Usage Example
@@ -1084,10 +1084,10 @@ Capitalization
.. Note:: ``NSString`` capitalizes the first letter of each substring
separated by spaces, tabs, or line terminators, which is in
- no sense “Unicode-correct.” In most other languages that
+ no sense "Unicode-correct." In most other languages that
support a ``capitalize`` method, it operates only on the
first character of the string, and capitalization-by-word is
- named something like “``title``.” If Swift ``String``
+ named something like "``title``." If Swift ``String``
supports capitalization by word, it should be
Unicode-correct, but how we sort this particular area out is
still **TBD**.
@@ -1100,7 +1100,7 @@ Capitalization
:Swift:
.. parsed-literal::
- trim **trim**\ (match: (Character)->Bool) -> String
+ trim **trim**\ (match: (Character) -> Bool) -> String
.. Admonition:: Usage Example
@@ -1712,7 +1712,7 @@ Why YAGNI
* Derivation
* ...
-.. [#agnostic] Unicode specifies default (“un-tailored”)
+.. [#agnostic] Unicode specifies default ("un-tailored")
locale-independent collation_ and segmentation_ algorithms that
make reasonable sense in most contexts. Using these algorithms
allows strings to be naturally compared and combined, generating
@@ -1748,6 +1748,6 @@ Why YAGNI
been normalized, thus speeding up comparison operations.
.. [#elements] Since ``String`` is locale-agnostic_, its elements are
- determined using Unicode's default, “un-tailored” segmentation_
+ determined using Unicode's default, "un-tailored" segmentation_
algorithm.
diff --git a/docs/Testing.rst b/docs/Testing.rst
index be91cbd822dc2..8e5c39f8de1ed 100644
--- a/docs/Testing.rst
+++ b/docs/Testing.rst
@@ -200,7 +200,7 @@ code for the target that is not the build machine:
* ``%target-jit-run``: run a Swift program on the target machine using a JIT
compiler.
-* ``%target-swiftc_driver``: FIXME
+* ``%target-swiftc_driver``: run ``swiftc`` for the target.
* ``%target-sil-opt``: run ``sil-opt`` for the target.
@@ -212,15 +212,13 @@ code for the target that is not the build machine:
arguments*: like ``%target-swift-ide-test``, but allows to specify command
line parameters to use a mock SDK.
-* ``%target-swiftc_driver``: FIXME.
-
* ``%target-swift-autolink-extract``: run ``swift-autolink-extract`` for the
target to extract its autolink flags on platforms that support them (when the
autolink-extract feature flag is set)
* ``%target-clang``: run the system's ``clang++`` for the target.
- If you want to run the ``clang`` executable that was built alongside
+ If you want to run the ``clang`` executable that was built alongside
Swift, use ``%clang`` instead.
* ``%target-ld``: run ``ld`` configured with flags pointing to the standard
@@ -229,6 +227,30 @@ code for the target that is not the build machine:
* ``%target-cc-options``: the clang flags to setup the target with the right
architecture and platform version.
+* ``%target-triple``: a triple composed of the ``%target-cpu``, the vendor,
+ the ``%target-os``, and the operating system version number. Possible values
+ include ``i386-apple-ios7.0`` or ``armv7k-apple-watchos2.0``.
+
+* ``%target-cpu``: the target CPU instruction set (``i386``, ``x86_64``,
+ ``armv7``, ``armv7k``, ``arm64``).
+
+* ``%target-os``: the target operating system (``macosx``, ``darwin``,
+ ``linux``, ``freebsd``).
+
+* ``%target-object-format``: the platform's object format (``elf``, ``macho``,
+ ``coff``).
+
+* ``%target-runtime``: the platform's Swift runtime (objc, native).
+
+* ``%target-ptrsize``: the pointer size of the target (32, 64).
+
+* ``%target-swiftmodule-name`` and ``%target-swiftdoc-name``: the basename of
+ swiftmodule and swiftdoc files for a framework compiled for the target (for
+ example, ``arm64.swiftmodule`` and ``arm64.swiftdoc``).
+
+* ``%target-sdk-name``: only for Apple platforms: ``xcrun``-style SDK name
+ (``macosx``, ``iphoneos``, ``iphonesimulator``).
+
Always use ``%target-*`` substitutions unless you have a good reason. For
example, an exception would be a test that checks how the compiler handles
mixing module files for incompatible platforms (that test would need to compile
@@ -236,33 +258,53 @@ Swift code for two different platforms that are known to be incompatible).
When you can't use ``%target-*`` substitutions, you can use:
-* ``%swift_driver_plain``: FIXME.
-* ``%swiftc_driver_plain``: FIXME.
-* ``%swift_driver``: FIXME.
-* ``%swiftc_driver``: FIXME.
-* ``%sil-opt``: FIXME.
-* ``%sil-extract``: FIXME.
-* ``%lldb-moduleimport-test``: FIXME.
-* ``%swift-ide-test_plain``: FIXME.
-* ``%swift-ide-test``: FIXME.
-* ``%llvm-opt``: FIXME.
-* ``%swift``: FIXME.
-* ``%clang-include-dir``: FIXME.
-* ``%clang-importer-sdk``: FIXME.
+* ``%swift_driver_plain``: run ``swift`` for the build machine.
+
+* ``%swift_driver``: like ``%swift_driver_plain`` with ``-module-cache-path``
+ set to a temporary directory used by the test suite, and using the
+ ``SWIFT_TEST_OPTIONS`` environment variable if available.
+
+* ``%swiftc_driver``: like ``%target-swiftc_driver`` for the build machine.
+
+* ``%swiftc_driver_plain``: like ``%swiftc_driver``, but does not set the
+ ``-module-cache-path`` to a temporary directory used by the test suite,
+ and does not respect the ``SWIFT_TEST_OPTIONS`` environment variable.
+
+* ``%sil-opt``: like ``%target-sil-opt`` for the build machine.
+
+* ``%sil-extract``: run ``%target-sil-extract`` for the build machine.
+
+* ``%lldb-moduleimport-test``: run ``lldb-moduleimport-test`` for the build
+ machine in order simulate importing LLDB importing modules from the
+ ``__apple_ast`` section in Mach-O files. See
+ ``tools/lldb-moduleimport-test/`` for details.
+
+* ``%swift-ide-test``: like ``%target-swift-ide-test`` for the build machine.
+
+* ``%swift-ide-test_plain``: like ``%swift-ide-test``, but does not set the
+ ``-module-cache-path`` or ``-completion-cache-path`` to temporary directories
+ used by the test suite.
+
+* ``%swift``: like ``%target-swift-frontend`` for the build machine.
+
+* ``%clang``: run the locally-built ``clang``. To run ``clang++`` for the
+ target, use ``%target-clang``.
Other substitutions:
-* ``%leaks-runner``: FIXME.
-* ``%clang_apinotes``: FIXME.
-* ``%clang``: FIXME.
-* ``%target-triple``: FIXME, possible values.
-* ``%target-cpu``: FIXME, possible values.
-* ``%target-os``: FIXME, possible values.
-* ``%target-object-format``: the platform's object format (elf, macho, coff).
-* ``%target-runtime``: the platform's Swift runtime (objc, native).
-* ``%target-ptrsize``: the pointer size of the target (32, 64).
-* ``%sdk``: FIXME.
-* ``%gyb``: FIXME.
+* ``%clang-include-dir``: absolute path of the directory where the Clang
+ include headers are stored on Linux build machines.
+
+* ``%clang-importer-sdk``: FIXME.
+
+* ``%clang_apinotes``: run ``clang -cc1apinotes`` using the locally-built
+ clang.
+
+* ``%sdk``: only for Apple platforms: the ``SWIFT_HOST_VARIANT_SDK`` specified
+ by tools/build-script. Possible values include ``IOS`` or ``TVOS_SIMULATOR``.
+
+* ``%gyb``: run ``gyb``, a boilerplate generation script. For details see
+ ``utils/gyb``.
* ``%platform-module-dir``: absolute path of the directory where the standard
library module file for the target platform is stored. For example,
@@ -271,12 +313,8 @@ Other substitutions:
* ``%platform-sdk-overlay-dir``: absolute path of the directory where the SDK
overlay module files for the target platform are stored.
-* ``%target-swiftmodule-name`` and ``%target-swiftdoc-name``: the basename of
- swiftmodule and swiftdoc files for a framework compiled for the target (for
- example, ``arm64.swiftmodule`` and ``arm64.swiftdoc``).
-
-* ``%target-sdk-name``: only for Apple platforms: ``xcrun``-style SDK name
- (``macosx``, ``iphoneos``, ``iphonesimulator``).
+* ``%{python}``: run the same Python interpreter that's being used to run the
+ current ``lit`` test.
When writing a test where output (or IR, SIL) depends on the bitness of the
target CPU, use this pattern::
@@ -319,7 +357,7 @@ CPU=i386_or_x86_64`` to ``REQUIRES: CPU=x86_64``.
``swift_test_mode_optimize[_unchecked|none]_`` to specify a test mode
plus cpu configuration.
-``optimized_stdlib_``` to specify a optimized stdlib plus cpu
+``optimized_stdlib_``` to specify an optimized stdlib plus cpu
configuration.
Feature ``REQUIRES: executable_test``
diff --git a/docs/TextFormatting.rst b/docs/TextFormatting.rst
index c57f721746286..30e47ef83eb5a 100644
--- a/docs/TextFormatting.rst
+++ b/docs/TextFormatting.rst
@@ -21,9 +21,9 @@ Scope
Goals
.....
-* The REPL and LLDB (“debuggers”) share formatting logic
-* All types are “debug-printable” automatically
-* Making a type “printable for humans” is super-easy
+* The REPL and LLDB ("debuggers") share formatting logic
+* All types are "debug-printable" automatically
+* Making a type "printable for humans" is super-easy
* ``toString()``-ability is a consequence of printability.
* Customizing a type's printed representations is super-easy
* Format variations such as numeric radix are explicit and readable
@@ -43,11 +43,11 @@ Non-Goals
that feature. Therefore, localization and dynamic format strings
should be designed together, and *under this proposal* the only
format strings are string literals containing interpolations
- (“``\(...)``”). Cocoa programmers can still use Cocoa localization
+ ("``\(...)``"). Cocoa programmers can still use Cocoa localization
APIs for localization jobs.
In Swift, only the most common cases need to be very terse.
- Anything “fancy” can afford to be a bit more verbose. If and when
+ Anything "fancy" can afford to be a bit more verbose. If and when
we address localization and design a full-featured dynamic string
formatter, it may make sense to incorporate features of ``printf``
into the design.
@@ -68,7 +68,7 @@ printed with ``print(x)``, and can be converted to ``String`` with
The simple extension story for beginners is as follows:
- “To make your type ``CustomStringConvertible``, simply declare conformance to
+ "To make your type ``CustomStringConvertible``, simply declare conformance to
``CustomStringConvertible``::
extension Person : CustomStringConvertible {}
@@ -129,8 +129,7 @@ Debug Printing
Via compiler magic, *everything* conforms to the ``CustomDebugStringConvertible``
protocol. To change the debug representation for a type, you don't
-need to declare conformance: simply give the type a ``debugFormat()``
-::
+need to declare conformance: simply give the type a ``debugFormat()``::
/// \brief A thing that can be printed in the REPL and the Debugger
protocol CustomDebugStringConvertible {
@@ -153,9 +152,9 @@ directly to the ``OutputStream`` for efficiency reasons,
Producing a representation that can be consumed by the REPL
and LLDB to produce an equivalent object is strongly encouraged
where possible! For example, ``String.debugFormat()`` produces
- a representation starting and ending with “``"``”, where special
+ a representation starting and ending with "``"``", where special
characters are escaped, etc. A ``struct Point { var x, y: Int }``
- might be represented as “``Point(x: 3, y: 5)``”.
+ might be represented as "``Point(x: 3, y: 5)``".
(Non-Debug) Printing
....................
@@ -199,7 +198,7 @@ Because it's not always efficient to construct a ``String``
representation before writing an object to a stream, we provide a
``Streamable`` protocol, for types that can write themselves into an
``OutputStream``. Every ``Streamable`` is also a ``CustomStringConvertible``,
-naturally ::
+naturally::
protocol Streamable : CustomStringConvertible {
func writeTo(target: [inout] T)
@@ -349,7 +348,7 @@ an underlying stream::
However, upcasing is a trivial example: many such transformations—such
as ``trim()`` or regex replacement—are stateful, which implies some
-way of indicating “end of input” so that buffered state can be
+way of indicating "end of input" so that buffered state can be
processed and written to the underlying stream:
.. parsed-literal::
@@ -423,10 +422,10 @@ If we were willing to say that only ``class``\ es can conform to
``OutputStream``\ s are passed around. Then, we'd simply need a
``class StringStream`` for creating ``String`` representations. It
would also make ``OutputStream`` adapters a *bit* simpler to use
-because you'd never need to “write back” explicitly onto the target
+because you'd never need to "write back" explicitly onto the target
stream. However, stateful ``OutputStream`` adapters would still need a
``close()`` method, which makes a perfect place to return a copy of
-the underlying stream, which can then be “written back.” :
+the underlying stream, which can then be "written back":
.. parsed-literal::
diff --git a/docs/TypeChecker.rst b/docs/TypeChecker.rst
index 73c54c4c39354..fb1856eb30645 100644
--- a/docs/TypeChecker.rst
+++ b/docs/TypeChecker.rst
@@ -126,12 +126,12 @@ the Swift type system:
to the second, which includes subtyping and equality. Additionally,
it allows a user-defined conversion function to be
called. Conversion constraints are written ``X {
@@ -376,10 +376,10 @@ has a regular structure. For example, consider the ``Optional`` type::
case Some(T)
}
-The type of ``Optional.Vone`` is ``Optional``, while the type of
+The type of ``Optional.None`` is ``Optional``, while the type of
``Optional.Some`` is ``(T) -> Optional``. In fact, the
-type of a enum element can have one of two forms: it can be ``T0``,
-for a enum element that has no extra data, or it can be ``T2 -> T0``,
+type of an enum element can have one of two forms: it can be ``T0``,
+for an enum element that has no extra data, or it can be ``T2 -> T0``,
where ``T2`` is the data associated with the enum element. For the
latter case, the actual arguments are parsed as part of the unresolved
member reference, so that a function application constraint describes
@@ -403,8 +403,8 @@ concrete type, so long as that type conforms to the protocol
``Comparable``. The type of ``min`` is (internally) written as `` (x: T, y: T) -> T``, which can be read as "for all ``T``,
where ``T`` conforms to ``Comparable``, the type of the function is
-``(x: T, y: T) -> T``. Different uses of the ``min`` function may
-have different bindings for the generic parameter``T``.
+``(x: T, y: T) -> T``." Different uses of the ``min`` function may
+have different bindings for the generic parameter ``T``.
When the constraint generator encounters a reference to a generic
function, it immediately replaces each of the generic parameters within
@@ -433,8 +433,8 @@ solver. For example, consider the following generic dictionary type::
// ...
}
-When the constraint solver encounters the expression ``
-Dictionary()``, it opens up the type ``Dictionary``---which has not
+When the constraint solver encounters the expression ``Dictionary()``,
+it opens up the type ``Dictionary``---which has not
been provided with any specific generic arguments---to the type
``Dictionary``, for fresh type variables ``T0`` and ``T1``,
and introduces the constraint ``T0 conforms to Hashable``. This allows
@@ -530,7 +530,7 @@ constraint ``A.member == B`` can be simplified when the type of ``A``
is determined to be a nominal or tuple type, in which case name lookup
can resolve the member name to an actual declaration. That declaration
has some type ``C``, so the member constraint is simplified to the
-exact equality constraint``B := C``.
+exact equality constraint ``B := C``.
The member name may refer to a set of overloaded declarations. In this
case, the type ``C`` is a fresh type variable (call it ``T0``). A
@@ -736,12 +736,12 @@ checking problem::
f(10.5, x)
This constraint system generates the constraints "``T(f)`` ==Fn ``T0
--> T1``" (for fresh variables ``T0`` and ``T1``), "``(T2, X)`` T1``" (for fresh variables ``T0`` and ``T1``), "``(T2, X) T1``" constraint has a locator that is
anchored at the function application and a path with the "apply
function" derivation step, meaning that this is the function being
-applied. Similarly, the "``(T2, X)`` Infix Attributes
FIXME: Implement these restrictions.
- Resilience Attribute
+ Resilience Attribute
attribute-resilience ::= 'resilient'
@@ -786,7 +786,7 @@ inout Attribute
inout indicates that the argument will be passed as an "in-out"
- parameter. The caller must pass an lvalue decorated with the &
+ parameter. The caller must pass an lvalue decorated with the &
prefix operator as the argument. Semantically, the value of the argument
is passed "in" to the callee to a local value, and that local value is
stored back "out" to the lvalue when the callee exits. This is normally
@@ -837,7 +837,7 @@
inout Attribute
The type being annotated must be materializable.
- The type after annotation is never materializable.
+ The type after annotation is never materializable.
FIXME: we probably need a const-like variant, which permits
r-values (and avoids writeback when the l-value is not physical).
@@ -1195,7 +1195,7 @@
Array Types
Array types include a base type and an optional size. Array types indicate
- a linear sequence of elements stored consequtively memory. Array elements may
+ a linear sequence of elements stored consecutively memory. Array elements may
be efficiently indexed in constant time. All array indexes are bounds checked
and out of bound accesses are diagnosed with either a compile time or
runtime failure (TODO: runtime failure mode not specified).
@@ -1295,10 +1295,13 @@ Optional Types
T?
.
To support these intrinsic use cases, the library is required to
- provide four functions with these exact signatures:
+ provide functions with these exact signatures:
- func _preconditionOptionalHasValue(inout v : T?)
+ func _doesOptionalHaveValueAsBool(v : T?) -> Bool
+ func _diagnoseUnexpectedNilOptional()
func _getOptionalValue(v : T?) -> T
+ func _injectValueIntoOptional(v : T) -> T?
+ func _injectNothingIntoOptional() -> T?
@@ -1317,7 +1320,7 @@ Optional Types
var b : Int? = .None
// Declare an array of optionals:
- var c : Int?[] = new Int?[4]
+ var c : [Int?] = [10, nil, 42]
@@ -1898,7 +1901,7 @@ Closure Expression
// both have type 'Int'.
magic(42, { $0 < $1 })
- // Compare the other way way.
+ // Compare the other way.
magic(42, { $1 < $0 })
// Provide parameter names, but infer the types.
@@ -2388,7 +2391,7 @@ 'while' Statement
'while' statements provide simple loop construct which (on each iteration
- of the loop) evalutes the condition, gets the 'boolValue' property of
+ of the loop) evaluates the condition, gets the 'boolValue' property of
the result if the result not a 'Bool', then determines whether to keep
looping. (Internally, the standard library type 'Bool' has a boolValue
property that yields a 'Builtin.Int1'.) It is an error if the type of
@@ -2449,7 +2452,7 @@
C-Style 'for' Statement
C-Style 'for' statements provide simple loop construct which evaluates the
- first part (the initializer) before entering the loop, then evalutes the
+ first part (the initializer) before entering the loop, then evaluates the
second condition as a logic value to determines whether to keep looping.
The third condition is executed at the end of the loop. All three are
evaluated in a new scope that surrounds the for statement.
diff --git a/docs/archive/LangRefNew.rst b/docs/archive/LangRefNew.rst
index 21fb5523d82c6..e1bccc4973106 100644
--- a/docs/archive/LangRefNew.rst
+++ b/docs/archive/LangRefNew.rst
@@ -40,7 +40,7 @@ Basic Goals
In no particular order, and not explained well:
* Support building great frameworks and applications, with a specific focus on
- permiting rich and powerful APIs.
+ permitting rich and powerful APIs.
* Get the defaults right: this reduces the barrier to entry and increases the
odds that the right thing happens.
* Through our support for building great APIs, we aim to provide an expressive
@@ -54,7 +54,7 @@ In no particular order, and not explained well:
ideas already out there.
* Memory safe by default: array overrun errors, uninitialized values, and other
problems endemic to C should not occur in Swift, even if it means some amount
- of runtime overhead. Eventually these checks will be disablable for people
+ of runtime overhead. Eventually these checks will be disableable for people
who want ultimate performance in production builds.
* Efficiently implementable with a static compiler: runtime compilation is
great technology and Swift may eventually get a runtime optimizer, but it is
@@ -752,7 +752,7 @@ protocols.
}
We disambiguate towards ``get-set`` or ``willset-didset`` production if the
- first token after ``{`` is the corresponding keyword, possibly preceeded by
+ first token after ``{`` is the corresponding keyword, possibly preceded by
attributes. Thus, the following code is rejected because we are expecting
``{`` after ``set``:
@@ -782,7 +782,7 @@ protocols.
}
We disambiguate towards ``willget-didset`` production if the first token
- after ``{`` is the keyword ``willSet`` or ``didSet``, possibly preceeded by
+ after ``{`` is the keyword ``willSet`` or ``didSet``, possibly preceded by
attributes.
.. admonition:: Rationale
@@ -1424,7 +1424,7 @@ into every file. Its declarations can only be found by dot
syntax. It provides access to a small number of primitive representation
types and operations defined over them that map directly to LLVM IR.
-The existance of and details of this module are a private implementation detail
+The existence of and details of this module are a private implementation detail
used by our implementation of the standard library. Swift code outside the
standard library should not be aware of this library, and an independent
implementation of the swift standard library should be allowed to be
@@ -1537,8 +1537,8 @@ Short Circuiting Logical Operators
::
- func && (lhs: Bool, rhs: ()->Bool) -> Bool
- func || (lhs: Bool, rhs: ()->Bool) -> Bool
+ func && (lhs: Bool, rhs: () -> Bool) -> Bool
+ func || (lhs: Bool, rhs: () -> Bool) -> Bool
Swift has a simplified precedence levels when compared with C. From highest to
lowest:
@@ -1551,5 +1551,3 @@ lowest:
"comparative:" ==, !=, <, <=, >=, >
"conjunctive:" &&
"disjunctive:" ||
-
-
diff --git a/docs/archive/Namespace Level Vars and Top Level Code.rst b/docs/archive/Namespace Level Vars and Top Level Code.rst
index ba140a8286acd..2ac134fdd0eae 100644
--- a/docs/archive/Namespace Level Vars and Top Level Code.rst
+++ b/docs/archive/Namespace Level Vars and Top Level Code.rst
@@ -68,10 +68,10 @@ does top level code and multiple actors. As such, the logical semantics are:
lazily.
3. Source files that have TLC are each initialized in a deterministic order: The
dependence graph of domains is respected (lower level domains are initialized
- before dependent ones), and the source files withing a domain are initialized
+ before dependent ones), and the source files within a domain are initialized
in some deterministic order (perhaps according to their filename or
something, TBD).
-4. Within a source file with TLC, the TLC is run top down in determinstic order
+4. Within a source file with TLC, the TLC is run top down in deterministic order
whenever the file's initializer is run. This initializer executes in the
context of the "first" actor, which is created on behalf of the program by
the runtime library.
diff --git a/docs/archive/Objective-C Interoperability.rst b/docs/archive/Objective-C Interoperability.rst
index c8921e0107a43..70efb8bbbfc83 100644
--- a/docs/archive/Objective-C Interoperability.rst
+++ b/docs/archive/Objective-C Interoperability.rst
@@ -216,7 +216,7 @@ Non-NSObjects are messageable but not ``id``-compatible:
- Cannot assign Swift objects to ``id`` variables.
- Cannot put arbitrary Swift objects in NSArrays.
- Potentially confusing: "I can message it but I can't put it in an ``id``??"
-- Clang must be taught how to message Swift objects and manage their retain
+- Clang must be taught how to message Swift objects and manage their retain
counts.
- On the plus side, then non-NSObjects can use Swift calling conventions.
- Requires framework authors to make an arbitrary decision that may not be
@@ -315,18 +315,18 @@ Method Overriding Model
*Requirement: Swift classes can override any Objective-C methods.*
-Methods marked as "overrideable API" only have Objective-C entry points:
+Methods marked as "overridable API" only have Objective-C entry points:
- Less to think about, maximum compatibility.
- Penalizes future Swift clients (and potentially Objective-C clients?).
-Methods marked as "overrideable API" have both Objective-C and Swift entry
+Methods marked as "overridable API" have both Objective-C and Swift entry
points:
- Requires teaching Clang to emit Swift vtables.
- Increases binary size and link time.
-Methods marked as "overrideable API" have only Swift entry points:
+Methods marked as "overridable API" have only Swift entry points:
- Requires teaching Clang to emit Swift vtables.
- Later exposing this method to Objective-C in a subclass may be awkward?
diff --git a/docs/conf.py b/docs/conf.py
index 968e48416374a..142245c748835 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -10,7 +10,7 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
-import sys, os
+import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
@@ -250,7 +250,7 @@
#texinfo_show_urls = 'footnote'
-# FIXME: Define intersphinx configration.
+# FIXME: Define intersphinx configuration.
intersphinx_mapping = {}
diff --git a/docs/doxygen.cfg.in b/docs/doxygen.cfg.in
index 5468e2386843e..6b56723b5d5f1 100644
--- a/docs/doxygen.cfg.in
+++ b/docs/doxygen.cfg.in
@@ -1,9 +1,9 @@
# Doxyfile 1.4.4
# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
+# doxygen (www.doxygen.org) for a project.
#
-# All text after a hash (#) is considered a comment and will be ignored
+# All text after a hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists items can also be appended using:
@@ -385,7 +385,7 @@ SHOW_DIRECTORIES = YES
# version control system). Doxygen will invoke the program by executing (via
# popen()) the command , where is the value of
# the FILE_VERSION_FILTER tag, and is the name of an input file
-# provided by doxygen. Whatever the progam writes to standard output
+# provided by doxygen. Whatever the program writes to standard output
# is used as the file version. See the manual for examples.
#FILE_VERSION_FILTER =
@@ -418,7 +418,7 @@ WARN_IF_UNDOCUMENTED = NO
WARN_IF_DOC_ERROR = YES
-# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for
# functions that are documented, but have no documentation for their parameters
# or return value. If set to NO (the default) doxygen will only warn about
# wrong or incomplete parameter documentation, but not about the absence of
@@ -1063,7 +1063,7 @@ PERL_PATH =
#---------------------------------------------------------------------------
# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# generate an inheritance diagram (in HTML, RTF and LaTeX) for classes with base
# or super classes. Setting the tag to NO turns the diagrams off. Note that
# this option is superseded by the HAVE_DOT option below. This is only a
# fallback. It is recommended to install and use dot, since it yields more
@@ -1239,7 +1239,7 @@ SEARCHENGINE = @enable_searchengine@
# using Javascript. Doxygen will generate the search PHP script and index
# file to put on the web server. The advantage of the server
# based approach is that it scales better to large projects and allows
-# full text search. The disadvances is that it is more difficult to setup
+# full text search. The disadvantage is that it is more difficult to setup
# and does not have live searching capabilities.
SERVER_BASED_SEARCH = @enable_server_based_search@
diff --git a/docs/doxygen.css b/docs/doxygen.css
index 83951f673db8d..d5691ed7e62d1 100644
--- a/docs/doxygen.css
+++ b/docs/doxygen.css
@@ -313,8 +313,8 @@ HR { height: 1px;
/*
* LLVM Modifications.
- * Note: Everything above here is generated with "doxygen -w htlm" command. See
- * "doxygen --help" for details. What follows are CSS overrides for LLVM
+ * Note: Everything above here is generated with "doxygen -w html" command. See
+ * "doxygen --help" for details. What follows are CSS overrides for LLVM
* specific formatting. We want to keep the above so it can be replaced with
* subsequent doxygen upgrades.
*/
diff --git a/docs/proposals/Accessors.rst b/docs/proposals/Accessors.rst
index 2af6d07517a36..da5da10f0426b 100644
--- a/docs/proposals/Accessors.rst
+++ b/docs/proposals/Accessors.rst
@@ -87,7 +87,7 @@ objects::
point = point1
point0.x = x
point = point0
-
+
Note that ``point.y`` is left unchanged.
Local analysis
@@ -157,7 +157,7 @@ through unexpected aliases::
Note that, in either solution, you've introduced extra full-value
loads. This may be quite expensive, and it's not guaranteed to be
semantically equivalent.
-
+
Performance
~~~~~~~~~~~
@@ -453,7 +453,7 @@ Nor can this be fixed with a purely local analysis; consider::
class C { var array: [Int] }
let global_C = C()
-
+
func assign(inout value: Int) {
C.array = []
value = 0
@@ -606,7 +606,7 @@ General solutions
~~~~~~~~~~~~~~~~~
A language generally has six tools for dealing with code it considers
-undesireable. Some of this terminology is taken from existing
+undesirable. Some of this terminology is taken from existing
standards, others not.
* The language may nonetheless take steps to ensure that the code
@@ -704,7 +704,7 @@ that was technically copied beforehand. For example::
var oldArray : [Int] = []
// This function copies array before modifying it, but because that
- // copy is of an value undergoing modification, the copy will use
+ // copy is of a value undergoing modification, the copy will use
// the same buffer and therefore observe updates to the element.
func foo(inout element: Int) {
oldArray = array
@@ -856,7 +856,7 @@ depend on how the l-value is used:
that ``left`` contains a value::
// begin FA for ? operand left (DSN={})
- // instataneous FA reading right (DSN={})
+ // instantaneous FA reading right (DSN={})
// begin FA for inout argument left?.member (DSN={lhs})
// evaluation of +=
// end FA for inout argument left?.member
@@ -916,7 +916,7 @@ I'm almost ready to state the core rule about formal accesses, but
first I need to build up a few more definitions.
An *abstract storage location* (ASL) is:
-
+
* a global variable declaration;
* an ``inout`` parameter declaration, along with a reference
@@ -1027,7 +1027,7 @@ summary of the rule being proposed.
If storage is passed to an ``inout`` argument, then any other
simultaneous attempt to read or write to that storage, including to
-the storage containing it, will have have unspecified behavior. Reads
+the storage containing it, will have unspecified behavior. Reads
from it may see partially-updated values, or even values which will
change as modifications are made to the original storage; and writes
may be clobbered or simply disappear.
@@ -1106,7 +1106,7 @@ the other FA's DSN set and (2) not from a non-overlapping subobject.
Are these conditions true?
Recall that an addressor is invoked for an l-value of the form::
-
+
base.memory
or::
@@ -1296,7 +1296,7 @@ Code generation patterns
The signatures and access patterns for addressors will need to change
in order to ensure memory-safety.
-``mutableAddress`` currentlys returns an ``UnsafeMutablePointer``; it
+``mutableAddress`` currently returns an ``UnsafeMutablePointer``; it
will need to return ``(Builtin.NativeObject?, UnsafeMutablePointer)``.
The owner pointer must be a native object; we cannot efficiently
support either uniqueness checking or the NSM bit on non-Swift
diff --git a/docs/proposals/ArrayBridge.rst b/docs/proposals/ArrayBridge.rst
index 163fb487874f7..8cd5bb1087bdd 100644
--- a/docs/proposals/ArrayBridge.rst
+++ b/docs/proposals/ArrayBridge.rst
@@ -4,7 +4,7 @@
..
.. This source file is part of the Swift.org open source project
..
-.. Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+.. Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
.. Licensed under Apache License v2.0 with Runtime Library Exception
..
.. See http://swift.org/LICENSE.txt for license information
@@ -71,7 +71,7 @@ significant. For example, the design above would pose significant performance
problems for arrays of integers, because every subscript operation would have to
check to see if the representation is an NSArray, realize it is not, then do the
constant time index into the native representation. Beyond requiring an extra
-check, this check would disable optimizations that can provide a signficant
+check, this check would disable optimizations that can provide a significant
performance win (like auto-vectorization).
However, the inherent limitations of ``NSArray`` mean that we can
diff --git a/docs/proposals/AttrC.rst b/docs/proposals/AttrC.rst
index 2c4d2cf193b88..aaaa6069be50e 100644
--- a/docs/proposals/AttrC.rst
+++ b/docs/proposals/AttrC.rst
@@ -4,7 +4,7 @@ Eventually, we would like to write Swift modules which define pure-C entry
points for top-level functions, and be able to export more data types to
C code.
-This will be imporant for the Linux port, but also perhaps for system
+This will be important for the Linux port, but also perhaps for system
frameworks that want to transition to Swift.
The radars tracking this work are:
@@ -59,14 +59,14 @@ and "non-POD". POD types include:
On Linux, we can't have reference counted pointers here at all, and
NSArray, etc do not exist, so only POD types are bridgeable. We must
-ensure that we produce ther right diagnostic and not crash when the
+ensure that we produce the right diagnostic and not crash when the
user references NSArray, etc on Linux.
On Darwin, we can allow passing reference counted pointers directly
as function parameters. They are still not allowed as fields in ``@c``
structs, though.
-The convention for arguments and results an be the same as CoreFoundation
+The convention for arguments and results can be the same as CoreFoundation
functions imported from C. The code in ``CFunctionConventions`` in
SILFunctionType.cpp looks relevant.
diff --git a/docs/proposals/CompressedMangledNames.md b/docs/proposals/CompressedMangledNames.md
new file mode 100644
index 0000000000000..bc581474f99f2
--- /dev/null
+++ b/docs/proposals/CompressedMangledNames.md
@@ -0,0 +1,238 @@
+
+Motivation
+----------
+
+We care deeply about the size of binaries that are generated by the Swift
+compiler and make an effort to optimize and shrink the generated binaries. One
+of the problems that we have today is that swift symbols are mangled into
+extremely long strings. This is especially a problem for libraries, and almost
+half of the size of libswiftCore.dylib (the swift runtime library on x86_64 OSX)
+is string tables. On MacOSX you can use the command ’size -m file.dylib’ to read
+the size of the string table. C++ also suffers from the problem of long names,
+but since we control the Swift ABI we can do better than C++.
+
+Here are two names from the Swift libraries:
+
+ __TIF14StdlibUnittest13checkSequenceu0_Rxs14CollectionType_s12SequenceTypeWx9Generator7Element_zW_9GeneratorS3__rFTxq_KT_SS9showFrameSb10stackTraceVS_14SourceLocStack4fileSS4lineSu16resiliencyChecksVS_32CollectionMisuseResiliencyChecks9sameValueFTWxS2_S3__WxS2_S3___Sb_T_A6_
+
+ __TTSg5VSS13CharacterViewS_s14CollectionTypes_GVs17IndexingGeneratorS__GS1_S__s13GeneratorTypes_VS_5IndexS3_s16ForwardIndexTypes_SiSis18_SignedIntegerTypes_SiSis33_BuiltinIntegerLiteralConvertibles_Vs20_DisabledRangeIndex__S_S_s9IndexablesS_s12SequenceTypes_GS1_S__GS1_S__S2_s_Vs9Character_S3_S3_S4_s_SiSiS5_s_SiSiS6_s_S7__S__S10__S10____TFFSS12replaceRangeuRxs14CollectionTypeWx9Generator7Element_zVs9CharacterrFTGVs5RangeVVSS13CharacterView5Index_4withx_T_U_FRS4_T_
+
+Swift is a systems programming language, and we need to prepare to a future
+where the whole operating system is developed in Swift. This means that one day
+our phones will have hundreds of shared libraries (written in swift) loaded at
+the same time. Thousands of shared libraries will be saved on disk, and updated
+every time you upgrade the OS and apps. The string table (linkedit section in
+Mach-O) is loaded into memory (as shared copy-on-write). In a world where every
+single process uses multiple swift libraries reducing the size of this section
+is very beneficial for memory usage, load time, disk usage, etc..
+
+On-disk and over-the-air compression can improve things, but these techniques
+are insufficient because generic compression is not as effective as domain
+specific compression, and they do not address the problem of in-memory tables.
+
+
+Character Set
+-------------
+The decision on a character set to be used by the compression scheme is
+independent of the algorithms that are used for compression. The more characters
+that we can use the more efficient the encoding would be. The Base64 encoding
+scheme uses 64 characters and has a 75% efficiency compared to unrestricted
+8-bit ascii. Base64 uses 6 bits to encode 8 bits of ascii.
+
+The current implementation uses the character set A-Z, a-z, 0-9 and "_", which
+are the legal identifier characters in C. We need to use only printable
+characters if we want tools such as nm to be able to work well. It is possible
+to extend the character set to more printable characters but this will make SIL
+(that uses these names freely) less usable. For example, names should probable
+not contain the character , but is probably okay.
+
+Symbol Compression
+------------------
+
+This section describes the Swift symbol compression. In Swift we compress each
+symbol individually as part of the mangling phase. The compression phase has two
+steps:
+
+1. Dictionary based compression (similar to Lempel-Ziv)
+2. Variable length compression (Huffman Coding)
+
+The swift Mangler and Demangler are responsible for compressing and
+decompressing the symbols, and this process is transparent to the debugger. The
+nm command line tool prints the compressed name, and swift-demangle is
+responsible for decompressing and demangling the name properly.
+
+Together, the Dictionary based compression and the Variable length compression
+are able to compress the size of the string section down to 50% (half of the
+original size).
+
+Dictionary-based compression
+----------------------------
+
+This section describes the dictionary based compression. This compression phase
+reduces the string table section by about 40%. Unlike Lempel-Ziv, the
+dictionary-based compression algorithm that we use here can't make use of string
+repetitions to compress the string because the input strings are too short. The
+obvious alternative is to use "prior knowledge". We know what are the common
+sub-strings that are used in Swift names. Some of the most common substrings in
+Swift mangled names are:
+
+ "S_S_S_S", "ollectio", "Type", "Index", "erator", "7Element", and "able".
+
+We can use this prior knowledge to compress our mangling!
+
+In our compression scheme we compress this string:
+
+__TTSg5VSS13CharacterView
+
+Into a string that contains references to some global table that is available to the compressor and decompressor.
+
+__TTSg513View
+
+Commonly used strings are encoded as references to global tables. The reference
+needs to be encoded as part of the name. We need to have some escape character
+and use that character to encode the reference. In our encoding scheme we have two
+escape characters.
+
+The first escape character records an index using a single character. This allows us to encode
+the top 63 frequent substrings in our dictionary using two characters (escape + index).
+
+The second escape character encodes a two-character reference that can access 63 x 63 entries in the table.
+Less common substrings can be encoded using this three character sequence (escape + index0 + index1).
+
+One interesting bit of information is that the character ‘Y’ is only used 4
+times in the entire standard library! The letter J, and a few other letters are
+also not used very frequently. We use Y and J as escape characters.
+
+The dictionary-based encoding uses the following rules:
+
+1. We use two escape characters that are not frequently used in names (Y and Z).
+These characters are escape character and cannot be used as part of the text
+without escaping. ‘Y’ is encoded as ‘YY’, and ‘Z’ would be encoded as ‘YZ’.
+
+2. The most commonly used sub-strings (calculated as length of substring times
+number of occurrences) is encoded with a single escape character and a
+single index character. The table of highly repetitive substrings can only
+contain 61 entries (a-zA-Z0-9_, minus two escape characters).
+
+A reference to the very frequent substrings is encoded as "Yx", where x is the
+character that is translated into a numeric index. This is two chars per
+substring.
+
+3. The less frequently used substrings are encoded as three-character sequence.
+"Zxx", where xx is the numeric index in the large table (that can hold 61*61
+substrings).
+
+It is obvious how to reverse this compression using the same string table used
+to compress the names.
+
+With this encoding scheme the name
+"__TwxxV14StdlibUnittest24MinimalForwardCollection" becomes
+"__TwxxJ1QYrt24J6wJ5KY9on" and the name "__TMPVs15ContiguousArray" becomes
+"__TMPJOSJ6lJ8G".
+
+Notice that the "_T" prefix is kept and should not be compressed because it
+differentiates between swift symbols and non-swift symbols.
+
+These are two related works on dictionary-based compression:
+
+"Text compression using a 4 bit coding scheme" by J Pike.
+"A universal algorithm for sequential data compression (1977)" by Jacob Ziv , Abraham Lempel
+
+Variable Length encoding
+------------------------
+
+The variable length encoding that we use is pretty standard. We use Huffman
+encoding to encode frequently used characters with few bits. One interesting
+aspect of the problem is that we use a character set that is not a power of two.
+To encode a bit stream in a character set that is now a power of two we need to
+represent the whole name as a big number and perform the operation of div-modulo
+for each character we encode, where the div-modulo value is the number of
+characters we use to encode the string.
+
+Strings are encoded into numbers in reverse (end to start) to make the
+decompression faster by allowing strings to be appended and not prepended.
+
+Implementation
+--------------
+
+This section describes the implementation of the symbol compression. Both the
+dictionary-based compression and the variable length compression are implemented
+in a similar way. An external program is used to scan lots of data that
+represents the kind of strings that are likely to be common, and generate header
+files that contain information that is used by the compression routines.
+
+The dictionary-based compression generates an H file that contains information
+about the escape characters used, the list of words in the codebook (this is the
+list of substrings), a list of lengths for each substrings (to accelerate length
+calculations).
+
+Our codebook contains about 3000 entries. In order to compress a word we need to
+search the whole codebook, for every character in the string. This is slow
+inefficient. Instead, the external program is generating a C program that
+implements a search in a Trie-like data structure. The auto-generate search
+routine exposes an API that returns the index of the matched word given a string
+(the original uncompressed symbol) and length until the end of the string.
+
+The Huffman coding uses a similar technique. An external program auto-generates
+routines that encode a sequence of strings into a number, or extract a number from
+a sequence of strings.
+
+The external programs CBCGen.py and HuffGen.py generate the header files
+HuffTables.h and CBC.h.
+
+Generating the compiler header files
+------------------------------------
+
+This section describes how to generate the compression tables using a training
+set and create the header files (that are currently checked in as part of the
+compiler). We generate the compression codebook and the Huffman tables using
+data that we think represent the kind of symbol names people use in Swift. It is
+important to select training data that is representitive or else the compression
+will be less effective.
+
+Step1: Generate a list of mangled names from swift dylibs. This is done using
+the "nm" command: "nm libSwiftCode.dylib > names.txt". Next, remove the prefix
+that nm is adding (stuff like "U", "T" and "t" and addresses of symbols in the
+dylib) and keep one name per line.
+
+Once we enable compression in our manglers you will need to decompress these
+names using the utility swift-compress:
+"cat compressed_names.txt | swift-compress -decompress > names.txt"
+
+Step2: Run "CBCGen.py file1.txt file2.txt file3.txt > CBC.h"
+This will create the CBC header file.
+
+Step3: Recompile swift-compress and use it to compress names without applying
+huffman encoding: "cat names.txt | swift-compress -cbc-only > names.txt.cbc"
+This will create a file with names that are only compressed with the CBC
+encoder, which is the input of our huffman encoder.
+
+Step4: Run HuffGen on the cbc-compressed file to generate the huffman encoding
+tables: "./HuffGen.py names.txt.cbc > HuffTables.h"
+
+Error handling
+--------------
+
+The compression routines only handle characters that are in the list of valid
+characters. It is possible to compress every string that uses the valid
+character set. However, now all incoming strings are legal. For example the
+string "Y" is illegal because 'Y' is an escape character and the decoded expects
+another character to follow the escape character.
+
+There are a few users that will use the compression routines: The
+mangler/demangler/remangler (in the compiler and debugger), the migration tool,
+the unittests, etc. The current error handling strategy is to have asserts in
+the compiler (in release builds). In addition to asserts the compiler handles
+the decoding of malformed strings by returning an empty string. This is not
+ideal and the compression routines should return a boolean flag that says if the
+decompression succeeded.
+
+Migration plan
+--------------
+
+Once we finalize the encoding scheme we need to update many places in the compiler. This includes testcases
+and places in the compiler where we've hard coded names of functions.
+The swift-compress utility can be used to compress and decompress mangled names that appear in text..
+Just like swift-demangle this utility can replace strings and preserve the text around the mangled name.
+This tool can help us in upgrading test files.
+
diff --git a/docs/proposals/Concurrency.rst b/docs/proposals/Concurrency.rst
index f74ca909f2664..0030d23a66d15 100644
--- a/docs/proposals/Concurrency.rst
+++ b/docs/proposals/Concurrency.rst
@@ -202,7 +202,7 @@ variables and unsafe code. Objective-C methods are automatically marked as
that do not explicitly mark the APIs as reentrant or non-reentrant.
In the example program below the method `fly` may access the global variable
-because it is marked with the attribute `unsafe`. The compile won't allow this
+because it is marked with the attribute `unsafe`. The compiler won't allow this
method to be executed from a worker-thread.
.. code-block:: swift
@@ -629,7 +629,7 @@ use actors can scale to support millions of concurrent actors because actors are
not backed by a live thread or by a stack.
In Swift actors could be implemented using classes that inherit from the generic
-``Actor`` class. The generic parameter determins the type of messages that the
+``Actor`` class. The generic parameter determines the type of messages that the
actor can accept. The message type needs to be of ``CopyableType`` to ensure the
safety of the model. The actor class exposes two methods: ``send`` and
``accept``. Messages are sent to actors using the ``send`` method and they never
diff --git a/docs/proposals/DeclarationTypeChecker.rst b/docs/proposals/DeclarationTypeChecker.rst
index bf49ac51d1c74..1872da6f5fd25 100644
--- a/docs/proposals/DeclarationTypeChecker.rst
+++ b/docs/proposals/DeclarationTypeChecker.rst
@@ -68,7 +68,7 @@ There are a few aspects of the language that make it challenging to implement th
extension C { }
extension B { struct Inner { } }
-Here, the name lookup used for the first extension needs to resolve the typealias, which depends on the second extension having already been bound. There is a similar dependency on resolving superclasses beforing binding extensions::
+Here, the name lookup used for the first extension needs to resolve the typealias, which depends on the second extension having already been bound. There is a similar dependency on resolving superclasses before binding extensions::
class X { struct Inner { } }
class Y : X { }
@@ -154,7 +154,7 @@ The proposed architecture is significantly different from the current type check
**Make name lookup phase-aware**: Name lookup is currently one of the worst offenders when violating phase ordering. Parameterize name lookup based on the phase at which it's operating. For example, asking for name lookup at the "extension binding" phase might not resolve type aliases, look into superclasses, or look into protocols.
-**Make type resolution phase-aware**: Type resolution effectively brings a given ``TypeRepr`` up to the "declaration type validation`` phase in one shot. Parameterize type resolution based on the target phase, and start minimizing the among of work that the type checking does. Use extension binding as a testbed for these more-minimal dependencies.
+**Make type resolution phase-aware**: Type resolution effectively brings a given ``TypeRepr`` up to the "declaration type validation`` phase in one shot. Parameterize type resolution based on the target phase, and start minimizing the amount of work that the type checking does. Use extension binding as a testbed for these more-minimal dependencies.
**Dependency graph and priority queue**: Extend the current-phase trait with an operation that enumerates the dependencies that need to be satisfied to bring a given AST node up to a particular phase. Start with ``TypeRepr`` nodes, and use the dependency graph and priority queue to satisfy all dependencies ahead of time, eliminating direct recursion from the type-resolution code path. Build circular-dependency detection within this test-bed.
@@ -165,7 +165,7 @@ The proposed architecture is significantly different from the current type check
How do we test it?
~~~~~~~~~~~~~~~~~~
-**Existing code continues to work**: As we move various parts of the type checker over to the dependency graph, existing Swift code should continue to work, since we'll have fallbacks to the existing logic and the new type checker should be strictly more lazy than the existing type checker.
+**Existing code continues to work**: As we move various parts of the type checker over to the dependency graph, existing Swift code should continue to work, since we'll have fallbacks to the existing logic and the new type checker should be strictly lazier than the existing type checker.
**Order-independence testing**: One of the intended improvements from this type checker architecture is that we should get more predictable order-independent behavior. To check this, we can randomly scramble the order in which we type-check declarations in the primary source file of a well-formed module and verify that we get the same results.
@@ -176,8 +176,8 @@ How do we measure progress?
The proposed change is a major architectural shift, and it's only complete when we have eliminated all ad hoc recursion from the front end. There are a few ways in which we can measure progress along the way:
-**AST nodes that implement the phase-aware trait**: Eventually, all of our AST nodes will implement the phase-aware trait. The number of AST nodes that do properly implement that trait (reporting current phase, enumerating dependencies for a phase transition) and become part of the dependency graph and priorty queue gives an indication of how far we've gotten.
+**AST nodes that implement the phase-aware trait**: Eventually, all of our AST nodes will implement the phase-aware trait. The number of AST nodes that do properly implement that trait (reporting current phase, enumerating dependencies for a phase transition) and become part of the dependency graph and priority queue gives an indication of how far we've gotten.
**Accessors that check the current phase**: When we're finished, each of the AST's accessors should assert that the AST node is in the appropriate phase. The number of such assertions that have been enabled is an indication of how well the type checker is respecting the dependencies.
-**Phases of AST nodes in non-primary files**: With the current type checker, every AST node in a non-primary file that gets touched when type-checking the primary file will end up being fully validated (currently, the "attribute checking" phase). As the type checker gets more lazy, the AST nodes in non-primary files will trend toward earlier phases. Tracking the number of nodes in non-primary files at each phase over time will help us establish how lazy the type checker is becoming.
+**Phases of AST nodes in non-primary files**: With the current type checker, every AST node in a non-primary file that gets touched when type-checking the primary file will end up being fully validated (currently, the "attribute checking" phase). As the type checker gets lazier, the AST nodes in non-primary files will trend toward earlier phases. Tracking the number of nodes in non-primary files at each phase over time will help us establish how lazy the type checker is becoming.
diff --git a/docs/proposals/Enums.rst b/docs/proposals/Enums.rst
index 46402160b1a1f..607596bd4d9b6 100644
--- a/docs/proposals/Enums.rst
+++ b/docs/proposals/Enums.rst
@@ -281,7 +281,7 @@ circumstances:
StringLiteralConvertible.
- None of the cases of the enum may have non-void payloads.
-If an enum declares an raw type, then its cases may declare raw
+If an enum declares a raw type, then its cases may declare raw
values. raw values must be integer, float, character, or string
literals, and must be unique within the enum. If the raw type is
IntegerLiteralConvertible, then the raw values default to
diff --git a/docs/proposals/Error Handling.rst b/docs/proposals/Error Handling.rst
deleted file mode 100644
index 697b9d3b406aa..0000000000000
--- a/docs/proposals/Error Handling.rst
+++ /dev/null
@@ -1,171 +0,0 @@
-:orphan:
-
-.. @raise litre.TestsAreMissing
-.. ErrorHandlingModel:
-
-Swift Error Handling Model
-==========================
-
-The goal of this writeup is to capture ideas around error handling in APIs and
-the tradeoffs involved that influenced this design.
-
-Error Handling In Contemporary Languages
-----------------------------------------
-
-C and POSIX proffer a mix of "errno" based APIs and APIs that return an error
-code explicitly as a result. While this approach _works_, it has a number of
-problems: 1) it is too easy to accidentally ignore an error, 2) using a thread
-local integer variable for error handling is non-extensible, and 3) using the
-return value as an error code in C forces the logical result of the function to
-be returned by reference through an argument pointer.
-
-In contrast, the "obvious" approach to error handling is exception handling as
-known from C++, Java, C#, and many other languages. Exception handling allows
-decoupling the logic that produces an error, the (implicitly generated)
-logic that propagates the error, and the logic that ultimately handles the error
-code. The implementation model allows a choice of either "zero cost" exceptions
-which have a slow error case, or an implicitly generated propagation which slows
-down the normal case a bit to make error propagation faster. That said, there
-are a lot of ways to do exception handling wrong.
-
-Exception Specifications
-````````````````````````
-
-Exception specifications are difficult to get right. Adding an concrete
-exception specification (i.e., "I only throw T") to a function is a very strong
-guarantee that is often difficult to maintain as APIs evolve. For this reason,
-Java has two sorts of exceptions: normal ones that obey exception specifications
-and "runtime" exceptions that are exempt from them. In practice, this loop-hole
-makes exception specifications in Java completely useless for reasoning about
-the exception behavior of a program, which is one of the reasons that C#
-eliminated them completely.
-
-C++'98 has other unfortunate issues with its exception specifications, including
-that all functions are assumed to implicitly throw if they have no exception
-spec. Also, its design for empty exception specification (e.g.
-"void foo() throw()") is also problematic, and was improved by adding "noexcept"
-in C++'11.
-
-Objective-C is interesting because its exception specifications (i.e. the
-presence of an NSError** argument) is binary: a function can return an
-error or not, but it isn't encouraged to document *how* APIs can fail in
-detailed ways.
-
-Runtime Failures
-````````````````
-
-Both Objective-C and Java recognize a difference between general application
-errors and "runtime" errors (such as out-of-bound NSArray accesses, or a null
-pointer dereference in Java). As mentioned above, Java allows runtime errors
-to avoid exception specifications, but otherwise treats them the same as other
-exceptions.
-
-Objective-C handles runtime errors by throwing an Objective-C exception, which
-is a somewhat hard failure because very little Objective-C code is exception
-safe. This leads to memory leaks or have other adverse effects, which is not
-regarded as recoverable behavior.
-
-A unfortunate aspect of allowing runtime exceptions to be "caught" is that it
-means that removing "guard rails" in the language (e.g. turning off array bounds
-checks or null pointer dereference checks) can turn a working application (one
-that detects, catches, and handles the error) into a broken application (one
-that scribbles on garbage memory).
-
-
-Other Problems with Exception Handling
-``````````````````````````````````````
-
-C++'s exception handling model causes many systems applications (e.g., LLVM,
-Webkit, and many others) to disable exception handling with -fno-exception. One
-issue is that C++ exception handling violates its own "pay for what you use"
-model of C++ by bloating your code with exception tables and RTTI data,
-even if you don't actually throw any exceptions. The fact that C++ has a poor
-model to reason about what calls actually throw also leads to pessimization in
-the optimizer as it has to assume the worst case about exception edges, leading
-to lower performance (even with "zero cost" exceptions) and code bloat compared
-to building with -fno-exceptions.
-
-C++ also requires a very specific design style (emphasizing RAII) to make an
-application exception safe because it lacks automatic memory management.
-
-Another common reason that C++ code disables exceptions is that they want a more
-"disciplined" or "strict" mode for writing their code. Many people
-(particularly at the lower levels of "systems programming" stack) want to know
-about and reason about the error handling and propagation behavior of every
-error state that can happen, and do not want the implicit propagation aspect of
-exceptions.
-
-Finally, because a lot of disables exceptions, many libraries actively avoid
-designing them into their APIs. The STL in particular has very few APIs that
-throw exceptions on error cases, and those APIs have non-throwing counterparts.
-
-Error Handling Goals
---------------------
-
-The design of an error handling system has conflicting goals based on the
-audience: some programmers don't want to think about error handling logic at
-all - yielding a more "scripting language" sort of experience, while some people
-want to control every error case and be forced to think about error handling in
-depth - yielding a more "disciplined" experience. Neither of these is "wrong"
-or better than the other, they serve different needs and Swift should support
-both use cases.
-
-While level of strictness is negotiable and Swift should support multiple
-approaches, the error handling behavior of stable *API* is something that must
-be considered as strongly as the arguments and return value of the function. We
-consider it a breaking change (and therefore, unacceptable) for API that was
-previously guaranteed to never return an error to start returning error codes.
-
-It's worth noting that Objective-C achieves these goals
-with NSError. NSError "results" are explicitly part of the signature of a
-method, and one cannot be added or removed without changing the selector (a
-breaking change). Clients who don't care about error handling can (and often
-do) completely ignore the NSError result of a method call.
-
-
-Swift Error Handling Model
---------------------------
-
-Swift categorizes error conditions into two classifications: exceptions and
-unrecoverable runtime errors. Either condition can be raised by arbitrary code,
-but the two are implemented in different ways and have different ramifications
-for propagation and handling of the condition.
-
-Swift Runtime Errors
-````````````````````
-
-Runtime errors are conditions like deferencing a null pointer, accessing an
-array out of bounds, and explicitly declared exceptions (e.g. out of memory
-conditions, at least in some cases). Because they can occur anywhere, they are
-not explicitly declared as part of API - any function is assumed to be capable
-of raising a runtime error.
-
-are considered to be "uncatchable" failures that terminate the
-current thread/actor, and are
-
-
-Runtime errors can occur anywhere in the application
-
-array out of bounds
-assertion failure, pre/post conditions failures, typestate violation.
-cast(V)
-
-
-
-
-
-
-
-
-Swift Exceptions
-````````````````
-
-
-TODO
-
-
-strict mode, vs sloppy mode.
-
-API means something is strict.
-
-
diff --git a/docs/proposals/InitializerInheritance.rst b/docs/proposals/InitializerInheritance.rst
index 6fbb8118deb13..4ae92827cf327 100644
--- a/docs/proposals/InitializerInheritance.rst
+++ b/docs/proposals/InitializerInheritance.rst
@@ -283,7 +283,7 @@ attribute, are guaranteed to be available in every subclass of
}
func f(meta: D.Type) {
- meta() // okay: every sublass of D guaranteed to have an init()
+ meta() // okay: every subclass of D guaranteed to have an init()
}
Note that ``@virtual`` places a requirement on all subclasses to
@@ -378,7 +378,7 @@ a trivial ``NSDocument``::
In Swift, there would be no way to create an object of type
``MyDocument``. However, the frameworks will allocate an instance of
-``MyDocument`` and then send an message such as
+``MyDocument`` and then send a message such as
``initWithContentsOfURL:ofType:error:`` to the object. This will find
``-[NSDocument initWithContentsOfURL:ofType:error:]``, which delegates
to ``-[NSDocument init]``, leaving ``MyDocument``'s stored properties
diff --git a/docs/proposals/InoutCOWOptimization.rst b/docs/proposals/InoutCOWOptimization.rst
index 4f0543fcbf2ed..c784fda253786 100644
--- a/docs/proposals/InoutCOWOptimization.rst
+++ b/docs/proposals/InoutCOWOptimization.rst
@@ -7,7 +7,7 @@
:Authors: Dave Abrahams, Joe Groff
:Summary: Our writeback model interacts with Copy-On-Write (COW) to
- cause some surprising ineffiencies, such as O(N) performance
+ cause some surprising inefficiencies, such as O(N) performance
for ``x[0][0] = 1``. We propose a modified COW optimization
that recovers O(1) performance for these cases and supports
the efficient use of slices in algorithm implementation.
@@ -25,8 +25,8 @@ The problem is caused as follows:
x[0].mutate()
- we “``subscript get``” ``x[0]`` into a temporary, mutate the
- temporary, and “``subscript set``” it back into ``x[0]``.
+ we "``subscript get``" ``x[0]`` into a temporary, mutate the
+ temporary, and "``subscript set``" it back into ``x[0]``.
* When the element itself is a COW type, that temporary implies a
retain count of at least 2 on the element's buffer.
@@ -51,7 +51,7 @@ could be written as follows:
protocol Sliceable {
...
@mutating
- func quickSort(compare: (StreamType.Element, StreamType.Element)->Bool) {
+ func quickSort(compare: (StreamType.Element, StreamType.Element) -> Bool) {
let (start,end) = (startIndex, endIndex)
if start != end && start.succ() != end {
let pivot = self[start]
diff --git a/docs/proposals/Inplace.rst b/docs/proposals/Inplace.rst
index 95d31e1623fc4..47cc17089b1ab 100644
--- a/docs/proposals/Inplace.rst
+++ b/docs/proposals/Inplace.rst
@@ -310,7 +310,7 @@ as though it were written:
.. parsed-literal::
{
- (var y: X)->X in
+ (var y: X) -> X in
y\ **.=**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*)
return y
}(x)
@@ -344,7 +344,7 @@ as though it were written:
.. parsed-literal::
{
- (var y: X)->X in
+ (var y: X) -> X in
y *op*\ **=**\ *expression*
return y
}(x)
@@ -424,7 +424,7 @@ fine::
foo.=advanced(10)
The alternative would be to say that explicitly-written assignment methods
-cannot work properly for immutable classes and “work” with reference
+cannot work properly for immutable classes and "work" with reference
semantics on other classes. We consider this approach indefensible,
especially when one considers that operators encourage writing
algorithms that can only work properly with value semantics and will
diff --git a/docs/proposals/ObjC Interoperation.rst b/docs/proposals/ObjC Interoperation.rst
index 90c142680b924..2eb2586c4b591 100644
--- a/docs/proposals/ObjC Interoperation.rst
+++ b/docs/proposals/ObjC Interoperation.rst
@@ -330,7 +330,7 @@ difference between a stored property and its underlying storage,
For another example, code
class might access
-In bot hcaess, t makes sense to organize the code that way,
+In both cases, t makes sense to organize the code that way,
but Objective C punishes the performance of that code in order to
reserve the language's
diff --git a/docs/proposals/OptimizerEffects.rst b/docs/proposals/OptimizerEffects.rst
index ae4ec5ded155f..d5c11835af489 100644
--- a/docs/proposals/OptimizerEffects.rst
+++ b/docs/proposals/OptimizerEffects.rst
@@ -2,8 +2,8 @@
.. OptimizerEffects:
-Optimizer Effects: Summarizing and specifing function side effects
-==================================================================
+Optimizer Effects: Summarizing and specifying function side effects
+===================================================================
.. contents::
@@ -20,10 +20,10 @@ Introduction
This document formalizes the effects that functions have on program
state for the purpose of facilitating compiler optimization. By
modeling more precise function effects, the optimizer can make more
-assumptions leading to more agressive transformation of the program.
+assumptions leading to more aggressive transformation of the program.
Function effects may be deduced by the compiler during program
-analyis. However, in certain situations it is helpful to directly
+analysis. However, in certain situations it is helpful to directly
communicate function effects to the compiler via function attributes
or types. These source level annotations may or may not be statically
enforceable.
@@ -207,7 +207,7 @@ state.
``@get_subobject``
- A method marked ``@get_subobject`` must fullfill all of ``@preserve_unique``'s
+ A method marked ``@get_subobject`` must fulfill all of ``@preserve_unique``'s
guarantees. Furthermore, it must return a 'subobject' that is stored by the
set of storage objects or a value stored in the CoW struct itself. It must be
guaranteed that the 'subobject' returned is kept alive as long the current
@@ -245,7 +245,7 @@ state.
``@get_subobject_non_bridged``
- A method marked ``@get_subobject`` must fullfill all of ``@preserve_unique``'s
+ A method marked ``@get_subobject`` must fulfill all of ``@preserve_unique``'s
guarantees. Furthermore, it must return a 'subobject' that is stored by the
set of storage objects or a value stored in the CoW struct itself. It must be
guaranteed that the 'subobject' returned is kept alive as long the current
@@ -280,7 +280,7 @@ state.
``@get_subobject_addr``
- A method marked ``@get_subobject_addr`` must fullfill all of
+ A method marked ``@get_subobject_addr`` must fulfill all of
``@preserve_unique``'s guarantees. Furthermore, it must return the address of
a 'subobject' that is stored by the set of storage objects. It is guaranteed
that the 'subobject' at the address returned is kept alive as long the current
@@ -304,7 +304,7 @@ state.
``@initialize_subobject``
- A method marked ``@initialize_subobject`` must fullfill all of
+ A method marked ``@initialize_subobject`` must fulfill all of
``@preserve_unique``'s guarantees. The method must only store its arguments
into *uninitialized* storage. The only effect to non-self state is the capture
of the method's arguments.::
@@ -332,7 +332,7 @@ state.
``@set_subobject``
- A method marked ``@set_subobject`` must fullfill all of
+ A method marked ``@set_subobject`` must fulfill all of
``@preserve_unique``'s guarantees. The method must only store its arguments
into *initialized* storage. The only effect to non-self state is the capture
of the method's arguments and the release of objects of the method arguments'
@@ -427,7 +427,7 @@ the object named by 'A' and therefore cannot modify it.
Why do we need ``@get_subobject``, ``@initialize_subobject``, and
``@set_subobject``?
-We want to be able to hoist ``makeunique`` calls when the array is not identfied
+We want to be able to hoist ``makeunique`` calls when the array is not identified
by a unique name.::
class AClass {
@@ -452,7 +452,7 @@ Further we would like to reason that:::
a.array.append
-cannot change the uniqueness state of the instance of array 'a.array' accross
+cannot change the uniqueness state of the instance of array 'a.array' across
iterations. We can conclude so because ``appendAssumingUnique``'s side-effects
guarantee that no destructor can run - it's only side-effect is that ``tmp``
is captured and initializes storage in the array - these are the only
@@ -535,7 +535,7 @@ User-Specified Effects, Syntax and Defaults
Mostly TBD.
The optimizer can only take advantage of user-specified effects before
-they have been inlined. Consequently, the optimizer initialy preserves
+they have been inlined. Consequently, the optimizer initially preserves
calls to annotated @effects() functions. After optimizing for effects
these functions can be inlined, dropping the effects information.
@@ -562,7 +562,7 @@ generic arguments::
func setElt(elt: T) { t = elt }
}
-With no knowledge of T.deinit() we must assume worst case. SIL effects
+With no knowledge of T.deinit() we must assume the worst case. SIL effects
analysis following specialization can easily handle such a trivial
example. But there are two situations to be concerned about:
@@ -617,7 +617,7 @@ optimizing the surrounding code.
For example::
func bar(t: T) {...}
-
+
func foo(t: T, N: Int) {
for _ in 1...N {
bar(t)
@@ -644,12 +644,12 @@ defined types composed from Arrays, Sets, and Strings.
Conceptually, a pure value does not share state with another
value. Any trivial struct is automatically pure. Other structs can be
declared pure by the author. It then becomes the author's
-resonsibility to guarantee value semantics. For instance, any stored
+responsibility to guarantee value semantics. For instance, any stored
reference into the heap must either be to immutable data or protected
by CoW.
Since a pure value type can in practice share implementation state, we
-need an enforcable definition of such types. More formally:
+need an enforceable definition of such types. More formally:
- Copying or destroying a pure value cannot affect other program
state.
@@ -738,7 +738,7 @@ effects. This is the crux of the difficulty in defining the CoW
effects. Consequently, communicating purity to the compiler will
require some function annotations and/or type constraints.
-A CoW type consits of a top-level value type, most likely a struct, and a
+A CoW type consists of a top-level value type, most likely a struct, and a
referenced storage, which may be shared between multiple instances of the CoW
type.
@@ -795,7 +795,7 @@ Store (1) and load (2) do not alias and (3) is defined as ``readnone``. So (1)
could be moved over (3).
Currently inlining is prevented in high-level SIL for all functions which
-have an semantics or effect attribute. Therefore we could say that the
+have a semantics or effect attribute. Therefore we could say that the
implementor of a pure value type has to define effects on all member functions
which eventually can access or modify the storage.
@@ -842,7 +842,7 @@ Inferring Function Purity
The optimizer can infer function purity by knowing that (1) the
function does not access unspecified state, (2) all arguments are pure
-values, and (3) no calls are made into nonpure code.
+values, and (3) no calls are made into non-pure code.
(1) The effects system described above already tells the optimizer via
analysis or annotation that the function does not access
@@ -853,7 +853,7 @@ values, and (3) no calls are made into nonpure code.
type definition, or it may rely on a type constraint.
(3) Naturally, any calls within the function body must be transitively
- pure. There is no need to check a calls to the storage
+ pure. There is no need to check calls to the storage
deinitializer, which should already be guaranteed pure by virtue
of (2).
@@ -919,5 +919,5 @@ Generally, a default-safe policy provides a much better user model
from some effects. For example, we could decide that functions cannot
affect unspecified state by default. If the user accesses globals,
they then need to annotate their function. However, default safety
-dictates that any neccessary annotations should be introduced before
+dictates that any necessary annotations should be introduced before
declaring API stability.
diff --git a/docs/proposals/ValueSemantics.rst b/docs/proposals/ValueSemantics.rst
index 3541d407e0a09..5d03c19518d0b 100644
--- a/docs/proposals/ValueSemantics.rst
+++ b/docs/proposals/ValueSemantics.rst
@@ -25,7 +25,7 @@ Value Semantics
---------------
For a type with value semantics, variable initialization, assignment,
-and argument-passing (hereafter, “the big three operations”) each
+and argument-passing (hereafter, "the big three operations") each
create an *independently modifiable copy* of the source value that is
*interchangeable with the source*. [#interchange]_
@@ -151,13 +151,13 @@ The Problem With Generics
The classic Liskov principle says the semantics of operations on
``Duck``\ 's subtypes need to be consistent with those on ``Duck`` itself,
-so that functions operating on ``Duck``\ s still “work” when passed a
+so that functions operating on ``Duck``\ s still "work" when passed a
``Mallard``. More generally, for a function to make meaningful
guarantees, the semantics of its sub-operations need to be consistent
regardless of the actual argument types passed.
The type of an argument passed by-value to an ordinary function is
-fully constrained, so the “big three” have knowable semantics. The
+fully constrained, so the "big three" have knowable semantics. The
type of an ordinary argument passed by-reference is constrained by
subtype polymorphism, where a (usually implicit) contract between
base- and sub-types can dictate consistency.
@@ -179,7 +179,7 @@ Here’s a version of cycle_length that works when state is a mutable
value type::
func cycle_length(
- s : State, mutate : ( [inout] State )->()
+ s : State, mutate : ( [inout] State ) -> ()
) -> Int
requires State : EqualityComparable
{
@@ -196,7 +196,7 @@ value type::
The reason the above breaks when the state is in a class instance is
that the intended copy in line 1 instead creates a new reference to
the same state, and the comparison in line 2 (regardless of whether we
-decide ``!=`` does “identity” or “value” comparison) always succeeds.
+decide ``!=`` does "identity" or "value" comparison) always succeeds.
You can write a different implementation that only works on clonable
classes:
@@ -211,7 +211,7 @@ classes:
}
func cycle_length(
- s : State, mutate : ( [inout] State )->()
+ s : State, mutate : ( [inout] State ) -> ()
) -> Int
requires State : EqualityComparable, **Clonable**
{
@@ -233,8 +233,8 @@ clonable classes:
func cycle_length(
s : State,
- **next : (x : State)->State,**
- **equal : ([inout] x : State, [inout] y : State)->Bool**
+ **next : (x : State) -> State,**
+ **equal : ([inout] x : State, [inout] y : State) -> Bool**
) -> Int
requires State : EqualityComparable
{
diff --git a/docs/proposals/WholeModuleOptimization.rst b/docs/proposals/WholeModuleOptimization.rst
index f391272a216c6..9f67bbf9ee89e 100644
--- a/docs/proposals/WholeModuleOptimization.rst
+++ b/docs/proposals/WholeModuleOptimization.rst
@@ -23,7 +23,7 @@ compilation that results from having the entire module available makes
it possible for the inliner to inline functions that it would
otherwise not be able to inline in normal separate compilation. Other
optimizations similarly benefit, for example generic specialization
-(since it has more opportunities for specializae) and function
+(since it has more opportunities for specialize) and function
signature optimization (since it has more call sites to rewrite).
diff --git a/docs/proposals/archive/Memory and Concurrency Model.rst b/docs/proposals/archive/Memory and Concurrency Model.rst
index 82dc4bd50d986..62568f908af22 100644
--- a/docs/proposals/archive/Memory and Concurrency Model.rst
+++ b/docs/proposals/archive/Memory and Concurrency Model.rst
@@ -48,7 +48,7 @@ Swift. Given a static type, it is obvious what kind it is from its
definition. These kinds are:
1. **Immutable Data** - Immutable data (which can have a constructor, but whose
- value cannot be changed after it completes) is sharable across actors, and it
+ value cannot be changed after it completes) is shareable across actors, and it
would make sense to unique them where possible. Immutable data can
(transitively) point to other immutable data, but it isn't valid (and the
compiler rejects) immutable data that is pointing to mutable data. For
diff --git a/docs/proposals/archive/ProgramStructureAndCompilationModel.rst b/docs/proposals/archive/ProgramStructureAndCompilationModel.rst
index 1f67481707cc1..cea89ce740524 100644
--- a/docs/proposals/archive/ProgramStructureAndCompilationModel.rst
+++ b/docs/proposals/archive/ProgramStructureAndCompilationModel.rst
@@ -35,7 +35,7 @@ to the business and management reality of the world:
**Ownership Domain / Top Level Component**: corresponds to a product that is
shipped as a unit (Mac OS/X, iWork, Xcode), is a collection of frameworks/dylibs
-and resources. Only acyclic dependences between different domains is
+and resources. Only acyclic dependencies between different domains is
allowed. There is some correlation in concept here to "umbrella headers" or
"dyld shared cache" though it isn't exact.
@@ -47,7 +47,7 @@ dylib + optional resources. All contributing source files and resources live in
one directory (with optional subdirs), and have a single "project file". Can
contribute to multiple namespaces. The division of a domain into components is
an implementation detail, not something externally visible as API. Can have
-cyclic dependences between other components. Components roughly correspond to
+cyclic dependencies between other components. Components roughly correspond to
"xcode project" or "B&I project" granularity at Apple. Can rebuild a "debug
version" of a subcomponent and drop it into an app without rebuilding the entire
world.
@@ -104,7 +104,7 @@ Components are explicitly declared, and these declarations can include:
* the version of the component (which are used for "availability macros" etc)
-* an explicit list of dependences on other top-level components (whose
+* an explicit list of dependencies on other top-level components (whose
dependence graph is required to be acyclic) optionally with specific versions:
"I depend on swift standard libs 1.4 or later"
@@ -283,7 +283,7 @@ Now the compiler parses each swift file into an AST. We'll keep the swift
grammar carefully factored to keep types and values distinct, so it is possible
to parse (but not fully typecheck) the files without first reading "all the
headers they depend on". This is important because we want to allow arbitrary
-type and value cyclic dependences between files in a component. As each file is
+type and value cyclic dependencies between files in a component. As each file is
parsed, the compiler resolves as many intra-file references as it can, and ends
up with a list of (namespace qualified) types and values that are imported by
the file that are not satisfied by other components. This is the list of things
@@ -311,7 +311,7 @@ carefully layered to be memory efficient (e.g. only processing an SCC at a time
instead of an entire component) as well as highly parallel for multicore
machines. For incremental builds, we will have a huge win because the
fine-grained dependence information between .o files is tracked and we know
-exactly what dependences to rebuild if anything changes. The build cache will
+exactly what dependencies to rebuild if anything changes. The build cache will
accelerate most of this, which will eventually be a hybrid on-disk/in-memory
data structure.
@@ -330,7 +330,7 @@ client builds against the component to type check the client and ensure that its
references are resolved.
Because we have the version number as well as the full interface to the
-component available in a consumable format is that we can build a SDK generation
+component available in a consumable format is that we can build an SDK generation
tool. This tool would take manifest files for a set of releases (e.g. iOS 4.0,
4.0.1, 4.0.2, 4.1, 4.1.1, 4.2) and build a single SDK manifest which would have
a mapping from symbol+type -> version list that indicates what the versions a
diff --git a/docs/proposals/archive/UnifiedFunctionSyntax.rst b/docs/proposals/archive/UnifiedFunctionSyntax.rst
index 5fa8e9a869bc0..5c15dbe1f4243 100644
--- a/docs/proposals/archive/UnifiedFunctionSyntax.rst
+++ b/docs/proposals/archive/UnifiedFunctionSyntax.rst
@@ -406,7 +406,7 @@ circumstances that affect inclusion or exclusion from the list.
+----------------+---------+---------+----------------------------+
| **From** | Yes | No | |
+----------------+---------+---------+----------------------------+
-| **Given** | Yes* | No | Never splits a slector |
+| **Given** | Yes* | No | Never splits a selector |
+----------------+---------+---------+----------------------------+
| **In** | Yes | No | |
+----------------+---------+---------+----------------------------+
diff --git a/docs/proposals/containers_value_type.html b/docs/proposals/containers_value_type.html
index 6599a83cc84c0..c64d60c53cf5f 100644
--- a/docs/proposals/containers_value_type.html
+++ b/docs/proposals/containers_value_type.html
@@ -231,7 +231,7 @@
those used in Cocoa. Now there is absolutely nothing wrong with high
quality, strictly followed naming conventions. But they aren't checked
by the compiler. Having the compiler be able to confirm: yes, this
-argument can be modified / no, that argument can not be modified; is a
+argument can be modified / no, that argument cannot be modified; is a
tremendous productivity booster.
@@ -347,7 +347,7 @@
archives
is an in-out argument. And just as importantly,
that archivePath
is not to be modified within
_checkPathForArchiveAndAddToArray
. However if
-archivePath
is a mutable object with reference semantics, we loose
+archivePath
is a mutable object with reference semantics, we lose
that ability to locally reason about this code, even in Swift.
@@ -482,7 +482,7 @@ Summary
more easily spot the few cases where this is desired.
-- Swift can not provide such protection for types with reference semantics.
+- Swift cannot provide such protection for types with reference semantics.
diff --git a/docs/proposals/rejected/Bridging Container Protocols to Class Clusters.rst b/docs/proposals/rejected/Bridging Container Protocols to Class Clusters.rst
index cbef36e587f2d..f80400d1b6fc4 100644
--- a/docs/proposals/rejected/Bridging Container Protocols to Class Clusters.rst
+++ b/docs/proposals/rejected/Bridging Container Protocols to Class Clusters.rst
@@ -24,7 +24,7 @@ Here's what I propose instead:
Although I'll be talking about arrays in this proposal, I think the same
approach would work for ``NSDictionary`` and ``NSSet`` as well, mapping them
-to generic containers for associative map and and unordered container protocols
+to generic containers for associative map and unordered container protocols
respectively.
NSArray vs Array
diff --git a/docs/proposals/rejected/ClassConstruction.rst b/docs/proposals/rejected/ClassConstruction.rst
index 9db9f65ead8a8..5b1ea48747c5d 100644
--- a/docs/proposals/rejected/ClassConstruction.rst
+++ b/docs/proposals/rejected/ClassConstruction.rst
@@ -7,7 +7,7 @@
.. warning:: This proposal was rejected, though it helped in the design of the
final Swift 1 initialization model.
-Objective-C's “designated inititalizers” pattern seems at first to
+Objective-C's "designated initializers pattern seems at first to
create a great deal of complication. However, designated initializers
are simply the only sane response to Objective-C's initialization rules,
which are the root cause of the complication.
@@ -116,9 +116,9 @@ Proposal
========
I suggest we define Swift initialization to be as simple and
-easily-understood as possible, and avoid “interesting” interactions
+easily-understood as possible, and avoid "interesting" interactions
with the more complicated Objective-C initialization process. If we
-do this, we can treat Objective-C base classes as “sealed and safe”
+do this, we can treat Objective-C base classes as "sealed and safe"
for the purpose of initialization, and help programmers reason
effectively about initialization and their class invariants.
@@ -133,7 +133,7 @@ Here are the proposed rules:
Objective-C.
* ``self.init(…)`` calls in Swift never dispatch virtually. We have a
- safe model for “virtual initialization:” ``init`` methods can call
+ safe model for "virtual initialization:" ``init`` methods can call
overridable methods after all instance variables and superclasses
are initialized. Allowing *virtual* constructor delegation would
undermine that safety.
diff --git a/docs/proposals/rejected/Clonable.rst b/docs/proposals/rejected/Clonable.rst
index 949ecf93cb883..39bf2c5d08a41 100644
--- a/docs/proposals/rejected/Clonable.rst
+++ b/docs/proposals/rejected/Clonable.rst
@@ -15,7 +15,7 @@
language-level copying mechanism for classes.
**Abstract:** to better support the creation of value types, we
-propose a “magic” ``Clonable`` protocol and an annotation for describing
+propose a "magic" ``Clonable`` protocol and an annotation for describing
which instance variables should be cloned when a type is copied. This
proposal **augments revision 1** of the Clonable proposal with our
rationale for dropping our support for ``val`` and ``ref``, a
@@ -65,7 +65,7 @@ automatic, if we add that feature) forwarding.
By dropping ``val`` we also lose some terseness aggregating ``class``
contents into ``struct``\ s. However, since ``ref`` is being dropped
-there's less call for a symmetric ``val``. The extra “cruft” that
+there's less call for a symmetric ``val``. The extra "cruft" that
``[clone]`` adds actually seems appropriate when viewed as a special
bridge for ``class`` types, and less like a penalty against value
types.
@@ -125,7 +125,7 @@ variables marked ``[clone]``::
var somethingIJustReferTo : Bar
}
-When a ``Baz`` is copied by any of the “big three” operations (variable
+When a ``Baz`` is copied by any of the "big three" operations (variable
initialization, assignment, or function argument passing), even as
part of a larger ``struct``, its ``[clone]`` member is ``clone()``\ d.
Because ``Foo`` itself has a ``[clone]`` member, that is ``clone()``\ d
diff --git a/docs/proposals/rejected/Constructors.rst b/docs/proposals/rejected/Constructors.rst
index 69fcb9660217f..c88b9b7802571 100644
--- a/docs/proposals/rejected/Constructors.rst
+++ b/docs/proposals/rejected/Constructors.rst
@@ -461,11 +461,11 @@ zero-argument selector with no trailing colon, e.g.,::
maps to the selector ``initToMemory``.
-This mapping is reversible: given a selector in the “init” family,
-i.e., where the first word is “init”, we split the selector into its
+This mapping is reversible: given a selector in the "init" family,
+i.e., where the first word is "init", we split the selector into its
various pieces at the colons:
-* For the first piece, we remove the “init” and then lowercase the
+* For the first piece, we remove the "init" and then lowercase the
next character *unless* the second character is also uppercase. This
becomes the name of the first parameter to the constructor. If this
string is non-empty and the selector is a zero-argument selector
@@ -494,7 +494,7 @@ designated initializers in Objective-C. Clang can then be extended to
perform similar checking to what we're describing for Swift:
designated initializers delegate or chain to the superclass
constructor, secondary constructors always delegate, and subclassing
-rrequires one to override the designated initializers. The impact can
+requires one to override the designated initializers. The impact can
be softened somewhat using warnings or other heuristics, to be
(separately) determined.
@@ -508,7 +508,7 @@ is being substituted for another object.
In both cases, we are left with a partially-constructed object that
then needs to be destroyed, even though its instance variables may not
-yet havee been initialized. This is also a problem for Objective-C,
+yet have been initialized. This is also a problem for Objective-C,
which makes returning anything other than the original ''self''
brittle.
@@ -533,7 +533,7 @@ Alternatives
------------
This proposal is complicated, in part because it's trying to balance
-the safety goals of Swift against the convience of Objective-C's
+the safety goals of Swift against the convenience of Objective-C's
two-phase initialization.
Separate Swift Constructors from Objective-C Initializers
diff --git a/docs/proposals/valref.rst b/docs/proposals/valref.rst
index 6266129ffd804..04f9dfe18fb34 100644
--- a/docs/proposals/valref.rst
+++ b/docs/proposals/valref.rst
@@ -29,15 +29,15 @@ Introduction
Until recently, Swift's support for value semantics outside trivial
types like scalars and immutable strings has been weak. While the
-recent ``Clonable`` proposal makes new things possible in the “safe”
+recent ``Clonable`` proposal makes new things possible in the "safe"
zone, it leaves the language syntactically and semantically lumpy,
keeping interactions between value and reference types firmly outside
-the “easy” zone and failing to address the issue of generic
+the "easy" zone and failing to address the issue of generic
programming.
This proposal builds on the ``Clonable`` proposal to create a more
uniform, flexible, and interoperable type system while solving the
-generic programming problem and expanding the “easy” zone.
+generic programming problem and expanding the "easy" zone.
General Description
===================
@@ -68,8 +68,8 @@ When applied to ``class`` types, "copy" means to call the ``clone()``
method, which is generated by the compiler when the user has
explicitly declared conformance to the ``Clonable`` protocol.
-When we refer to variables being “declared ``val``” or “declared
-``ref``”, we mean to include the case of equivalent declarations using
+When we refer to variables being "declared ``val``" or "declared
+``ref``", we mean to include the case of equivalent declarations using
``var`` that request the default semantics for the type.
Unless otherwise specified, we discuss implementation details such as
@@ -150,7 +150,7 @@ Instance variables can be explicitly declared ``val`` or ``ref``::
When a value is copied, all of its instance variables declared ``val``
(implicitly or explicitly) are copied. Instance variables declared
``ref`` merely have their reference counts incremented (i.e. the
-refrence is copied). Therefore, when the defaults are in play, the
+reference is copied). Therefore, when the defaults are in play, the
semantic rules already defined for Swift are preserved.
The new rules are as follows:
@@ -178,8 +178,8 @@ Array elements can be explicitly declared ``val`` or ``ref``::
When a reference to an array appears without a variable name, it can
be written using the `usual syntax`__::
- var f : ()->ref Int[42] // a closure returning a reference to an array
- var b : ref Int[42] // equivalent to to "ref b : Int[42]"
+ var f : () -> ref Int[42] // a closure returning a reference to an array
+ var b : ref Int[42] // equivalent to "ref b : Int[42]"
__ `standalone types`_
@@ -191,8 +191,8 @@ brackets, that most users will never touch, e.g.::
var z : Array[ // an array of 42 integers-on-the-heap
var z : Array][, 2> // an array of 2 references to arrays
ref a : Array // a reference to an array of 42 integers
- var f : ()->ref Array // a closure returning a reference to an array
- var b : ref Array // equivalent to to "ref b : Int[42]"
+ var f : () -> ref Array // a closure returning a reference to an array
+ var b : ref Array // equivalent to "ref b : Int[42]"
Rules for copying array elements follow those of instance variables.
@@ -365,7 +365,7 @@ Objective-C Interoperability
Clonable Objective-C classes
-----------------------------
-In Cocoa, a notion similar to clonability is captured in the ``NSCopying`` and
+In Cocoa, a notion similar to cloneability is captured in the ``NSCopying`` and
``NSMutableCopying`` protocols, and a notion similar to ``val`` instance
variables is captured by the behavior of ``(copy)`` properties. However, there
are some behavioral and semantic differences that need to be taken into account.
@@ -425,7 +425,7 @@ How This Design Improves Swift
matters.
4. We move the cases where values and references interact much closer
- to, and arguably into, the “easy” zone.
+ to, and arguably into, the "easy" zone.
How This Design Beats Rust/C++/C#/etc.
======================================
@@ -437,7 +437,7 @@ How This Design Beats Rust/C++/C#/etc.
rooting`__, etc. By contrast, there's a path to learning swift that
postpones the ``val``\ /``ref`` distinction, and that's pretty much
*all* one must learn to have a complete understanding of the object
- model in the “easy” and “safe” zones.
+ model in the "easy" and "safe" zones.
__ http://static.rust-lang.org/doc/tutorial.html#boxes-and-pointers
__ http://static.rust-lang.org/doc/tutorial-borrowed-ptr.html#named-lifetimes
@@ -560,7 +560,7 @@ example:
There's always the dreaded ``auto``.
* Should we drop ``let``\ /``var``\ /``auto`` for ivars, because it
- “just feels wrong” there?
+ "just feels wrong" there?
* ``ref`` is spelled like ``[inout]``, but they mean very different things
@@ -569,7 +569,7 @@ example:
``[inout]``.
* Should we spell ``[inout]`` differently? I think at a high level
- it means something like “``[rebind]`` the name to a new value.”
+ it means something like "``[rebind]`` the name to a new value."
* Do we want to consider replacing ``struct`` and/or ``class`` with
new names such as ``valtype`` and ``reftype``? We don't love those
diff --git a/docs/scripts/ns-html2rst b/docs/scripts/ns-html2rst
index 004cf6f6d6a29..bc5ec847ea1d9 100755
--- a/docs/scripts/ns-html2rst
+++ b/docs/scripts/ns-html2rst
@@ -1,13 +1,15 @@
#!/usr/bin/env python
+from __future__ import print_function
+
import sys, re, subprocess
def run():
if len(sys.argv) > 1:
- print """
+ print("""
ns-html2rst - Convert Cocoa HTML documentation into ReST
usage: nshtml2rst < NSString.html > NSString.rst
- """
+ """)
exit(0)
html = sys.stdin.read()
diff --git a/docs/weak.rst b/docs/weak.rst
index 55079a9cc06d2..8ca03a0b7a36c 100644
--- a/docs/weak.rst
+++ b/docs/weak.rst
@@ -355,29 +355,29 @@ Finalization models built around calling a method on the
finalized object (such as Objective-C's :code:`-dealloc`)
suffer from a number of limitations and problems:
- - Since the method receives a pointer to the object being
- deallocated, the implementation must guard against
- attempts to resurrect the object. This may complicate
- and/or slow down the system's basic reference-management
- logic, which tends to be quite important for performance.
-
- - Since the method receives a pointer to the object being
- deallocated, the implementation must leave the object at
- least a minimally valid state until the user code is
- complete. For example, the instance variables of a
- subclass cannot be destroyed until a later phase of
- destruction, because a superclass finalizer might invoke
- subclass behavior. (This assumes that the dynamic type
- of the object does not change during destruction, which
- is an alternative that brings its own problems.)
-
- - Finalization code must be inherent to the object; other
- objects cannot request that code be run when the object
- is deallocated. For example, an object that registers
- itself to observe a certain event source must explicitly
- deregister itself in a finalizer; the event source cannot
- simply automatically drop the object when it is
- deallocated.
+- Since the method receives a pointer to the object being
+ deallocated, the implementation must guard against
+ attempts to resurrect the object. This may complicate
+ and/or slow down the system's basic reference-management
+ logic, which tends to be quite important for performance.
+
+- Since the method receives a pointer to the object being
+ deallocated, the implementation must leave the object at
+ least a minimally valid state until the user code is
+ complete. For example, the instance variables of a
+ subclass cannot be destroyed until a later phase of
+ destruction, because a superclass finalizer might invoke
+ subclass behavior. (This assumes that the dynamic type
+ of the object does not change during destruction, which
+ is an alternative that brings its own problems.)
+
+- Finalization code must be inherent to the object; other
+ objects cannot request that code be run when the object
+ is deallocated. For example, an object that registers
+ itself to observe a certain event source must explicitly
+ deregister itself in a finalizer; the event source cannot
+ simply automatically drop the object when it is
+ deallocated.
Optimization
------------
@@ -402,15 +402,15 @@ Proposal Overview
Looking at these use-cases, there are two main thrusts:
- - There is a general need to set up back references to objects.
- These references must be designed for convenient use by non-expert
- users.
+- There is a general need to set up back references to objects.
+ These references must be designed for convenient use by non-expert
+ users.
- - There are a number of more sophisticated use cases which require
- notification or interruption of deallocation; these can be used in
- the implementation of higher-level abstractions like weak caches.
- Here it is reasonable to expect more user expertise, such that
- power and flexibility should take priority over ease of use.
+- There are a number of more sophisticated use cases which require
+ notification or interruption of deallocation; these can be used in
+ the implementation of higher-level abstractions like weak caches.
+ Here it is reasonable to expect more user expertise, such that
+ power and flexibility should take priority over ease of use.
The second set of use cases should addressed by library types working
on top of basic runtime support.
@@ -439,11 +439,11 @@ variable-like declaration of reference type :code:`T`. For
type-system purposes, the variables behaves like a normal
variable of type :code:`Optional`, except:
- - it does not maintain a +1 reference count invariant and
+- it does not maintain a +1 reference count invariant and
- - loading from the variable after the current referent (if present)
- has started destruction will result in a :code:`Nothing` value,
- indistinguishable from the normal case.
+- loading from the variable after the current referent (if present)
+ has started destruction will result in a :code:`Nothing` value,
+ indistinguishable from the normal case.
The semantics are quite similar to weak references in other
environments (particularly Objective-C) except that the change in
@@ -485,10 +485,10 @@ designed without first having a solid error-handling design.
type-system purposes, the variable behaves exactly like a normal
variable of type :code:`T`, except:
- - it does not maintain a +1 reference count invariant and
+- it does not maintain a +1 reference count invariant and
- - loading from the variable after the referent has started
- destruction causes an assertion failure.
+- loading from the variable after the referent has started
+ destruction causes an assertion failure.
This is a refinement of :code:`weak` focused more narrowly on the case
of a back reference with relatively tight validity invariants. This
@@ -498,32 +498,32 @@ references; see below.
This name isn't really optimal. We've considered several different
candidates:
- - :code:`weak` is a poor choice because our semantics are very
- different from weak references in other environments where it's
- valid to access a cleared reference. Plus, we need to expose
- those semantics, so the name is claimed.
-
- - :code:`backref` is strongly evocative of the major use case in the
- static reference graph; this would encourage users to use it for
- back references and to consider alternatives for other cases, both
- of which I like. The latter also makes the husk-leaking
- implementation (see below) more palatable. It also contrasts very
- well with :code:`weak`. However, its evocativeness makes it
- unwieldy to use for local reference-counting optimizations.
-
- - :code:`dangling` is more general than :code:`backref`, but it has
- such strong negative associations that it wouldn't be unreasonable
- for users to assume that it's unsafe (with all the pursuant
- debugging difficulties) based on the name alone. I don't think
- we want to discourage a feature that can help users build tighter
- invariants on their classes.
-
- - :code:`unowned` is somewhat cleaner-looking, and it isn't as tied
- to a specific use case, but it does not contrast with :code:`weak`
- *at all*; only someone with considerable exposure to weak
- references would understand why we named each one the way we did,
- and even they are likely to roll their eyes at us. But it's okay
- for a working proposal.
+- :code:`weak` is a poor choice because our semantics are very
+ different from weak references in other environments where it's
+ valid to access a cleared reference. Plus, we need to expose
+ those semantics, so the name is claimed.
+
+- :code:`backref` is strongly evocative of the major use case in the
+ static reference graph; this would encourage users to use it for
+ back references and to consider alternatives for other cases, both
+ of which I like. The latter also makes the husk-leaking
+ implementation (see below) more palatable. It also contrasts very
+ well with :code:`weak`. However, its evocativeness makes it
+ unwieldy to use for local reference-counting optimizations.
+
+- :code:`dangling` is more general than :code:`backref`, but it has
+ such strong negative associations that it wouldn't be unreasonable
+ for users to assume that it's unsafe (with all the pursuant
+ debugging difficulties) based on the name alone. I don't think
+ we want to discourage a feature that can help users build tighter
+ invariants on their classes.
+
+- :code:`unowned` is somewhat cleaner-looking, and it isn't as tied
+ to a specific use case, but it does not contrast with :code:`weak`
+ *at all*; only someone with considerable exposure to weak
+ references would understand why we named each one the way we did,
+ and even they are likely to roll their eyes at us. But it's okay
+ for a working proposal.
Asserting and Uncheckable
.........................
@@ -716,7 +716,7 @@ One complication with extending :code:`weak` to value types is that
generally the implementing type will need to be different from the
underlying value type. Probably the best solution would be to hide
the use of the implementing type from the type system outside of the
-well-formedness checks for the variable; SIL-gen would lower the field
+wellformedness checks for the variable; SIL-gen would lower the field
to its implementing type using the appropriate protocol conformances.
As long as we have convenient optional back-references, though, we
@@ -857,19 +857,19 @@ become laborious and redundant, and a different mechanism is called for.
In the following discussion, a *var-or-member expression* is an
expression which is semantically constrained to be one of:
- - A reference to a local variable-like declaration from an
- enclosing context.
+- A reference to a local variable-like declaration from an
+ enclosing context.
- - A member access thereof, possibly recursively.
+- A member access thereof, possibly recursively.
Such expressions have two useful traits:
- - They always end in an identifier which on some level meaningfully
- identifies the object.
+- They always end in an identifier which on some level meaningfully
+ identifies the object.
- - Evaluating them is relatively likely (but not guaranteed) to not
- have interesting side effects, and so we feel less bad about
- apparently shifting their evaluation around.
+- Evaluating them is relatively likely (but not guaranteed) to not
+ have interesting side effects, and so we feel less bad about
+ apparently shifting their evaluation around.
Decorated Capture References
----------------------------
@@ -1141,7 +1141,7 @@ The library should definitely provide the following types:
will preserve the weakness of the reference.
In keeping with our design for :code:`unowned`, I think this type
- should should actually be an alias to either
+ should actually be an alias to either
:code:`SafeUnownedReference` or :code:`UnsafeUnownedReference`
depending on the current component's build settings. The choice
would be exported in binary modules, but for cleanliness we would
diff --git a/include/swift/ABI/Class.h b/include/swift/ABI/Class.h
index df17094aaf7dd..9b1c7ad858a56 100644
--- a/include/swift/ABI/Class.h
+++ b/include/swift/ABI/Class.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -22,7 +22,7 @@
namespace swift {
-/// Objetive-C class flags, stored in the ro-data.
+/// Objective-C class flags, stored in the ro-data.
enum class ObjCClassFlags : uint32_t {
/// This class is a metaclass.
Meta = 0x00001,
diff --git a/include/swift/ABI/Compression.h b/include/swift/ABI/Compression.h
new file mode 100644
index 0000000000000..83152a3667b96
--- /dev/null
+++ b/include/swift/ABI/Compression.h
@@ -0,0 +1,53 @@
+//===--- Compression.h - Defines the compression interface ------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See http://swift.org/LICENSE.txt for license information
+// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+#ifndef SWIFT_ABI_COMPRESSION_H
+#define SWIFT_ABI_COMPRESSION_H
+
+#include "llvm/ADT/APInt.h"
+#include
+
+namespace swift {
+namespace Compress {
+
+/// Compress a string using the swift codebook compression.
+/// Returns a new compressed string from \p In.
+std::string DecodeCBCString(llvm::StringRef In);
+
+/// Decompress a string using the swift codebook compression.
+/// Returns a new decompressed string from \p In.
+std::string EncodeCBCString(llvm::StringRef In);
+
+/// Character encoding kind:
+/// Variable - huffman encoding using variable length characters.
+/// Fixed - simple fixed length characters.
+enum class EncodingKind { Variable, Fixed };
+
+/// Convert the string \p In into a number using a fixed length or variable
+/// length encoding.
+llvm::APInt EncodeStringAsNumber(llvm::StringRef In, EncodingKind Kind);
+
+/// Convert the number \p In into a string using a fixed length or variable
+/// length encoding.
+std::string DecodeStringFromNumber(const llvm::APInt &In, EncodingKind Kind);
+
+/// Compress the string \p In with CBC and variable length encoding.
+/// On error return an empty string.
+std::string CompressName(llvm::StringRef In);
+
+/// Decompress the string \p, which is compressed using the swift name
+/// compression. On error return an empty string.
+std::string DecompressName(llvm::StringRef In);
+
+} // namespace Compress
+} // namespace swift
+#endif /* SWIFT_ABI_COMPRESSION_H */
+
diff --git a/include/swift/ABI/MetadataKind.def b/include/swift/ABI/MetadataKind.def
index 1e8d454288756..7747bd9def2e9 100644
--- a/include/swift/ABI/MetadataKind.def
+++ b/include/swift/ABI/MetadataKind.def
@@ -1,8 +1,8 @@
-//===--- MetadataKind.def --------------------------------------*- C++ -*--===//
+//===--- MetadataKind.def ---------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -47,6 +47,9 @@ NOMINALTYPEMETADATAKIND(Struct, 1)
/// If we add reference enums, that needs to go here.
NOMINALTYPEMETADATAKIND(Enum, 2)
+/// An optional type.
+NOMINALTYPEMETADATAKIND(Optional, 3)
+
/// A type whose value is not exposed in the metadata system.
METADATAKIND(Opaque, 8)
diff --git a/include/swift/ABI/MetadataValues.h b/include/swift/ABI/MetadataValues.h
index 73ec6843095eb..6a91131ac1291 100644
--- a/include/swift/ABI/MetadataValues.h
+++ b/include/swift/ABI/MetadataValues.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/ABI/System.h b/include/swift/ABI/System.h
index f0214fd427b85..dceb3e85bc5b2 100644
--- a/include/swift/ABI/System.h
+++ b/include/swift/ABI/System.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/AST.h b/include/swift/AST/AST.h
index b0b68744720da..283ceb1e7d7d4 100644
--- a/include/swift/AST/AST.h
+++ b/include/swift/AST/AST.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -25,6 +25,7 @@
#include "swift/AST/ExprHandle.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/Module.h"
+#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Types.h"
diff --git a/include/swift/AST/ASTContext.h b/include/swift/AST/ASTContext.h
index 7349cef227efb..d21c1d790b8fc 100644
--- a/include/swift/AST/ASTContext.h
+++ b/include/swift/AST/ASTContext.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -34,7 +34,6 @@
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/TinyPtrVector.h"
-#include "llvm/ADT/StringMap.h"
#include "llvm/Support/Allocator.h"
#include
#include
@@ -281,7 +280,7 @@ class ASTContext {
template
typename std::remove_reference::type *AllocateObjectCopy(T &&t,
AllocationArena arena = AllocationArena::Permanent) const {
- // This function can not be named AllocateCopy because it would always win
+ // This function cannot be named AllocateCopy because it would always win
// overload resolution over the AllocateCopy(ArrayRef).
using TNoRef = typename std::remove_reference::type;
TNoRef *res = (TNoRef *) Allocate(sizeof(TNoRef), alignof(TNoRef), arena);
@@ -481,6 +480,9 @@ class ASTContext {
/// Retrieve the declaration of Swift._unimplemented_initializer.
FuncDecl *getUnimplementedInitializerDecl(LazyResolver *resolver) const;
+ /// Retrieve the declaration of Swift._undefined.
+ FuncDecl *getUndefinedDecl(LazyResolver *resolver) const;
+
// Retrieve the declaration of Swift._stdlib_isOSVersionAtLeast.
FuncDecl *getIsOSVersionAtLeastDecl(LazyResolver *resolver) const;
@@ -587,7 +589,7 @@ class ASTContext {
/// one.
void loadExtensions(NominalTypeDecl *nominal, unsigned previousGeneration);
- /// \brief Load the methods within the given class that that produce
+ /// \brief Load the methods within the given class that produce
/// Objective-C class or instance methods with the given selector.
///
/// \param classDecl The class in which we are searching for @objc methods.
@@ -601,7 +603,7 @@ class ASTContext {
///
/// \param previousGeneration The previous generation with which this
/// callback was invoked. The list of methods will already contain all of
- /// the results from generations up and and including \c previousGeneration.
+ /// the results from generations up and including \c previousGeneration.
///
/// \param methods The list of @objc methods in this class that have this
/// selector and are instance/class methods as requested. This list will be
@@ -788,7 +790,7 @@ class ASTContext {
/// Collect visible clang modules from the ClangModuleLoader. These modules are
/// not necessarily loaded.
- void getVisibleTopLevelClangeModules(SmallVectorImpl &Modules) const;
+ void getVisibleTopLevelClangModules(SmallVectorImpl &Modules) const;
/// Retrieve or create the stored archetype builder for the given
/// canonical generic signature and module.
diff --git a/include/swift/AST/ASTNode.h b/include/swift/AST/ASTNode.h
index 2570d04a8a148..da20251935ddb 100644
--- a/include/swift/AST/ASTNode.h
+++ b/include/swift/AST/ASTNode.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -18,7 +18,6 @@
#define SWIFT_AST_AST_NODE_H
#include "llvm/ADT/PointerUnion.h"
-#include "swift/AST/ASTWalker.h"
#include "swift/AST/TypeAlignments.h"
namespace swift {
@@ -27,6 +26,7 @@ namespace swift {
class Decl;
class SourceLoc;
class SourceRange;
+ class ASTWalker;
struct ASTNode : public llvm::PointerUnion3 {
// Inherit the constructors from PointerUnion.
diff --git a/include/swift/AST/ASTPrinter.h b/include/swift/AST/ASTPrinter.h
index e56eac35ae955..65b0a54ca6e60 100644
--- a/include/swift/AST/ASTPrinter.h
+++ b/include/swift/AST/ASTPrinter.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -30,10 +30,13 @@ namespace swift {
/// Describes the context in which a name is being printed, which
/// affects the keywords that need to be escaped.
enum class PrintNameContext {
- // Normal context
+ /// Normal context
Normal,
- // Generic parameter context, where 'Self' is not escaped.
+ /// Generic parameter context, where 'Self' is not escaped.
GenericParameter,
+ /// Function parameter context, where keywords other than let/var/inout are
+ /// not escaped.
+ FunctionParameter,
};
/// An abstract class used to print an AST.
@@ -102,7 +105,7 @@ class ASTPrinter {
PendingDeclLocCallback = D;
}
- /// To sanitize a malformatted utf8 string to a well-formatted one.
+ /// To sanitize a malformed utf8 string to a well-formed one.
static std::string sanitizeUtf8(StringRef Text);
static bool printTypeInterface(Type Ty, DeclContext *DC, std::string &Result);
static bool printTypeInterface(Type Ty, DeclContext *DC, llvm::raw_ostream &Out);
diff --git a/include/swift/AST/ASTVisitor.h b/include/swift/AST/ASTVisitor.h
index e48987a12494f..acdcae3192adc 100644
--- a/include/swift/AST/ASTVisitor.h
+++ b/include/swift/AST/ASTVisitor.h
@@ -1,8 +1,8 @@
-//===-- ASTVisitor.h - Decl, Expr and Stmt Visitor --------------*- C++ -*-===//
+//===--- ASTVisitor.h - Decl, Expr and Stmt Visitor -------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -27,6 +27,7 @@
#include "llvm/Support/ErrorHandling.h"
namespace swift {
+ class ParameterList;
/// ASTVisitor - This is a simple visitor class for Swift expressions.
template(AA)...); \
}
#include "swift/AST/Attr.def"
+
+ bool visit(ParameterList *PL) {
+ return static_cast(this)->visitParameterList(PL);
+ }
+
+ bool visitParameterList(ParameterList *PL) { return false; }
};
diff --git a/include/swift/AST/ASTWalker.h b/include/swift/AST/ASTWalker.h
index b5115f0a26b21..43fb12cb6abfe 100644
--- a/include/swift/AST/ASTWalker.h
+++ b/include/swift/AST/ASTWalker.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -25,6 +25,7 @@ class Stmt;
class Pattern;
class TypeRepr;
struct TypeLoc;
+class ParameterList;
/// \brief An abstract class used to traverse an AST.
class ASTWalker {
@@ -182,6 +183,18 @@ class ASTWalker {
/// params in an AbstractFunctionDecl.
virtual bool shouldWalkIntoFunctionGenericParams() { return false; }
+ /// walkToParameterListPre - This method is called when first visiting a
+ /// ParameterList, before walking into its parameters. If it returns false,
+ /// the subtree is skipped.
+ ///
+ virtual bool walkToParameterListPre(ParameterList *PL) { return true; }
+
+ /// walkToParameterListPost - This method is called after visiting the
+ /// children of a parameter list. If it returns false, the remaining
+ /// traversal is terminated and returns failure.
+ virtual bool walkToParameterListPost(ParameterList *PL) { return true; }
+
+
protected:
ASTWalker() = default;
ASTWalker(const ASTWalker &) = default;
diff --git a/include/swift/AST/AnyFunctionRef.h b/include/swift/AST/AnyFunctionRef.h
index d72c8548aabc2..01455fb313272 100644
--- a/include/swift/AST/AnyFunctionRef.h
+++ b/include/swift/AST/AnyFunctionRef.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -61,10 +61,10 @@ class AnyFunctionRef {
getCaptureInfo().getLocalCaptures(Result);
}
- ArrayRef getBodyParamPatterns() const {
+ ArrayRef getParameterLists() const {
if (auto *AFD = TheFunction.dyn_cast())
- return AFD->getBodyParamPatterns();
- return TheFunction.get()->getParamPatterns();
+ return AFD->getParameterLists();
+ return TheFunction.get()->getParameterLists();
}
bool hasType() const {
diff --git a/include/swift/AST/ArchetypeBuilder.h b/include/swift/AST/ArchetypeBuilder.h
index 2922cae789c9b..cb95ff800d0f2 100644
--- a/include/swift/AST/ArchetypeBuilder.h
+++ b/include/swift/AST/ArchetypeBuilder.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -176,7 +176,7 @@ class ArchetypeBuilder {
void visitPotentialArchetypes(F f);
public:
- /// Construct a new archtype builder.
+ /// Construct a new archetype builder.
///
/// \param mod The module in which the builder will create archetypes.
///
@@ -218,6 +218,12 @@ class ArchetypeBuilder {
/// \returns true if an error occurred, false otherwise.
bool addGenericParameter(GenericTypeParamDecl *GenericParam);
+ /// Add the requirements placed on the given abstract type parameter
+ /// to the given potential archetype.
+ ///
+ /// \returns true if an error occurred, false otherwise.
+ bool addGenericParameterRequirements(GenericTypeParamDecl *GenericParam);
+
/// \brief Add a new generic parameter for which there may be requirements.
///
/// \returns true if an error occurred, false otherwise.
@@ -245,6 +251,14 @@ class ArchetypeBuilder {
bool addGenericSignature(GenericSignature *sig, bool adoptArchetypes,
bool treatRequirementsAsExplicit = false);
+ /// \brief Get a generic signature based on the provided complete list
+ /// of generic parameter types.
+ ///
+ /// \returns a generic signature build based on the provided list of
+ /// generic parameter types.
+ GenericSignature *
+ getGenericSignature(ArrayRef genericParamsTypes);
+
/// Infer requirements from the given type, recursively.
///
/// This routine infers requirements from a type that occurs within the
@@ -275,12 +289,12 @@ class ArchetypeBuilder {
/// because the type \c Dictionary cannot be formed without it.
///
/// \returns true if an error occurred, false otherwise.
- bool inferRequirements(Pattern *pattern, GenericParamList *genericParams);
+ bool inferRequirements(ParameterList *params,GenericParamList *genericParams);
/// Finalize the set of requirements, performing any remaining checking
/// required before generating archetypes.
///
- /// \returns true if an error occurs, false otherwse.
+ /// \returns true if an error occurs, false otherwise.
bool finalize(SourceLoc loc);
/// \brief Resolve the given type to the potential archetype it names.
diff --git a/include/swift/AST/Attr.def b/include/swift/AST/Attr.def
index 9f74e9e5fa195..264b72f05ac74 100644
--- a/include/swift/AST/Attr.def
+++ b/include/swift/AST/Attr.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -37,7 +37,6 @@ TYPE_ATTR(noreturn)
// SIL-specific attributes
TYPE_ATTR(block_storage)
TYPE_ATTR(box)
-TYPE_ATTR(local_storage)
TYPE_ATTR(sil_unowned)
TYPE_ATTR(sil_unmanaged)
TYPE_ATTR(sil_weak)
@@ -45,6 +44,7 @@ TYPE_ATTR(error)
TYPE_ATTR(out)
TYPE_ATTR(in)
TYPE_ATTR(inout)
+TYPE_ATTR(inout_aliasable)
TYPE_ATTR(in_guaranteed)
TYPE_ATTR(noescape) // Only valid in sil mode.
TYPE_ATTR(owned)
@@ -91,7 +91,7 @@ SIMPLE_DECL_ATTR(final, Final,
DECL_ATTR(objc, ObjC,
OnFunc | OnClass | OnProtocol | OnVar | OnSubscript |
- OnConstructor | OnDestructor | OnEnum, 3)
+ OnConstructor | OnDestructor | OnEnum | OnEnumElement, 3)
SIMPLE_DECL_ATTR(required, Required,
OnConstructor|DeclModifier, 4)
@@ -139,7 +139,7 @@ DECL_ATTR(inline, Inline, OnFunc | OnConstructor, 20)
DECL_ATTR(_semantics, Semantics,
OnFunc | OnConstructor | OnDestructor | OnSubscript |
- UserInaccessible, 21)
+ AllowMultipleAttributes | UserInaccessible, 21)
SIMPLE_DECL_ATTR(dynamic, Dynamic,
OnFunc | OnVar | OnSubscript | OnConstructor | DeclModifier, 22)
@@ -239,6 +239,8 @@ SIMPLE_DECL_ATTR(indirect, Indirect,
SIMPLE_DECL_ATTR(warn_unqualified_access, WarnUnqualifiedAccess,
OnFunc /*| OnVar*/ | LongAttribute, 61)
+DECL_ATTR(_migration_id, MigrationId, OnAnyDecl, 62)
+
#undef TYPE_ATTR
#undef DECL_ATTR_ALIAS
#undef SIMPLE_DECL_ATTR
diff --git a/include/swift/AST/Attr.h b/include/swift/AST/Attr.h
index 9fcaa865b8266..36e094df4c51a 100644
--- a/include/swift/AST/Attr.h
+++ b/include/swift/AST/Attr.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -19,6 +19,8 @@
#include "swift/Basic/SourceLoc.h"
#include "swift/Basic/UUID.h"
+#include "swift/Basic/STLExtras.h"
+#include "swift/Basic/Range.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/KnownProtocols.h"
#include "swift/AST/Ownership.h"
@@ -462,7 +464,7 @@ class DeclAttribute : public AttributeBase {
static bool canAttributeAppearOnDecl(DeclAttrKind DK, const Decl *D);
/// Returns true if multiple instances of an attribute kind
- /// can appear on a delcaration.
+ /// can appear on a declaration.
static bool allowMultipleAttributes(DeclAttrKind DK) {
return getOptions(DK) & AllowMultipleAttributes;
}
@@ -642,7 +644,7 @@ enum class MinVersionComparison {
Unavailable,
/// The entity might be unavailable, because it was introduced after
- /// the minimimum version.
+ /// the minimum version.
PotentiallyUnavailable,
/// The entity has been obsoleted.
@@ -1148,6 +1150,31 @@ class WarnUnusedResultAttr : public DeclAttribute {
}
};
+/// The internal @_migration_id attribute, which is used to keep track of stdlib
+/// changes for migration purposes.
+class MigrationIdAttr : public DeclAttribute {
+ StringRef Ident;
+ StringRef PatternId;
+
+public:
+ MigrationIdAttr(SourceLoc atLoc, SourceLoc attrLoc, SourceLoc lParenLoc,
+ StringRef ident, StringRef patternId,
+ SourceLoc rParenLoc, bool implicit)
+ : DeclAttribute(DAK_MigrationId, attrLoc,
+ SourceRange(atLoc, rParenLoc), implicit),
+ Ident(ident), PatternId(patternId) {}
+
+ /// Retrieve the migration identifier associated with the symbol.
+ StringRef getIdent() const { return Ident; }
+
+ /// Retrieve pattern identifier associated with the symbol.
+ StringRef getPatternId() const { return PatternId; }
+
+ static bool classof(const DeclAttribute *DA) {
+ return DA->getKind() == DAK_MigrationId;
+ }
+};
+
/// \brief Attributes that may be applied to declarations.
class DeclAttributes {
/// Linked list of declaration attributes.
@@ -1258,6 +1285,34 @@ class DeclAttributes {
return nullptr;
}
+private:
+ /// Predicate used to filter MatchingAttributeRange.
+ template struct ToAttributeKind {
+ ToAttributeKind() {}
+
+ Optional
+ operator()(const DeclAttribute *Attr) const {
+ if (isa(Attr) && (Attr->isValid() || AllowInvalid))
+ return Attr;
+ return None;
+ }
+ };
+
+public:
+ template
+ using AttributeKindRange =
+ OptionalTransformRange,
+ ToAttributeKind,
+ const_iterator>;
+
+ /// Return a range with all attributes in DeclAttributes with AttrKind
+ /// ATTR.
+ template
+ AttributeKindRange getAttributes() const {
+ return AttributeKindRange(
+ make_range(begin(), end()), ToAttributeKind());
+ }
+
// Remove the given attribute from the list of attributes. Used when
// the attribute was semantically invalid.
void removeAttribute(const DeclAttribute *attr) {
diff --git a/include/swift/AST/Availability.h b/include/swift/AST/Availability.h
index 731edec4f4f34..cd38482080e99 100644
--- a/include/swift/AST/Availability.h
+++ b/include/swift/AST/Availability.h
@@ -1,8 +1,8 @@
-//===--- Availability.h - Swift Availability Structures -----*- C++ -*-===//
+//===--- Availability.h - Swift Availability Structures ---------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -35,7 +35,7 @@ class VersionRange {
// The concretization of lattice elements is:
// Empty: empty
// All: all versions
- // x.y.x: all versions greater than or equal to to x.y.z
+ // x.y.x: all versions greater than or equal to x.y.z
enum class ExtremalRange { Empty, All };
@@ -117,7 +117,7 @@ class VersionRange {
}
/// Mutates this range to be the union of itself and Other. This is the
- /// join operator (least upper bound) in the veresion range lattice.
+ /// join operator (least upper bound) in the version range lattice.
void unionWith(const VersionRange &Other) {
// With the existing lattice this operation is precise. If the lattice
// is ever extended it is important that this operation be an
@@ -242,9 +242,9 @@ class AvailabilityInference {
/// We assume a declaration without an annotation is always available.
static VersionRange availableRange(const Decl *D, ASTContext &C);
- /// \brief Returns the version range on which the declaration for which
- /// declaration is annotated as available, or None if the declaration
- /// has not availability annotation.
+ /// \brief Returns the version range for which the declaration
+ /// is annotated as available, or None if the declaration
+ /// has no availability annotation.
static Optional annotatedAvailableRange(const Decl *D,
ASTContext &C);
diff --git a/include/swift/AST/AvailabilitySpec.h b/include/swift/AST/AvailabilitySpec.h
index 23c28e409ee31..7bc9b9876bb5a 100644
--- a/include/swift/AST/AvailabilitySpec.h
+++ b/include/swift/AST/AvailabilitySpec.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -97,7 +97,7 @@ class VersionConstraintAvailabilitySpec : public AvailabilitySpec {
/// to new platforms. Because new platforms typically branch from
/// existing platforms, the wildcard allows an #available() check to do the
/// "right" thing (executing the guarded branch) on the new platform without
-/// requiring a modification to every availablity guard in the program. Note
+/// requiring a modification to every availability guard in the program. Note
/// that we still do compile-time availability checking with '*', so the
/// compiler will still catch references to potentially unavailable symbols.
class OtherPlatformAvailabilitySpec : public AvailabilitySpec {
diff --git a/include/swift/AST/Builtins.def b/include/swift/AST/Builtins.def
index a6592e5eb4f5f..9437d8f7f683b 100644
--- a/include/swift/AST/Builtins.def
+++ b/include/swift/AST/Builtins.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -353,6 +353,11 @@ BUILTIN_RUNTIME_CALL(UnexpectedError, "unexpectedError", "")
/// errorInMain: ErrorType -> ()
BUILTIN_RUNTIME_CALL(ErrorInMain, "errorInMain", "")
+/// IsOptionalType : T.Type -> Bool
+/// This builtin takes a metatype and returns true if the metatype's
+/// nominal type is Optional.
+BUILTIN_RUNTIME_CALL(IsOptionalType, "isOptional", "")
+
#undef BUILTIN_RUNTIME_CALL
// BUILTIN_MISC_OPERATION - Miscellaneous operations without a unifying class.
diff --git a/include/swift/AST/Builtins.h b/include/swift/AST/Builtins.h
index 66b74381686b8..07933bd22f0d9 100644
--- a/include/swift/AST/Builtins.h
+++ b/include/swift/AST/Builtins.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -91,7 +91,7 @@ getLLVMIntrinsicIDForBuiltinWithOverflow(BuiltinValueKind ID);
/// Returns null if the name does not identifier a known builtin value.
ValueDecl *getBuiltinValueDecl(ASTContext &Context, Identifier Name);
-/// \brief Returns the name of a builtin declaration given an builtin ID.
+/// \brief Returns the name of a builtin declaration given a builtin ID.
StringRef getBuiltinName(BuiltinValueKind ID);
/// \brief The information identifying the builtin - its kind and types.
diff --git a/include/swift/AST/CanTypeVisitor.h b/include/swift/AST/CanTypeVisitor.h
index 345706d33e94b..0904ee40d2232 100644
--- a/include/swift/AST/CanTypeVisitor.h
+++ b/include/swift/AST/CanTypeVisitor.h
@@ -1,8 +1,8 @@
-//===-- CanTypeVisitor.h - TypeVisitor specialization -----------*- C++ -*-===//
+//===--- CanTypeVisitor.h - TypeVisitor specialization ----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/CaptureInfo.h b/include/swift/AST/CaptureInfo.h
index d60af9c679861..8ca4faab21d7f 100644
--- a/include/swift/AST/CaptureInfo.h
+++ b/include/swift/AST/CaptureInfo.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/ClangModuleLoader.h b/include/swift/AST/ClangModuleLoader.h
index cbc9266e2ae1e..f9062a26d0512 100644
--- a/include/swift/AST/ClangModuleLoader.h
+++ b/include/swift/AST/ClangModuleLoader.h
@@ -1,8 +1,8 @@
-//===--- ClangModuleLoader.h - Clang Module Loader Interface --*- C++ -*- -===//
+//===--- ClangModuleLoader.h - Clang Module Loader Interface ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/Comment.h b/include/swift/AST/Comment.h
index 50e8793a97343..3018ff77bafc3 100644
--- a/include/swift/AST/Comment.h
+++ b/include/swift/AST/Comment.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/ConcreteDeclRef.h b/include/swift/AST/ConcreteDeclRef.h
index 8afa6b9670ad3..abddc14eaccce 100644
--- a/include/swift/AST/ConcreteDeclRef.h
+++ b/include/swift/AST/ConcreteDeclRef.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DebuggerClient.h b/include/swift/AST/DebuggerClient.h
index 6f6d9c523220b..70dcc573736bc 100644
--- a/include/swift/AST/DebuggerClient.h
+++ b/include/swift/AST/DebuggerClient.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index be729431cf27e..8f94f8e7b25c1 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -17,29 +17,14 @@
#ifndef SWIFT_DECL_H
#define SWIFT_DECL_H
-#include "swift/AST/Attr.h"
#include "swift/AST/CaptureInfo.h"
-#include "swift/AST/DeclContext.h"
#include "swift/AST/DefaultArgumentKind.h"
#include "swift/AST/GenericSignature.h"
-#include "swift/AST/KnownProtocols.h"
-#include "swift/AST/Identifier.h"
#include "swift/AST/LazyResolver.h"
-#include "swift/AST/Requirement.h"
-#include "swift/AST/Substitution.h"
-#include "swift/AST/Type.h"
-#include "swift/AST/TypeLoc.h"
#include "swift/Basic/OptionalEnum.h"
#include "swift/Basic/Range.h"
-#include "swift/Basic/SourceLoc.h"
-#include "swift/Basic/STLExtras.h"
-#include "llvm/Support/ErrorHandling.h"
-#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
-#include "llvm/ADT/Hashing.h"
-#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallPtrSet.h"
-#include
namespace clang {
class Decl;
@@ -76,6 +61,7 @@ namespace swift {
class NameAliasType;
class EnumCaseDecl;
class EnumElementDecl;
+ class ParameterList;
class Pattern;
struct PrintOptions;
class ProtocolDecl;
@@ -209,7 +195,7 @@ enum class CircularityCheck {
Checked
};
-/// Keeps track of whrther a given class inherits initializers from its
+/// Keeps track of whether a given class inherits initializers from its
/// superclass.
enum class StoredInheritsSuperclassInits {
/// We have not yet checked.
@@ -386,8 +372,8 @@ class alignas(1 << DeclAlignInBits) Decl {
/// \see AbstractFunctionDecl::BodyKind
unsigned BodyKind : 3;
- /// Number of curried parameter patterns (tuples).
- unsigned NumParamPatterns : 6;
+ /// Number of curried parameter lists.
+ unsigned NumParameterLists : 6;
/// Whether we are overridden later.
unsigned Overridden : 1;
@@ -573,8 +559,11 @@ class alignas(1 << DeclAlignInBits) Decl {
unsigned : NumTypeDeclBits;
unsigned Recursive : 1;
+
+ /// Whether or not this declaration is currently being type-checked.
+ unsigned BeingTypeChecked : 1;
};
- enum { NumAssociatedTypeDeclBits = NumTypeDeclBits + 1 };
+ enum { NumAssociatedTypeDeclBits = NumTypeDeclBits + 2 };
static_assert(NumAssociatedTypeDeclBits <= 32, "fits in an unsigned");
class ImportDeclBitfields {
@@ -868,7 +857,7 @@ class alignas(1 << DeclAlignInBits) Decl {
// Only allow allocation of Decls using the allocator in ASTContext
// or by doing a placement new.
- void *operator new(size_t Bytes, ASTContext &C,
+ void *operator new(size_t Bytes, const ASTContext &C,
unsigned Alignment = alignof(Decl));
void *operator new(size_t Bytes, void *Mem) {
assert(Mem);
@@ -1556,7 +1545,7 @@ class ImportDecl : public Decl {
/// Returns the most appropriate import kind for the given list of decls.
///
- /// If the list is non-homogenous, or if there is more than one decl that
+ /// If the list is non-homogeneous, or if there is more than one decl that
/// cannot be overloaded, returns None.
static Optional findBestImportKind(ArrayRef Decls);
@@ -2174,6 +2163,7 @@ class ValueDecl : public Decl {
/// Retrieve the full name of the declaration.
/// TODO: Rename to getName?
DeclName getFullName() const { return Name; }
+ void setName(DeclName name) { Name = name; }
/// Retrieve the base name of the declaration, ignoring any argument
/// names.
@@ -2239,16 +2229,6 @@ class ValueDecl : public Decl {
/// If \p DC is null, returns true only if this declaration is public.
bool isAccessibleFrom(const DeclContext *DC) const;
- /// Get the innermost declaration context that can provide generic
- /// parameters used within this declaration.
- DeclContext *getPotentialGenericDeclContext();
-
- /// Get the innermost declaration context that can provide generic
- /// parameters used within this declaration.
- const DeclContext *getPotentialGenericDeclContext() const {
- return const_cast(this)->getPotentialGenericDeclContext();
- }
-
/// Retrieve the "interface" type of this value, which is the type used when
/// the declaration is viewed from the outside. For a generic function,
/// this will have generic function type using generic parameters rather than
@@ -2402,7 +2382,7 @@ class TypeAliasDecl : public TypeDecl {
/// The type that represents this (sugared) name alias.
mutable NameAliasType *AliasTy;
- SourceLoc TypeAliasLoc; // The location of the 'typalias' keyword
+ SourceLoc TypeAliasLoc; // The location of the 'typealias' keyword
TypeLoc UnderlyingTy;
public:
@@ -2605,6 +2585,14 @@ class AssociatedTypeDecl : public AbstractTypeParamDecl {
void setIsRecursive() { AssociatedTypeDeclBits.Recursive = true; }
bool isRecursive() { return AssociatedTypeDeclBits.Recursive; }
+ /// Whether the declaration is currently being validated.
+ bool isBeingTypeChecked() { return AssociatedTypeDeclBits.BeingTypeChecked; }
+
+ /// Toggle whether or not the declaration is being validated.
+ void setIsBeingTypeChecked(bool ibt = true) {
+ AssociatedTypeDeclBits.BeingTypeChecked = ibt;
+ }
+
static bool classof(const Decl *D) {
return D->getKind() == DeclKind::AssociatedType;
}
@@ -2797,7 +2785,7 @@ class NominalTypeDecl : public TypeDecl, public DeclContext,
return ValidatingGenericSignature;
}
- /// \brief Returns true if this this decl contains delayed value or protocol
+ /// \brief Returns true if this decl contains delayed value or protocol
/// declarations.
bool hasDelayedMembers() const {
return NominalTypeDeclBits.HasDelayedMembers;
@@ -2860,9 +2848,6 @@ class NominalTypeDecl : public TypeDecl, public DeclContext,
return GenericSig;
}
- /// Mark generic type signature as invalid.
- void markInvalidGenericSignature();
-
/// getDeclaredType - Retrieve the type declared by this entity.
Type getDeclaredType() const { return DeclaredTy; }
@@ -3263,17 +3248,19 @@ class ClassDecl : public NominalTypeDecl {
return ClassDeclBits.Foreign;
}
void setForeign(bool isForeign = true) {
- ClassDeclBits.Foreign = true;
+ ClassDeclBits.Foreign = isForeign;
}
/// Find a method of a class that overrides a given method.
/// Return nullptr, if no such method exists.
- FuncDecl *findOverridingDecl(const FuncDecl *method) const;
+ AbstractFunctionDecl *findOverridingDecl(
+ const AbstractFunctionDecl *method) const;
/// Find a method implementation which will be used when a given method
/// is invoked on an instance of this class. This implementation may stem
/// either from a class itself or its direct or indirect superclasses.
- FuncDecl *findImplementingMethod(const FuncDecl *method) const;
+ AbstractFunctionDecl *findImplementingMethod(
+ const AbstractFunctionDecl *method) const;
/// True if the class has a destructor.
///
@@ -3947,7 +3934,7 @@ class AbstractStorageDecl : public ValueDecl {
return getAddressorInfo().MutableAddress;
}
- /// \brief Return the approproiate addressor for the given access kind.
+ /// \brief Return the appropriate addressor for the given access kind.
FuncDecl *getAddressorForAccess(AccessKind accessKind) const {
if (accessKind == AccessKind::Read)
return getAddressor();
@@ -4022,7 +4009,7 @@ class AbstractStorageDecl : public ValueDecl {
/// VarDecl - 'var' and 'let' declarations.
class VarDecl : public AbstractStorageDecl {
protected:
- llvm::PointerUnion3 ParentPattern;
+ llvm::PointerUnion ParentPattern;
VarDecl(DeclKind Kind, bool IsStatic, bool IsLet, SourceLoc NameLoc,
Identifier Name, Type Ty, DeclContext *DC)
@@ -4075,9 +4062,9 @@ class VarDecl : public AbstractStorageDecl {
ParentPattern = PBD;
}
- /// Return the Pattern involved in initializing this VarDecl. Recall that the
- /// Pattern may be involved in initializing more than just this one vardecl
- /// though. For example, if this is a VarDecl for "x", the pattern may be
+ /// Return the Pattern involved in initializing this VarDecl. However, recall
+ /// that the Pattern may be involved in initializing more than just this one
+ /// vardecl. For example, if this is a VarDecl for "x", the pattern may be
/// "(x, y)" and the initializer on the PatternBindingDecl may be "(1,2)" or
/// "foo()".
///
@@ -4095,7 +4082,7 @@ class VarDecl : public AbstractStorageDecl {
ParentPattern = S;
}
- /// Return the initializer involved in this VarDecl. However, Recall that the
+ /// Return the initializer involved in this VarDecl. Recall that the
/// initializer may be involved in initializing more than just this one
/// vardecl though. For example, if this is a VarDecl for "x", the pattern
/// may be "(x, y)" and the initializer on the PatternBindingDecl may be
@@ -4163,7 +4150,7 @@ class VarDecl : public AbstractStorageDecl {
void emitLetToVarNoteIfSimple(DeclContext *UseDC) const;
/// Returns true if the name is the self identifier and is implicit.
- bool isImplicitSelf() const;
+ bool isSelfParameter() const;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) {
@@ -4176,14 +4163,32 @@ class ParamDecl : public VarDecl {
Identifier ArgumentName;
SourceLoc ArgumentNameLoc;
+ /// This is the type specified, including location information.
+ TypeLoc typeLoc;
+
+ /// The default value, if any, along with whether this is varargs.
+ llvm::PointerIntPair DefaultValueAndIsVariadic;
+
+ /// True if the type is implicitly specified in the source, but this has an
+ /// apparently valid typeRepr. This is used in accessors, which look like:
+ /// set (value) {
+ /// but need to get the typeRepr from the property as a whole so Sema can
+ /// resolve the type.
+ bool IsTypeLocImplicit = false;
+
+ /// Information about a symbolic default argument, like __FILE__.
+ DefaultArgumentKind defaultArgumentKind = DefaultArgumentKind::None;
+
public:
ParamDecl(bool isLet, SourceLoc argumentNameLoc,
Identifier argumentName, SourceLoc parameterNameLoc,
- Identifier parameterName, Type ty, DeclContext *dc)
- : VarDecl(DeclKind::Param, /*IsState=*/false, isLet, parameterNameLoc,
- parameterName, ty, dc),
- ArgumentName(argumentName), ArgumentNameLoc(argumentNameLoc) { }
+ Identifier parameterName, Type ty, DeclContext *dc);
+ /// Clone constructor, allocates a new ParamDecl identical to the first.
+ /// Intentionally not defined as a typical copy constructor to avoid
+ /// accidental copies.
+ ParamDecl(ParamDecl *PD);
+
/// Retrieve the argument (API) name for this function parameter.
Identifier getArgumentName() const { return ArgumentName; }
@@ -4192,21 +4197,56 @@ class ParamDecl : public VarDecl {
/// The resulting source location will be valid if the argument name
/// was specified separately from the parameter name.
SourceLoc getArgumentNameLoc() const { return ArgumentNameLoc; }
+
+ TypeLoc &getTypeLoc() { return typeLoc; }
+ TypeLoc getTypeLoc() const { return typeLoc; }
- SourceRange getSourceRange() const {
- if (ArgumentNameLoc.isValid() && getNameLoc().isInvalid())
- return ArgumentNameLoc;
- if (ArgumentNameLoc.isInvalid() && getNameLoc().isValid())
- return getNameLoc();
- return SourceRange(ArgumentNameLoc, getNameLoc());
+ bool isTypeLocImplicit() const { return IsTypeLocImplicit; }
+ void setIsTypeLocImplicit(bool val) { IsTypeLocImplicit = val; }
+
+ bool isDefaultArgument() const {
+ return defaultArgumentKind != DefaultArgumentKind::None;
}
-
- Pattern *getParamParentPattern() const {
- return ParentPattern.dyn_cast();
+ DefaultArgumentKind getDefaultArgumentKind() const {
+ return defaultArgumentKind;
}
- void setParamParentPattern(Pattern *Pat) {
- ParentPattern = Pat;
+ void setDefaultArgumentKind(DefaultArgumentKind K) {
+ defaultArgumentKind = K;
}
+
+ void setDefaultValue(ExprHandle *H) {
+ DefaultValueAndIsVariadic.setPointer(H);
+ }
+ ExprHandle *getDefaultValue() const {
+ return DefaultValueAndIsVariadic.getPointer();
+ }
+ /// Whether or not this parameter is varargs.
+ bool isVariadic() const { return DefaultValueAndIsVariadic.getInt(); }
+ void setVariadic(bool value = true) {DefaultValueAndIsVariadic.setInt(value);}
+
+ /// Remove the type of this varargs element designator, without the array
+ /// type wrapping it. A parameter like "Int..." will have formal parameter
+ /// type of "[Int]" and this returns "Int".
+ static Type getVarargBaseTy(Type VarArgT);
+
+ /// Remove the type of this varargs element designator, without the array
+ /// type wrapping it.
+ Type getVarargBaseTy() const {
+ assert(isVariadic());
+ return getVarargBaseTy(getType());
+ }
+
+ SourceRange getSourceRange() const;
+
+ /// Create an implicit 'self' decl for a method in the specified decl context.
+ /// If 'static' is true, then this is self for a static method in the type.
+ ///
+ /// Note that this decl is created, but it is returned with an incorrect
+ /// DeclContext that needs to be set correctly. This is automatically handled
+ /// when a function is created with this as part of its argument list.
+ ///
+ static ParamDecl *createSelf(SourceLoc loc, DeclContext *DC,
+ bool isStatic = false, bool isInOut = false);
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) {
@@ -4254,15 +4294,16 @@ enum class ObjCSubscriptKind {
/// A given type can have multiple subscript declarations, so long as the
/// signatures (indices and element type) are distinct.
///
-class SubscriptDecl : public AbstractStorageDecl {
+class SubscriptDecl : public AbstractStorageDecl, public DeclContext {
SourceLoc ArrowLoc;
- Pattern *Indices;
+ ParameterList *Indices;
TypeLoc ElementTy;
public:
- SubscriptDecl(DeclName Name, SourceLoc SubscriptLoc, Pattern *Indices,
+ SubscriptDecl(DeclName Name, SourceLoc SubscriptLoc, ParameterList *Indices,
SourceLoc ArrowLoc, TypeLoc ElementTy, DeclContext *Parent)
: AbstractStorageDecl(DeclKind::Subscript, Parent, Name, SubscriptLoc),
+ DeclContext(DeclContextKind::SubscriptDecl, Parent),
ArrowLoc(ArrowLoc), Indices(nullptr), ElementTy(ElementTy) {
setIndices(Indices);
}
@@ -4272,9 +4313,9 @@ class SubscriptDecl : public AbstractStorageDecl {
SourceRange getSourceRange() const;
/// \brief Retrieve the indices for this subscript operation.
- Pattern *getIndices() { return Indices; }
- const Pattern *getIndices() const { return Indices; }
- void setIndices(Pattern *p);
+ ParameterList *getIndices() { return Indices; }
+ const ParameterList *getIndices() const { return Indices; }
+ void setIndices(ParameterList *p);
/// Retrieve the type of the indices.
Type getIndicesType() const;
@@ -4303,6 +4344,13 @@ class SubscriptDecl : public AbstractStorageDecl {
static bool classof(const Decl *D) {
return D->getKind() == DeclKind::Subscript;
}
+
+ static bool classof(const DeclContext *DC) {
+ return DC->getContextKind() == DeclContextKind::SubscriptDecl;
+ }
+
+ using DeclContext::operator new;
+ using Decl::getASTContext;
};
/// \brief Base class for function-like declarations.
@@ -4358,31 +4406,41 @@ class AbstractFunctionDecl : public ValueDecl, public DeclContext {
};
GenericParamList *GenericParams;
+ GenericSignature *GenericSig;
CaptureInfo Captures;
AbstractFunctionDecl(DeclKind Kind, DeclContext *Parent, DeclName Name,
- SourceLoc NameLoc, unsigned NumParamPatterns,
+ SourceLoc NameLoc, unsigned NumParameterLists,
GenericParamList *GenericParams)
: ValueDecl(Kind, Parent, Name, NameLoc),
DeclContext(DeclContextKind::AbstractFunctionDecl, Parent),
- Body(nullptr), GenericParams(nullptr) {
+ Body(nullptr), GenericParams(nullptr), GenericSig(nullptr) {
setBodyKind(BodyKind::None);
setGenericParams(GenericParams);
- AbstractFunctionDeclBits.NumParamPatterns = NumParamPatterns;
+ AbstractFunctionDeclBits.NumParameterLists = NumParameterLists;
AbstractFunctionDeclBits.Overridden = false;
// Verify no bitfield truncation.
- assert(AbstractFunctionDeclBits.NumParamPatterns == NumParamPatterns);
+ assert(AbstractFunctionDeclBits.NumParameterLists == NumParameterLists);
}
- MutableArrayRef getBodyParamBuffer();
-
void setBodyKind(BodyKind K) {
AbstractFunctionDeclBits.BodyKind = unsigned(K);
}
void setGenericParams(GenericParamList *GenericParams);
+
+public:
+ void setGenericSignature(GenericSignature *GenericSig) {
+ assert(!this->GenericSig && "already have signature?");
+ this->GenericSig = GenericSig;
+ }
+
+ GenericSignature *getGenericSignature() const {
+ return GenericSig;
+ }
+
public:
// FIXME: Hack that provides names with keyword arguments for accessors.
DeclName getEffectiveFullName() const;
@@ -4418,14 +4476,14 @@ class AbstractFunctionDecl : public ValueDecl, public DeclContext {
}
void setBody(BraceStmt *S, BodyKind NewBodyKind = BodyKind::Parsed) {
assert(getBodyKind() != BodyKind::Skipped &&
- "can not set a body if it was skipped");
+ "cannot set a body if it was skipped");
Body = S;
setBodyKind(NewBodyKind);
}
/// \brief Note that the body was skipped for this function. Function body
- /// can not be attached after this call.
+ /// cannot be attached after this call.
void setBodySkipped(SourceRange bodyRange) {
assert(getBodyKind() == BodyKind::None);
BodyRange = bodyRange;
@@ -4499,8 +4557,8 @@ class AbstractFunctionDecl : public ValueDecl, public DeclContext {
/// Determine whether the name of the ith argument is an API name by default.
bool argumentNameIsAPIByDefault(unsigned i) const;
- unsigned getNumParamPatterns() const {
- return AbstractFunctionDeclBits.NumParamPatterns;
+ unsigned getNumParameterLists() const {
+ return AbstractFunctionDeclBits.NumParameterLists;
}
/// \brief Returns the "natural" number of argument clauses taken by this
@@ -4525,7 +4583,7 @@ class AbstractFunctionDecl : public ValueDecl, public DeclContext {
/// func const(x : Int) -> () -> Int { return { x } } // NAC==1
/// \endcode
unsigned getNaturalArgumentCount() const {
- return getNumParamPatterns();
+ return getNumParameterLists();
}
/// \brief Returns the parameter pattern(s) for the function definition that
@@ -4533,24 +4591,24 @@ class AbstractFunctionDecl : public ValueDecl, public DeclContext {
///
/// The number of "top-level" elements in this pattern will match the number
/// of argument names in the compound name of the function or constructor.
- MutableArrayRef getBodyParamPatterns() {
- return getBodyParamBuffer();
+ MutableArrayRef getParameterLists();
+ ArrayRef getParameterLists() const {
+ auto paramLists =
+ const_cast(this)->getParameterLists();
+ return ArrayRef(paramLists.data(),paramLists.size());
+ }
+ ParameterList *getParameterList(unsigned i) {
+ return getParameterLists()[i];
}
- ArrayRef getBodyParamPatterns() const {
- auto Patterns =
- const_cast(this)->getBodyParamBuffer();
- return ArrayRef(Patterns.data(), Patterns.size());
+ const ParameterList *getParameterList(unsigned i) const {
+ return getParameterLists()[i];
}
/// \brief If this is a method in a type or extension thereof, compute
/// and return the type to be used for the 'self' argument of the type, or an
/// empty Type() if no 'self' argument should exist. This can
/// only be used after name binding has resolved types.
- ///
- /// \param outerGenericParams If non-NULL, and this function is an instance
- /// of a generic type, will be set to the generic parameter list of that
- /// generic type.
- Type computeSelfType(GenericParamList **outerGenericParams = nullptr);
+ Type computeSelfType();
/// \brief If this is a method in a type or extension thereof, compute
/// and return the type to be used for the 'self' argument of the interface
@@ -4566,7 +4624,10 @@ class AbstractFunctionDecl : public ValueDecl, public DeclContext {
///
/// Note that some functions don't have an implicit 'self' decl, for example,
/// free functions. In this case nullptr is returned.
- VarDecl *getImplicitSelfDecl() const;
+ const ParamDecl *getImplicitSelfDecl() const {
+ return const_cast(this)->getImplicitSelfDecl();
+ }
+ ParamDecl *getImplicitSelfDecl();
/// \brief Retrieve the set of parameters to a generic function, or null if
/// this function is not generic.
@@ -4579,6 +4640,10 @@ class AbstractFunctionDecl : public ValueDecl, public DeclContext {
/// Retrieve the declaration that this method overrides, if any.
AbstractFunctionDecl *getOverriddenDecl() const;
+ /// Returns true if a function declaration overrides a given
+ /// method from its direct or indirect superclass.
+ bool isOverridingDecl(const AbstractFunctionDecl *method) const;
+
/// Whether the declaration is later overridden in the module
///
/// Overriddes are resolved during type checking; only query this field after
@@ -4627,7 +4692,7 @@ class FuncDecl : public AbstractFunctionDecl {
SourceLoc StaticLoc; // Location of the 'static' token or invalid.
SourceLoc FuncLoc; // Location of the 'func' token.
SourceLoc ThrowsLoc; // Location of the 'throws' token.
- SourceLoc AccessorKeywordLoc; // Location of the accessor keyword token, e,g. 'set'.
+ SourceLoc AccessorKeywordLoc; // Location of the accessor keyword, e.g. 'set'.
TypeLoc FnRetType;
@@ -4646,23 +4711,24 @@ class FuncDecl : public AbstractFunctionDecl {
/// which property and what kind of accessor.
llvm::PointerIntPair AccessorDecl;
llvm::PointerUnion OverriddenOrDerivedForDecl;
- llvm::PointerIntPair OperatorAndAddressorKind;
+ llvm::PointerIntPair OperatorAndAddressorKind;
FuncDecl(SourceLoc StaticLoc, StaticSpellingKind StaticSpelling,
SourceLoc FuncLoc, DeclName Name,
SourceLoc NameLoc, SourceLoc ThrowsLoc,
SourceLoc AccessorKeywordLoc,
- unsigned NumParamPatterns,
+ unsigned NumParameterLists,
GenericParamList *GenericParams, Type Ty, DeclContext *Parent)
: AbstractFunctionDecl(DeclKind::Func, Parent, Name, NameLoc,
- NumParamPatterns, GenericParams),
+ NumParameterLists, GenericParams),
StaticLoc(StaticLoc), FuncLoc(FuncLoc), ThrowsLoc(ThrowsLoc),
AccessorKeywordLoc(AccessorKeywordLoc),
OverriddenOrDerivedForDecl(),
OperatorAndAddressorKind(nullptr, AddressorKind::NotAddressor) {
FuncDeclBits.IsStatic = StaticLoc.isValid() || getName().isOperator();
FuncDeclBits.StaticSpelling = static_cast(StaticSpelling);
- assert(NumParamPatterns > 0 && "Must have at least an empty tuple arg");
+ assert(NumParameterLists > 0 && "Must have at least an empty tuple arg");
setType(Ty);
FuncDeclBits.Mutating = false;
FuncDeclBits.HasDynamicSelf = false;
@@ -4678,7 +4744,7 @@ class FuncDecl : public AbstractFunctionDecl {
SourceLoc NameLoc, SourceLoc ThrowsLoc,
SourceLoc AccessorKeywordLoc,
GenericParamList *GenericParams, Type Ty,
- unsigned NumParamPatterns,
+ unsigned NumParameterLists,
DeclContext *Parent,
ClangNode ClangN);
@@ -4690,7 +4756,7 @@ class FuncDecl : public AbstractFunctionDecl {
SourceLoc NameLoc, SourceLoc ThrowsLoc,
SourceLoc AccessorKeywordLoc,
GenericParamList *GenericParams, Type Ty,
- unsigned NumParamPatterns,
+ unsigned NumParameterLists,
DeclContext *Parent);
static FuncDecl *create(ASTContext &Context, SourceLoc StaticLoc,
@@ -4698,7 +4764,7 @@ class FuncDecl : public AbstractFunctionDecl {
SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc,
SourceLoc ThrowsLoc, SourceLoc AccessorKeywordLoc,
GenericParamList *GenericParams,
- Type Ty, ArrayRef BodyParams,
+ Type Ty, ArrayRef ParameterLists,
TypeLoc FnRetType, DeclContext *Parent,
ClangNode ClangN = ClangNode());
@@ -4721,6 +4787,25 @@ class FuncDecl : public AbstractFunctionDecl {
FuncDeclBits.Mutating = Mutating;
}
+ /// \brief Returns the parameter lists(s) for the function definition.
+ ///
+ /// The number of "top-level" elements will match the number of argument names
+ /// in the compound name of the function or constructor.
+ MutableArrayRef getParameterLists() {
+ auto Ptr = reinterpret_cast(cast(this) + 1);
+ return { Ptr, getNumParameterLists() };
+ }
+ ArrayRef getParameterLists() const {
+ return AbstractFunctionDecl::getParameterLists();
+ }
+ ParameterList *getParameterList(unsigned i) {
+ return getParameterLists()[i];
+ }
+ const ParameterList *getParameterList(unsigned i) const {
+ return getParameterLists()[i];
+ }
+
+
bool getHaveSearchedForCommonOverloadReturnType() {
return HaveSearchedForCommonOverloadReturnType;
}
@@ -4738,7 +4823,7 @@ class FuncDecl : public AbstractFunctionDecl {
/// attribute. For example a "mutating set" accessor.
bool isExplicitNonMutating() const;
- void setDeserializedSignature(ArrayRef BodyParams,
+ void setDeserializedSignature(ArrayRef ParameterLists,
TypeLoc FnRetType);
SourceLoc getStaticLoc() const { return StaticLoc; }
@@ -4784,22 +4869,24 @@ class FuncDecl : public AbstractFunctionDecl {
}
/// isUnaryOperator - Determine whether this is a unary operator
- /// implementation, in other words, the name of the function is an operator,
- /// and the argument list consists syntactically of a single-element tuple
- /// pattern. This check is syntactic rather than type-based in order to allow
+ /// implementation. This check is a syntactic rather than type-based check,
+ /// which looks at the number of parameters specified, in order to allow
/// for the definition of unary operators on tuples, as in:
- /// func [prefix] + (_:(a:Int, b:Int))
+ ///
+ /// prefix func + (param : (a:Int, b:Int))
+ ///
/// This also allows the unary-operator-ness of a func decl to be determined
/// prior to type checking.
bool isUnaryOperator() const;
/// isBinaryOperator - Determine whether this is a binary operator
- /// implementation, in other words, the name of the function is an operator,
- /// and the argument list consists syntactically of a two-element tuple
- /// pattern. This check is syntactic rather than type-based in order to
- /// distinguish a binary operator from a unary operator on tuples, as in:
- /// func [prefix] + (_:(a:Int, b:Int)) // unary operator +(1,2)
- /// func [infix] + (a:Int, b:Int) // binary operator 1 + 2
+ /// implementation. This check is a syntactic rather than type-based check,
+ /// which looks at the number of parameters specified, in order to allow
+ /// distinguishing a binary operator from a unary operator on tuples, as in:
+ ///
+ /// prefix func + (_:(a:Int, b:Int)) // unary operator +(1,2)
+ /// infix func + (a:Int, b:Int) // binary operator 1 + 2
+ ///
/// This also allows the binary-operator-ness of a func decl to be determined
/// prior to type checking.
bool isBinaryOperator() const;
@@ -4918,10 +5005,6 @@ class FuncDecl : public AbstractFunctionDecl {
FuncDeclBits.ForcedStaticDispatch = flag;
}
- /// Returns true if a function declaration overrides a given
- /// method from its direct or indirect superclass.
- bool isOverridingDecl(const FuncDecl *method) const;
-
static bool classof(const Decl *D) { return D->getKind() == DeclKind::Func; }
static bool classof(const AbstractFunctionDecl *D) {
return classof(static_cast(D));
@@ -5134,8 +5217,6 @@ enum class CtorInitializerKind {
/// }
/// \endcode
class ConstructorDecl : public AbstractFunctionDecl {
- friend class AbstractFunctionDecl;
-
/// The failability of this initializer, which is an OptionalTypeKind.
unsigned Failability : 2;
@@ -5145,7 +5226,7 @@ class ConstructorDecl : public AbstractFunctionDecl {
// Location of the 'throws' token.
SourceLoc ThrowsLoc;
- Pattern *BodyParams[2];
+ ParameterList *ParameterLists[2];
/// The type of the initializing constructor.
Type InitializerType;
@@ -5164,11 +5245,11 @@ class ConstructorDecl : public AbstractFunctionDecl {
public:
ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc,
OptionalTypeKind Failability, SourceLoc FailabilityLoc,
- Pattern *SelfBodyParam, Pattern *BodyParams,
+ ParamDecl *selfParam, ParameterList *BodyParams,
GenericParamList *GenericParams,
SourceLoc throwsLoc, DeclContext *Parent);
- void setBodyParams(Pattern *selfPattern, Pattern *bodyParams);
+ void setParameterLists(ParamDecl *selfParam, ParameterList *bodyParams);
SourceLoc getConstructorLoc() const { return getNameLoc(); }
SourceLoc getStartLoc() const { return getConstructorLoc(); }
@@ -5193,6 +5274,26 @@ class ConstructorDecl : public AbstractFunctionDecl {
Expr *getSuperInitCall() { return CallToSuperInit; }
void setSuperInitCall(Expr *CallExpr) { CallToSuperInit = CallExpr; }
+ MutableArrayRef getParameterLists() {
+ return { ParameterLists, 2 };
+ }
+ ArrayRef getParameterLists() const {
+ return AbstractFunctionDecl::getParameterLists();
+ }
+ ParameterList *getParameterList(unsigned i) {
+ return getParameterLists()[i];
+ }
+ const ParameterList *getParameterList(unsigned i) const {
+ return getParameterLists()[i];
+ }
+
+ /// Returns the normal parameters to the initializer, not including self.
+ ParameterList *getParameters() { return ParameterLists[1]; }
+
+ /// Returns the normal parameters to the initializer, not including self.
+ const ParameterList *getParameters() const { return ParameterLists[1]; }
+
+
/// Specifies the kind of initialization call performed within the body
/// of the constructor, e.g., self.init or super.init.
enum class BodyInitKind {
@@ -5341,14 +5442,22 @@ class ConstructorDecl : public AbstractFunctionDecl {
/// }
/// \endcode
class DestructorDecl : public AbstractFunctionDecl {
- friend class AbstractFunctionDecl;
- Pattern *SelfPattern;
+ ParameterList *SelfParameter;
public:
DestructorDecl(Identifier NameHack, SourceLoc DestructorLoc,
- Pattern *SelfPattern, DeclContext *Parent);
+ ParamDecl *selfDecl, DeclContext *Parent);
- void setSelfPattern(Pattern *selfPattern);
+ void setSelfDecl(ParamDecl *selfDecl);
+
+ MutableArrayRef getParameterLists() {
+ return { &SelfParameter, 1 };
+ }
+ ArrayRef getParameterLists() const {
+ return { &SelfParameter, 1 };
+ }
+
+
SourceLoc getDestructorLoc() const { return getNameLoc(); }
SourceLoc getStartLoc() const { return getDestructorLoc(); }
SourceRange getSourceRange() const;
@@ -5607,25 +5716,17 @@ inline bool AbstractStorageDecl::isStatic() const {
return false;
}
-inline MutableArrayRef AbstractFunctionDecl::getBodyParamBuffer() {
- unsigned NumPatterns = AbstractFunctionDeclBits.NumParamPatterns;
- Pattern **Ptr;
+inline MutableArrayRef
+AbstractFunctionDecl::getParameterLists() {
switch (getKind()) {
default: llvm_unreachable("Unknown AbstractFunctionDecl!");
case DeclKind::Constructor:
- Ptr = cast(this)->BodyParams;
- break;
-
+ return cast(this)->getParameterLists();
case DeclKind::Destructor:
- Ptr = &cast(this)->SelfPattern;
- break;
-
+ return cast(this)->getParameterLists();
case DeclKind::Func:
- // Body patterns are tail allocated.
- Ptr = reinterpret_cast(cast(this) + 1);
- break;
+ return cast(this)->getParameterLists();
}
- return MutableArrayRef(Ptr, NumPatterns);
}
inline DeclIterator &DeclIterator::operator++() {
diff --git a/include/swift/AST/DeclContext.h b/include/swift/AST/DeclContext.h
index c396a90cccf6b..a131ad4cf2219 100644
--- a/include/swift/AST/DeclContext.h
+++ b/include/swift/AST/DeclContext.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -66,6 +66,7 @@ enum class DeclContextKind : uint8_t {
AbstractClosureExpr,
Initializer,
TopLevelCodeDecl,
+ SubscriptDecl,
AbstractFunctionDecl,
SerializedLocal,
Last_LocalDeclContextKind = SerializedLocal,
@@ -245,7 +246,7 @@ class alignas(1 << DeclContextAlignInBits) DeclContext {
/// ClassDecl, otherwise return null.
ClassDecl *isClassOrClassExtensionContext() const;
- /// If this DeclContext is a enum, or an extension on a enum, return the
+ /// If this DeclContext is an enum, or an extension on an enum, return the
/// EnumDecl, otherwise return null.
EnumDecl *isEnumOrEnumExtensionContext() const;
@@ -359,6 +360,15 @@ class alignas(1 << DeclContextAlignInBits) DeclContext {
/// Determine whether the innermost context is generic.
bool isInnermostContextGeneric() const;
+
+ /// Determine whether the innermost context is either a generic type context,
+ /// or a concrete type nested inside a generic type context.
+ bool isGenericTypeContext() const;
+
+ /// Determine the maximum depth of the current generic type context's generic
+ /// parameters. If the current context is not a generic type context, returns
+ /// the maximum depth of any generic parameter in this context.
+ unsigned getGenericTypeContextDepth() const;
/// Returns true if lookups within this context could affect downstream files.
///
diff --git a/include/swift/AST/DeclNodes.def b/include/swift/AST/DeclNodes.def
index 9f349abd502ac..d1cbbf47ccb73 100644
--- a/include/swift/AST/DeclNodes.def
+++ b/include/swift/AST/DeclNodes.def
@@ -1,8 +1,8 @@
-//===-- DeclNodes.def - Swift Declaration AST Metaprogramming -*- C++ -*-===//
+//===--- DeclNodes.def - Swift Declaration AST Metaprogramming --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DefaultArgumentKind.h b/include/swift/AST/DefaultArgumentKind.h
index a53a88d3e346f..14ef3124b60f5 100644
--- a/include/swift/AST/DefaultArgumentKind.h
+++ b/include/swift/AST/DefaultArgumentKind.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -17,10 +17,16 @@
#ifndef SWIFT_DEFAULTARGUMENTKIND_H
#define SWIFT_DEFAULTARGUMENTKIND_H
+namespace llvm {
+class StringRef;
+}
+
namespace swift {
+class Expr;
+
/// Describes the kind of default argument a tuple pattern element has.
-enum class DefaultArgumentKind {
+enum class DefaultArgumentKind : unsigned {
/// No default argument.
None,
/// A normal default argument.
@@ -38,8 +44,22 @@ enum class DefaultArgumentKind {
Function,
/// The __DSO_HANDLE__ default argument, which is expanded at the call site.
DSOHandle,
+ /// The "nil" literal.
+ Nil,
+ /// An empty array literal.
+ EmptyArray,
+ /// An empty dictionary literal.
+ EmptyDictionary,
};
+/// Retrieve the spelling of this default argument in source code, or
+/// an empty string if it has none.
+llvm::StringRef getDefaultArgumentSpelling(DefaultArgumentKind kind);
+
+/// Infer a default argument kind from an expression, if the
+/// expression is the canonical way to spell that default argument.
+DefaultArgumentKind inferDefaultArgumentKind(Expr *expr);
+
} // end namespace swift
#endif // LLVM_SWIFT_DEFAULTARGUMENTKIND_H
diff --git a/include/swift/AST/DiagnosticEngine.h b/include/swift/AST/DiagnosticEngine.h
index 1331f8bdb1d98..0331c50cf4c0d 100644
--- a/include/swift/AST/DiagnosticEngine.h
+++ b/include/swift/AST/DiagnosticEngine.h
@@ -1,8 +1,8 @@
-//===- DiagnosticEngine.h - Diagnostic Display Engine -----------*- C++ -*-===//
+//===--- DiagnosticEngine.h - Diagnostic Display Engine ---------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -18,18 +18,8 @@
#ifndef SWIFT_BASIC_DIAGNOSTICENGINE_H
#define SWIFT_BASIC_DIAGNOSTICENGINE_H
-#include "swift/Basic/LLVM.h"
-#include "swift/AST/Identifier.h"
-#include "swift/AST/Type.h"
#include "swift/AST/TypeLoc.h"
#include "swift/Basic/DiagnosticConsumer.h"
-#include "swift/Basic/SourceLoc.h"
-#include "clang/Basic/VersionTuple.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/StringRef.h"
-#include
-#include
namespace swift {
class Decl;
diff --git a/include/swift/AST/DiagnosticsAll.def b/include/swift/AST/DiagnosticsAll.def
index d808b5ea6b84c..000f0839cc924 100644
--- a/include/swift/AST/DiagnosticsAll.def
+++ b/include/swift/AST/DiagnosticsAll.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsAll.def - Diagnostics Text Index --------------*- C++ -*-===//
+//===--- DiagnosticsAll.def - Diagnostics Text Index ------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsClangImporter.def b/include/swift/AST/DiagnosticsClangImporter.def
index 9371fc5ed01b1..3c88a837c5319 100644
--- a/include/swift/AST/DiagnosticsClangImporter.def
+++ b/include/swift/AST/DiagnosticsClangImporter.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsClangImporter.def - Diagnostics Text ----------*- C++ -*-===//
+//===--- DiagnosticsClangImporter.def - Diagnostics Text --------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsClangImporter.h b/include/swift/AST/DiagnosticsClangImporter.h
index 754beefa0ba55..82d10334edcf4 100644
--- a/include/swift/AST/DiagnosticsClangImporter.h
+++ b/include/swift/AST/DiagnosticsClangImporter.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsClangImporter.h - Diagnostic Definitions ------*- C++ -*-===//
+//===--- DiagnosticsClangImporter.h - Diagnostic Definitions ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsCommon.def b/include/swift/AST/DiagnosticsCommon.def
index 7004c58209a8a..11ca741a8a38a 100644
--- a/include/swift/AST/DiagnosticsCommon.def
+++ b/include/swift/AST/DiagnosticsCommon.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsCommon.def - Diagnostics Text -----------------*- C++ -*-===//
+//===--- DiagnosticsCommon.def - Diagnostics Text ---------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -73,12 +73,6 @@ ERROR(class_var_not_in_class,common,none,
// FIXME: Used by both the parser and the type-checker.
ERROR(func_decl_without_brace,decl_parsing,PointsToFirstBadToken,
"expected '{' in body of function declaration", ())
-ERROR(unsupported_fixed_length_array,type_parsing,none,
- "fixed-length arrays are not yet supported", ())
-
-ERROR(new_array_syntax,type_parsing,none,
- "array types are now written with the brackets around the element type",
- ())
NOTE(convert_let_to_var,sema,none,
"change 'let' to 'var' to make it mutable", ())
diff --git a/include/swift/AST/DiagnosticsCommon.h b/include/swift/AST/DiagnosticsCommon.h
index cec28f3c3d76b..86f5b85a99d66 100644
--- a/include/swift/AST/DiagnosticsCommon.h
+++ b/include/swift/AST/DiagnosticsCommon.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsCommon.h - Shared Diagnostic Definitions ------*- C++ -*-===//
+//===--- DiagnosticsCommon.h - Shared Diagnostic Definitions ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsDriver.def b/include/swift/AST/DiagnosticsDriver.def
index 15cc058c5c683..a99d3de1c5bfd 100644
--- a/include/swift/AST/DiagnosticsDriver.def
+++ b/include/swift/AST/DiagnosticsDriver.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsDriver.def - Diagnostics Text -----------------*- C++ -*-===//
+//===--- DiagnosticsDriver.def - Diagnostics Text ---------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -77,7 +77,7 @@ ERROR(error_unknown_target,driver,none,
"unknown target '%0'", (StringRef))
ERROR(error_framework_bridging_header,driver,none,
- "using bridging headers with framework targets is unsupported", ())
+ "using bridging headers with framework targets is unsupported", ())
ERROR(error_i_mode,driver,none,
"the flag '-i' is no longer required and has been removed; "
diff --git a/include/swift/AST/DiagnosticsDriver.h b/include/swift/AST/DiagnosticsDriver.h
index 133eb7c337435..1c9c76dbdb627 100644
--- a/include/swift/AST/DiagnosticsDriver.h
+++ b/include/swift/AST/DiagnosticsDriver.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsDriver.h - Diagnostic Definitions -------------*- C++ -*-===//
+//===--- DiagnosticsDriver.h - Diagnostic Definitions -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsFrontend.def b/include/swift/AST/DiagnosticsFrontend.def
index 683c66bdb4b60..aa8ad25c5ea9b 100644
--- a/include/swift/AST/DiagnosticsFrontend.def
+++ b/include/swift/AST/DiagnosticsFrontend.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsFrontend.def - Diagnostics Text ---------------*- C++ -*-===//
+//===--- DiagnosticsFrontend.def - Diagnostics Text -------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -58,8 +58,6 @@ ERROR(cannot_open_serialized_file,frontend,none,
"cannot open file '%0' for diagnostics emission (%1)", (StringRef, StringRef))
ERROR(error_open_input_file,frontend,none,
"error opening input file '%0' (%1)", (StringRef, StringRef))
-ERROR(error_clang_importer_not_linked_in,frontend,none,
- "clang importer not available", ())
ERROR(error_clang_importer_create_fail,frontend,none,
"clang importer creation failed", ())
ERROR(error_missing_arg_value,frontend,none,
diff --git a/include/swift/AST/DiagnosticsFrontend.h b/include/swift/AST/DiagnosticsFrontend.h
index 9fc1b3d98fdef..07cce746a8d1f 100644
--- a/include/swift/AST/DiagnosticsFrontend.h
+++ b/include/swift/AST/DiagnosticsFrontend.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsFrontend.h - Diagnostic Definitions -----------*- C++ -*-===//
+//===--- DiagnosticsFrontend.h - Diagnostic Definitions ---------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsIRGen.def b/include/swift/AST/DiagnosticsIRGen.def
index 8eb159a901d92..ef300c38a6bb7 100644
--- a/include/swift/AST/DiagnosticsIRGen.def
+++ b/include/swift/AST/DiagnosticsIRGen.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsIRGen.def - Diagnostics Text ------------------*- C++ -*-===//
+//===--- DiagnosticsIRGen.def - Diagnostics Text ----------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsIRGen.h b/include/swift/AST/DiagnosticsIRGen.h
index 13a46d7be2343..e97170973f5b2 100644
--- a/include/swift/AST/DiagnosticsIRGen.h
+++ b/include/swift/AST/DiagnosticsIRGen.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsIRGen.h - Diagnostic Definitions --------------*- C++ -*-===//
+//===--- DiagnosticsIRGen.h - Diagnostic Definitions ------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsParse.def b/include/swift/AST/DiagnosticsParse.def
index 86eab14e3d55d..f2429e715838d 100644
--- a/include/swift/AST/DiagnosticsParse.def
+++ b/include/swift/AST/DiagnosticsParse.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsParse.def - Diagnostics Text ------------------*- C++ -*-===//
+//===--- DiagnosticsParse.def - Diagnostics Text ----------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -71,6 +71,10 @@ ERROR(extra_tokens_line_directive,parsing,none,
ERROR(line_directive_line_zero,parsing,none,
"the line number needs to be greater than zero", ())
+WARNING(escaped_parameter_name,parsing,none,
+ "keyword '%0' does not need to be escaped in argument list",
+ (StringRef))
+
//------------------------------------------------------------------------------
// Lexer diagnostics
//------------------------------------------------------------------------------
@@ -126,12 +130,14 @@ ERROR(lex_expected_binary_exponent_in_hex_float_literal,lexing,none,
"hexadecimal floating point literal must end with an exponent", ())
ERROR(lex_unexpected_block_comment_end,lexing,none,
"unexpected end of block comment", ())
-ERROR(lex_unary_equal_is_reserved,lexing,none,
- "%select{prefix|postfix}0 '=' is reserved", (unsigned))
+ERROR(lex_unary_equal,lexing,none,
+ "'=' must have consistent whitespace on both sides", ())
ERROR(lex_unary_postfix_dot_is_reserved,lexing,none,
"postfix '.' is reserved", ())
ERROR(lex_editor_placeholder,lexing,none,
"editor placeholder in source file", ())
+WARNING(lex_editor_placeholder_in_playground,lexing,none,
+ "editor placeholder in source file", ())
//------------------------------------------------------------------------------
// Declaration parsing diagnostics
@@ -173,25 +179,12 @@ ERROR(decl_inner_scope,decl_parsing,none,
ERROR(decl_not_static,decl_parsing,none,
"declaration cannot be marked %0", (StaticSpellingKind))
-ERROR(ownership_not_attribute,decl_parsing,none,
- "'@%0' is not an attribute, use the '%0' keyword instead",
- (StringRef))
-
ERROR(cskeyword_not_attribute,decl_parsing,none,
"'%0' is a declaration modifier, not an attribute", (StringRef))
-ERROR(convenience_invalid,sema_tcd,none,
- "'convenience' is not valid on this declaration", ())
-
ERROR(decl_already_static,decl_parsing,none,
"%0 specified twice", (StaticSpellingKind))
-ERROR(autoclosure_is_decl_attribute,attribute_parsing,none,
- "@autoclosure is now an attribute of the parameter "
- "declaration, not its type", ())
-ERROR(autoclosure_not_on_enums,attribute_parsing,none,
- "@autoclosure is only allowed on parameters, not on enum cases", ())
-
ERROR(enum_case_dot_prefix,decl_parsing,none,
"extraneous '.' in enum 'case' declaration", ())
@@ -286,11 +279,6 @@ ERROR(static_func_decl_global_scope,decl_parsing,none,
(StaticSpellingKind))
ERROR(func_decl_expected_arrow,decl_parsing,none,
"expected '->' after function parameter tuple", ())
-ERROR(func_static_not_allowed,decl_parsing,none,
- "static functions are not allowed in this context, "
- "use 'class' to declare a class method", ())
-ERROR(func_conversion,decl_parsing,none,
- "'__conversion' functions are no longer allowed", ())
// Enum
ERROR(expected_lbrace_enum,decl_parsing,PointsToFirstBadToken,
@@ -335,7 +323,11 @@ ERROR(expected_arrow_subscript,decl_parsing,PointsToFirstBadToken,
ERROR(expected_type_subscript,type_parsing,PointsToFirstBadToken,
"expected subscripting element type", ())
ERROR(expected_lbrace_subscript,decl_parsing,PointsToFirstBadToken,
- "expected '{' for subscripting", ())
+ "expected '{' in subscript to specify getter and setter implementation",
+ ())
+ERROR(expected_lbrace_subscript_protocol,decl_parsing,PointsToFirstBadToken,
+ "subscript in protocol must have explicit { get } or "
+ "{ get set } specifier", ())
ERROR(subscript_without_get,decl_parsing,none,
"subscript declarations must have a getter", ())
ERROR(subscript_static,decl_parsing,none,
@@ -362,6 +354,9 @@ ERROR(operator_decl_inner_scope,decl_parsing,none,
"'operator' may only be declared at file scope", ())
ERROR(expected_operator_name_after_operator,decl_parsing,PointsToFirstBadToken,
"expected operator name in operator declaration", ())
+ERROR(identifier_when_expecting_operator,decl_parsing,PointsToFirstBadToken,
+ "%0 is considered to be an identifier, not an operator", (Identifier))
+
ERROR(operator_decl_no_fixity,decl_parsing,none,
"operator must be declared as 'prefix', 'postfix', or 'infix'", ())
ERROR(expected_lbrace_after_operator,decl_parsing,PointsToFirstBadToken,
@@ -410,8 +405,6 @@ ERROR(expected_sil_constant, decl_parsing,none,
"expected constant in SIL code", ())
ERROR(referenced_value_no_accessor, decl_parsing,none,
"referenced declaration has no %select{getter|setter}0", (unsigned))
-ERROR(sil_local_storage_non_address, decl_parsing,none,
- "can only work with the address of local storage", ())
// SIL Values
ERROR(sil_value_redefinition, decl_parsing,none,
@@ -453,6 +446,9 @@ ERROR(sil_invalid_instr_operands,decl_parsing,none,
"invalid instruction operands", ())
ERROR(sil_operand_not_address,decl_parsing,none,
"%0 operand of '%1' must have address type", (StringRef, StringRef))
+ERROR(sil_operand_not_unowned_address,decl_parsing,none,
+ "%0 operand of '%1' must have address of [unowned] type",
+ (StringRef, StringRef))
ERROR(sil_operand_not_weak_address,decl_parsing,none,
"%0 operand of '%1' must have address of [weak] type",
(StringRef, StringRef))
@@ -460,8 +456,6 @@ ERROR(sil_integer_literal_not_integer_type,decl_parsing,none,
"integer_literal instruction requires a 'Builtin.Int' type", ())
ERROR(sil_float_literal_not_float_type,decl_parsing,none,
"float_literal instruction requires a 'Builtin.FP' type", ())
-ERROR(sil_apply_archetype_not_found,decl_parsing,none,
- "archetype name not found in polymorphic function type of apply instruction", ())
ERROR(sil_substitutions_on_non_polymorphic_type,decl_parsing,none,
"apply of non-polymorphic function cannot have substitutions", ())
ERROR(sil_witness_method_not_protocol,decl_parsing,none,
@@ -480,6 +474,8 @@ ERROR(sil_missing_substitutions,decl_parsing,none,
"missing substitutions", ())
ERROR(sil_too_many_substitutions,decl_parsing,none,
"too many substitutions", ())
+ERROR(sil_dbg_unknown_key,decl_parsing,none,
+ "unknown key '%0' in debug variable declaration", (StringRef))
// SIL Basic Blocks
ERROR(expected_sil_block_name, decl_parsing,none,
@@ -494,8 +490,6 @@ ERROR(sil_basicblock_arg_rparen, decl_parsing,none,
"expected ')' in basic block argument list", ())
// SIL Functions
-ERROR(expected_sil_linkage_or_function, decl_parsing,none,
- "expected SIL linkage type or function name", ())
ERROR(expected_sil_function_name, decl_parsing,none,
"expected SIL function name", ())
ERROR(expected_sil_rbrace, decl_parsing,none,
@@ -580,8 +574,6 @@ ERROR(expected_type_function_result,type_parsing,PointsToFirstBadToken,
"expected type for function result", ())
ERROR(generic_non_function,type_parsing,PointsToFirstBadToken,
"only syntactic function types can be generic", ())
-ERROR(throwing_non_function,type_parsing,PointsToFirstBadToken,
- "only function types may throw", ())
ERROR(rethrowing_function_type,type_parsing,PointsToFirstBadToken,
"only function declarations may be marked 'rethrows'", ())
ERROR(throws_after_function_result,type_parsing,none,
@@ -598,8 +590,9 @@ ERROR(nonliteral_enum_case_raw_value,type_parsing,PointsToFirstBadToken,
"raw value for enum case must be a literal", ())
// Collection Types
-ERROR(expected_expr_array_type,expr_parsing,PointsToFirstBadToken,
- "expected expression for size of array type", ())
+ERROR(new_array_syntax,type_parsing,none,
+ "array types are now written with the brackets around the element type",
+ ())
ERROR(expected_rbracket_array_type,type_parsing,PointsToFirstBadToken,
"expected ']' in array type", ())
ERROR(expected_element_type,type_parsing,PointsToFirstBadToken,
@@ -641,10 +634,8 @@ ERROR(untyped_pattern_ellipsis,pattern_parsing,none,
"'...' cannot be applied to a subpattern which is not explicitly typed", ())
ERROR(non_func_decl_pattern_init,pattern_parsing,none,
"default argument is only permitted for a non-curried function parameter",())
-ERROR(var_not_allowed_in_pattern,pattern_parsing, none,
- "Use of 'var' binding here is not allowed", ())
-WARNING(let_on_param_is_redundant,pattern_parsing, none,
- "'let' keyword is unnecessary; function parameters are immutable by default", (unsigned))
+WARNING(var_not_allowed_in_pattern,pattern_parsing, none,
+ "Use of '%select{var|let}0' binding here is deprecated and will be removed in a future version of Swift", (unsigned))
ERROR(var_pattern_in_var,pattern_parsing,none,
"'%select{var|let}0' cannot appear nested inside another 'var' or "
"'let' pattern", (unsigned))
@@ -662,26 +653,13 @@ ERROR(multiple_parameter_ellipsis,decl_parsing,none,
"only a single variadic parameter '...' is permitted", ())
ERROR(parameter_vararg_default,decl_parsing,none,
"variadic parameter cannot have a default value", ())
-ERROR(parameter_backtick_missing_name,decl_parsing,PointsToFirstBadToken,
- "expected parameter name after '#'", ())
-ERROR(parameter_backtick_empty_name,decl_parsing,none,
- "expected non-empty parameter name after '#'", ())
ERROR(parameter_inout_var_let,decl_parsing,none,
"parameter may not have multiple 'inout', 'var', or 'let' specifiers",
())
-WARNING(parameter_backtick_two_names,decl_parsing,none,
- "extraneous '#' in parameter; keyword argument and parameter name "
- "already specified separately", ())
WARNING(parameter_extraneous_double_up,decl_parsing,none,
"extraneous duplicate parameter name; %0 already has an argument "
"label", (Identifier))
-ERROR(parameter_extraneous_pound,decl_parsing,none,
- "'#' has been removed from Swift; %0 already has an argument label",
- (Identifier))
-ERROR(parameter_pound_double_up,decl_parsing,none,
- "'#' has been removed from Swift; double up '%0 %0' to make the "
- "argument label the same as the parameter name", (StringRef))
WARNING(parameter_extraneous_empty_name,decl_parsing,none,
"extraneous '_' in parameter: %0 has no keyword argument name",
(Identifier))
@@ -754,8 +732,6 @@ ERROR(expected_expr_conditional_letbinding,stmt_parsing,none,
ERROR(expected_expr_conditional_letbinding_bool_conditions,stmt_parsing,none,
"expected 'let' or 'var' in conditional; "
"use '&&' to join boolean conditions", ())
-ERROR(expected_simple_identifier_pattern,stmt_parsing,none,
- "expected simple identifier pattern in optional binding condition", ())
ERROR(expected_expr_conditional_var,stmt_parsing,PointsToFirstBadToken,
"expected expression after '=' in conditional binding", ())
ERROR(expected_expr_conditional_where,stmt_parsing,PointsToFirstBadToken,
@@ -809,8 +785,6 @@ ERROR(expected_while_after_repeat_body,stmt_parsing,PointsToFirstBadToken,
"expected 'while' after body of 'repeat' statement", ())
ERROR(expected_expr_repeat_while,stmt_parsing,PointsToFirstBadToken,
"expected expression in 'repeat-while' condition", ())
-ERROR(missing_condition_after_repeat_while,stmt_parsing,none,
- "missing condition in a 'repeat-while' statement", ())
ERROR(do_while_now_repeat_while,stmt_parsing,none,
"'do-while' statement is not allowed; use 'repeat-while' instead", ())
@@ -968,8 +942,6 @@ ERROR(availability_query_outside_if_stmt_guard, expr_parsing, none,
ERROR(expected_identifier_after_dot_expr,expr_parsing,none,
"expected identifier after '.' expression", ())
-ERROR(expected_field_spec_name_tuple_expr,expr_parsing,none,
- "expected field specifier name in tuple expression", ())
ERROR(expected_identifier_after_super_dot_expr,expr_parsing,
PointsToFirstBadToken,
@@ -1105,14 +1077,6 @@ ERROR(attr_availability_renamed, attribute_parsing, none,
ERROR(attr_autoclosure_expected_r_paren,attribute_parsing,PointsToFirstBadToken,
"expected ')' in @autoclosure", ())
-// cc
-ERROR(cc_attribute_expected_lparen,attribute_parsing,none,
- "expected '(' after 'cc' attribute", ())
-ERROR(cc_attribute_expected_name,attribute_parsing,none,
- "expected calling convention name identifier in 'cc' attribute", ())
-ERROR(cc_attribute_expected_rparen,attribute_parsing,none,
- "expected ')' after calling convention name for 'cc' attribute", ())
-
// convention
ERROR(convention_attribute_expected_lparen,attribute_parsing,none,
"expected '(' after 'convention' attribute", ())
@@ -1169,6 +1133,20 @@ WARNING(attr_warn_unused_result_unknown_parameter,attribute_parsing,none,
ERROR(attr_warn_unused_result_expected_rparen,attribute_parsing,none,
"expected ')' after 'warn_unused_result' attribute", ())
+// _migration_id
+WARNING(attr_migration_id_expected_name,attribute_parsing,none,
+ "expected parameter 'pattern'", ())
+WARNING(attr_migration_id_unknown_parameter,attribute_parsing,none,
+ "unknown parameter '%0' in '_migration_id' attribute", (StringRef))
+ERROR(attr_migration_id_expected_eq,attribute_parsing,none,
+ "expected '=' following '%0' parameter", (StringRef))
+ERROR(attr_migration_id_expected_string,attribute_parsing,none,
+ "expected a string following '=' for '%0' parameter", (StringRef))
+WARNING(attr_migration_id_duplicate_parameter,attribute_parsing,none,
+ "duplicate '%0' parameter; previous value will be ignored", (StringRef))
+ERROR(attr_migration_id_expected_rparen,attribute_parsing,none,
+ "expected ')' after '_migration_id' attribute", ())
+
//------------------------------------------------------------------------------
// Generics parsing diagnostics
//------------------------------------------------------------------------------
@@ -1233,9 +1211,6 @@ WARNING(unknown_build_config,parsing,none,
//------------------------------------------------------------------------------
// Availability query parsing diagnostics
//------------------------------------------------------------------------------
-ERROR(avail_query_not_enabled,parsing,Fatal,
- "experimental availability checking not enabled", ())
-
ERROR(avail_query_expected_condition,parsing,PointsToFirstBadToken,
"expected availability condition", ())
ERROR(avail_query_expected_platform_name,parsing,PointsToFirstBadToken,
diff --git a/include/swift/AST/DiagnosticsParse.h b/include/swift/AST/DiagnosticsParse.h
index e50840cfb8fd1..509b2ebd4c15e 100644
--- a/include/swift/AST/DiagnosticsParse.h
+++ b/include/swift/AST/DiagnosticsParse.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsParse.h - Diagnostic Definitions --------------*- C++ -*-===//
+//===--- DiagnosticsParse.h - Diagnostic Definitions ------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsSIL.def b/include/swift/AST/DiagnosticsSIL.def
index c795e28c20691..13aa70809c263 100644
--- a/include/swift/AST/DiagnosticsSIL.def
+++ b/include/swift/AST/DiagnosticsSIL.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsSILAnalysis.def - Diagnostics Text ------------*- C++ -*-===//
+//===--- DiagnosticsSIL.def - Diagnostics Text ------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -97,7 +97,7 @@ ERROR(variable_used_before_initialized,sil_analysis,none,
ERROR(variable_inout_before_initialized,sil_analysis,none,
"%select{variable|constant}1 '%0' passed by reference before being"
" initialized", (StringRef, bool))
-ERROR(variable_escape_before_initialized,sil_analysis,none,
+ERROR(variable_closure_use_uninit,sil_analysis,none,
"%select{variable|constant}1 '%0' captured by a closure before being"
" initialized", (StringRef, bool))
@@ -145,7 +145,7 @@ ERROR(return_from_init_without_initing_stored_properties,sil_analysis,none,
"return from initializer without initializing all"
" stored properties", ())
-ERROR(global_variable_function_use_uninit,sil_analysis,none,
+ERROR(variable_function_use_uninit,sil_analysis,none,
"%select{variable|constant}1 '%0' used by function definition before"
" being initialized",
(StringRef, bool))
diff --git a/include/swift/AST/DiagnosticsSIL.h b/include/swift/AST/DiagnosticsSIL.h
index 7c9e24d2c11a7..5bf0c81926f96 100644
--- a/include/swift/AST/DiagnosticsSIL.h
+++ b/include/swift/AST/DiagnosticsSIL.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsSIL.h - Diagnostic Definitions ----------------*- C++ -*-===//
+//===--- DiagnosticsSIL.h - Diagnostic Definitions --------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index 9c32d337738db..2dbb3c183cf71 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -1,8 +1,8 @@
-//===- DiagnosticsSema.def - Diagnostics Text -------------------*- C++ -*-===//
+//===--- DiagnosticsSema.def - Diagnostics Text -----------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -397,9 +397,6 @@ ERROR(serialization_target_too_new_repl,sema,none,
"module file's minimum deployment target is %0 v%1.%2%select{|.%3}3: %4",
(StringRef, unsigned, unsigned, unsigned, StringRef))
-ERROR(unknown_name_in_type,sema_nb,none,
- "use of unknown scope %0 in type reference", (Identifier))
-
ERROR(invalid_redecl,sema_nb,none,"invalid redeclaration of %0", (DeclName))
NOTE(invalid_redecl_prev,sema_nb,none,
"%0 previously declared here", (DeclName))
@@ -420,16 +417,30 @@ ERROR(ambiguous_module_type,sema_nb,none,
ERROR(use_nonmatching_operator,sema_nb,none,
"%0 is not a %select{binary|prefix unary|postfix unary}1 operator",
(Identifier, unsigned))
+
+ERROR(unspaced_binary_operator_fixit,sema_nb,none,
+ "missing whitespace between %0 and %1 operators",
+ (Identifier, Identifier, bool))
+ERROR(unspaced_binary_operator,sema_nb,none,
+ "ambiguous missing whitespace between unary and binary operators", ())
+NOTE(unspaced_binary_operators_candidate,sema_nb,none,
+ "could be %select{binary|postfix}2 %0 and %select{prefix|binary}2 %1",
+ (Identifier, Identifier, bool))
+ERROR(unspaced_unary_operator,sema_nb,none,
+ "unary operators may not be juxtaposed; parenthesize inner expression",
+ ())
+
+
ERROR(use_unresolved_identifier,sema_nb,none,
- "use of unresolved identifier %0", (Identifier))
+ "use of unresolved %select{identifier|operator}1 %0", (Identifier, bool))
ERROR(use_undeclared_type,sema_nb,none,
"use of undeclared type %0", (Identifier))
ERROR(use_undeclared_type_did_you_mean,sema_nb,none,
-"use of undeclared type %0; did you mean to use '%1'?", (Identifier, StringRef))
+ "use of undeclared type %0; did you mean to use '%1'?", (Identifier, StringRef))
NOTE(note_remapped_type,sema_nb,none,
- "did you mean to use '%0'?", (StringRef))
+ "did you mean to use '%0'?", (StringRef))
ERROR(identifier_init_failure,sema_nb,none,
- "could not infer type for %0", (Identifier))
+ "could not infer type for %0", (Identifier))
ERROR(pattern_used_in_type,sema_nb,none,
"%0 used within its own type", (Identifier))
NOTE(note_module_as_type,sema_nb,none,
@@ -437,6 +448,11 @@ NOTE(note_module_as_type,sema_nb,none,
ERROR(use_unknown_object_literal,sema_nb,none,
"use of unknown object literal name %0", (Identifier))
+ERROR(object_literal_default_type_missing,sema_nb,none,
+ "could not infer type of %0 literal", (StringRef))
+NOTE(object_literal_resolve_import,sema_nb,none,
+ "import %0 to use '%1' as the default %2 literal type",
+ (StringRef, StringRef, StringRef))
ERROR(use_non_type_value,sema_nb,none,
"%0 is not a type", (Identifier))
@@ -545,9 +561,6 @@ ERROR(downcast_same_type,sema_tcc,none,
(Type, Type, StringRef))
WARNING(downcast_to_unrelated,sema_tcc,none,
"cast from %0 to unrelated type %1 always fails", (Type, Type))
-ERROR(downcast_from_existential_to_unrelated,sema_tcc,none,
- "cannot cast from protocol type %0 to non-conforming type %1",
- (Type, Type))
ERROR(downcast_to_more_optional,sema_tcc,none,
"cannot downcast from %0 to a more optional type %1",
(Type, Type))
@@ -618,6 +631,10 @@ ERROR(argument_out_of_order,sema_tcc,none,
ERROR(argument_out_of_order_named_unnamed,sema_tcc,none,
"argument %0 must precede unnamed parameter #%1", (Identifier, unsigned))
+ERROR(instance_member_use_on_type,sema_tcc,none,
+ "use of instance member %1 on type %0; "
+ "did you mean to use a value of type %0 instead?", (Type, Identifier))
+
ERROR(missing_argument_named,sema_tcc,none,
"missing argument for parameter %0 in call", (Identifier))
ERROR(missing_argument_positional,sema_tcc,none,
@@ -638,6 +655,12 @@ ERROR(unbound_generic_parameter,sema_tcc,none,
ERROR(cannot_bind_generic_parameter_to_type,sema_tcc,none,
"cannot bind generic parameter to type %0",
(Type))
+ERROR(string_index_not_integer,sema_tcc,none,
+ "String may not be indexed with %0, it has variable size elements",
+ (Type))
+NOTE(string_index_not_integer_note,sema_tcc,none,
+ "consider using an existing high level algorithm, "
+ "str.startIndex.advancedBy(n), or a projection like str.utf8", ())
ERROR(invalid_c_function_pointer_conversion_expr,sema_tcc,none,
"a C function pointer can only be formed from a reference to a 'func' or "
@@ -828,6 +851,8 @@ NOTE(note_no_in_class_init_3plus,sema_tcd,none,
(Identifier, Identifier, Identifier, bool))
ERROR(missing_unimplemented_init_runtime,sema_tcd,none,
"standard library error: missing _unimplemented_initializer", ())
+ERROR(missing_undefined_runtime,sema_tcd,none,
+ "standard library error: missing _undefined", ())
WARNING(unsupported_synthesize_init_variadic,sema_tcd,none,
"synthesizing a variadic inherited initializer for subclass %0 is "
"unsupported",
@@ -1052,7 +1077,7 @@ NOTE(ambiguous_witnesses_wrong_name,sema_tcd,none,
"subscript operators}0 with type %2", (RequirementKind, DeclName, Type))
NOTE(no_witnesses_type,sema_tcd,none,
"protocol requires nested type %0", (Identifier))
-NOTE(default_assocated_type_req_fail,sema_tcd,none,
+NOTE(default_associated_type_req_fail,sema_tcd,none,
"default type %0 for associated type %1 (from protocol %2) "
"does not conform to %3",
(Type, DeclName, Type, Type))
@@ -1210,9 +1235,6 @@ ERROR(override_multiple_decls_base,sema_tcd,none,
ERROR(override_multiple_decls_arg_mismatch,sema_tcd,none,
"declaration %0 has different argument names from any potential "
"overrides", (DeclName))
-ERROR(override_multiple_decls_derived,sema_tcd,none,
- "declaration cannot be overridden by more than one subclass "
- "declaration", ())
NOTE(overridden_near_match_here,sema_tcd,none,
"potential overridden %select{method|initializer}0 %1 here",
(bool, DeclName))
@@ -1324,10 +1346,6 @@ ERROR(override_mutable_covariant_subscript,sema_tcd,none,
(Type, Type))
ERROR(decl_already_final,sema_tcd,none,
"static declarations are already final", ())
-ERROR(decl_no_default_init,sema_tcd,none,
- "cannot default-initialize variable of type %0", (Type))
-ERROR(decl_no_default_init_ivar_hole,sema_tcd,none,
- "cannot use initial value when one of the variables is '_'", ())
NOTE(decl_init_here,sema_tcd,none,
"initial value is here", ())
@@ -1473,8 +1491,6 @@ ERROR(override_rethrows_with_non_rethrows,sema_tcd,none,
ERROR(rethrows_without_throwing_parameter,sema_tcd,none,
"'rethrows' function must take a throwing function argument", ())
-ERROR(inconsistent_attribute_override,sema_tcd,none,
- "@%0 must be consistent between a method and its override", (StringRef))
ERROR(autoclosure_function_type,attribute_parsing,none,
"@autoclosure may only be applied to values of function type",
())
@@ -1494,7 +1510,7 @@ ERROR(noescape_conflicts_escaping_autoclosure,attribute_parsing,none,
ERROR(attr_NSManaged_not_instance_member,sema_tcd,none,
"@NSManaged only allowed on an instance property or method", ())
ERROR(attr_NSManaged_not_stored,sema_tcd,none,
- "@NSManaged not allowed on %select{computed|observing|adressed}0 "
+ "@NSManaged not allowed on %select{computed|observing|addressed}0 "
"properties", (unsigned))
ERROR(attr_NSManaged_let_property,sema_tcd,none,
"@NSManaged not allowed on a 'let' property", ())
@@ -1694,18 +1710,13 @@ ERROR(try_assign_rhs_noncovering,sema_tce,none,
"everything to its right", (unsigned))
ERROR(reference_non_inout,sema_tce,none,
- "reference to %0 not used to initialize a inout parameter", (Type))
+ "reference to %0 not used to initialize an inout parameter", (Type))
NOTE(subscript_decl_here,sema_tca,none,
"subscript operator declared here", ())
ERROR(condition_broken_proto,sema_tce,none,
"protocol 'BooleanType' is broken", ())
-ERROR(option_type_broken,sema_tce,none,
- "type 'Optional' is broken", ())
ERROR(broken_bool,sema_tce,none, "type 'Bool' is broken", ())
-ERROR(binding_explicit_downcast,sema_tce,none,
- "operand of postfix '?' is a forced downcast to type %0; use 'as?' to "
- "perform a conditional downcast", (Type))
WARNING(inject_forced_downcast,sema_tce,none,
"treating a forced downcast to %0 as optional will never produce 'nil'",
@@ -1736,11 +1747,6 @@ ERROR(migrate_from_allZeros,sema_tce,none,
ERROR(migrate_to_raw_to_raw_value,sema_tce,none,
"method 'fromRaw' has been replaced with a property 'rawValue'", ())
-ERROR(new_array_bound_zero,sema_tce,none,
- "array type cannot have zero length", ())
-ERROR(non_constant_array,type_parsing,none,
- "array has non-constant size", ())
-
ERROR(interpolation_missing_proto,sema_tce,none,
"string interpolation requires the protocol 'StringInterpolationConvertible' to be defined",
())
@@ -1809,6 +1815,8 @@ ERROR(type_is_not_array,sema_tce,none,
"contextual type %0 cannot be used with array literal", (Type))
NOTE(meant_dictionary_lit, sema_tce,none,
"did you mean to use a dictionary literal instead?", ())
+ERROR(should_use_empty_dictionary_literal,sema_tce,none,
+ "use [:] to get an empty dictionary literal", ())
// Dictionary literals
ERROR(dictionary_protocol_broken,sema_tce,none,
@@ -1845,7 +1853,6 @@ ERROR(partial_application_of_function_invalid,tce_sema,none,
"partial application of %select{"
"function with 'inout' parameters|"
"'mutating' method|"
- "method in @objc protocol|"
"'super.init' initializer chain|"
"'self.init' initializer delegation"
"}0 is not allowed",
@@ -1872,11 +1879,6 @@ ERROR(transitive_capture_before_declaration,tce_sema,none,
NOTE(transitive_capture_through_here,tce_sema,none,
"%0, declared here, captures %1",
(Identifier, Identifier))
-ERROR(unsupported_local_function_reference,tce_sema,none,
- "cannot reference a local function with captures from another local "
- "function", ())
-ERROR(unsupported_recursive_local_function,tce_sema,none,
- "local functions cannot reference themselves", ())
WARNING(recursive_accessor_reference,tce_sema,none,
"attempting to %select{access|modify}1 %0 within its own "
@@ -1990,6 +1992,12 @@ NOTE(change_to_mutating,sema_tcs,none,
"mark %select{method|accessor}0 'mutating' to make 'self' mutable",
(bool))
+// For Stmt
+WARNING(deprecated_c_style_for_stmt,sema_tcs,none,
+"C-style for statement is deprecated and will be removed in a future version of Swift", ())
+NOTE(cant_fix_c_style_for_stmt,sema_tcs,none,
+"C-style for statement can't be automatically fixed to for-in, because the loop variable is modified inside the loop", ())
+
// ForEach Stmt
ERROR(sequence_protocol_broken,sema_tcs,none,
"SequenceType protocol definition is broken", ())
@@ -2046,12 +2054,6 @@ ERROR(type_pattern_missing_is,sema_tcp,none,
ERROR(pattern_type_mismatch_context,sema_tcp,none,
"type annotation does not match contextual type %0", (Type))
-ERROR(label_single_entry_tuple,sema_tcp,none,
- "label is not allowed on single element tuple pattern", ())
-NOTE(remove_parens_for_type_annotation,sema_tcp,none,
- "remove the parentheses to make this a type annotation", ())
-NOTE(remove_label_for_tuple_pattern,sema_tcp,none,
- "remove the label to make this a tuple pattern", ())
ERROR(tuple_pattern_in_non_tuple_context,sema_tcp,none,
"tuple pattern cannot match values of the non-tuple type %0", (Type))
@@ -2068,8 +2070,6 @@ ERROR(tuple_pattern_label_mismatch,sema_tcp,none,
"tuple pattern element label %0 must be %1", (Identifier, Identifier))
ERROR(enum_element_pattern_member_not_found,sema_tcp,none,
"enum case '%0' not found in type %1", (StringRef, Type))
-ERROR(enum_element_pattern_not_enum,sema_tcp,none,
- "enum case pattern cannot match values of the non-enum type %0", (Type))
ERROR(optional_element_pattern_not_valid_type,sema_tcp,none,
"'?' pattern cannot match values of type %0", (Type))
ERROR(condition_optional_element_pattern_not_valid_type,sema_tcp,none,
@@ -2247,8 +2247,6 @@ NOTE(overridden_required_initializer_here,sema_tcd,none,
// Functions
ERROR(attribute_requires_function_type,attribute_parsing,none,
"attribute only applies to syntactic function types", ())
-ERROR(first_class_generic_function,type_parsing,PointsToFirstBadToken,
- "generic types cannot be used as first-class types", ())
ERROR(objc_block_cannot_be_thin,attribute_parsing,none,
"@objc_block function type cannot be @thin", ())
ERROR(attribute_not_supported,attribute_parsing,none,
@@ -2265,8 +2263,6 @@ WARNING(deprecated_convention_attribute,type_parsing,none,
"instead", (StringRef, StringRef))
// SIL
-ERROR(sil_local_storage_nested, decl_parsing,none,
- "local storage types cannot be in nested positions", ())
ERROR(opened_non_protocol, decl_parsing,none,
"@opened cannot be applied to non-protocol type %0", (Type))
ERROR(sil_function_ellipsis,type_parsing,PointsToFirstBadToken,
@@ -2280,8 +2276,6 @@ ERROR(sil_function_multiple_results,type_parsing,PointsToFirstBadToken,
"SIL function types cannot have multiple results", ())
ERROR(sil_function_multiple_error_results,type_parsing,PointsToFirstBadToken,
"SIL function types cannot have multiple @error results", ())
-ERROR(unsupported_cc_representation_combo,type_parsing,none,
- "cc unsupported with this sil representation", ())
ERROR(unsupported_sil_convention,type_parsing,none,
"convention '%0' not supported in SIL", (StringRef))
ERROR(sil_deprecated_convention_attribute,type_parsing,none,
@@ -2333,9 +2327,7 @@ ERROR(objc_setter_for_nonobjc_subscript,sema_tcd,none,
ERROR(objc_enum_generic,sema_tcd,none,
"'@objc' enum cannot be generic", ())
ERROR(objc_name_req_nullary,sema_objc,none,
- "'@objc' %select{class|protocol|property}0 must have a simple name", (int))
-ERROR(objc_name_enum,sema_objc,none,
- "'@objc' enum cannot have a name", ())
+ "'@objc' %select{class|protocol|enum|enum case|property}0 must have a simple name", (int))
ERROR(objc_name_subscript,sema_objc,none,
"'@objc' subscript cannot have a name; did you mean to put "
"the name on the getter or setter?", ())
@@ -2345,6 +2337,13 @@ ERROR(objc_name_func_mismatch,sema_objc,none,
"%select{initializer|method}0 has %select{one parameter|%3 parameters}4"
"%select{| (%select{|including }4the error parameter)}5",
(bool, unsigned, bool, unsigned, bool, bool))
+ERROR(objc_enum_case_req_name,sema_objc,none,
+ "attribute has no effect; cases within an '@objc' enum are already "
+ "exposed to Objective-C", ())
+ERROR(objc_enum_case_req_objc_enum,sema_objc,none,
+ "'@objc' enum case is not allowed outside of an '@objc' enum", ())
+ERROR(objc_enum_case_multi,sema_objc,none,
+ "'@objc' enum case declaration defines multiple enum cases with the same Objective-C name", ())
// If you change this, also change enum ObjCReason
#define OBJC_ATTR_SELECT "select{marked dynamic|marked @objc|marked @IBOutlet|marked @NSManaged|a member of an @objc protocol|implicitly @objc|an @objc override}"
diff --git a/include/swift/AST/DiagnosticsSema.h b/include/swift/AST/DiagnosticsSema.h
index 1177807691734..494756037cbe4 100644
--- a/include/swift/AST/DiagnosticsSema.h
+++ b/include/swift/AST/DiagnosticsSema.h
@@ -1,8 +1,8 @@
-//===- DiagnosticsSema.h - Diagnostic Definitions ---------------*- C++ -*-===//
+//===--- DiagnosticsSema.h - Diagnostic Definitions -------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -23,7 +23,7 @@
namespace swift {
namespace diag {
- /// Describes the kind of requirement in a protocl.
+ /// Describes the kind of requirement in a protocol.
enum class RequirementKind : uint8_t {
Constructor,
Func,
diff --git a/include/swift/AST/Expr.h b/include/swift/AST/Expr.h
index f6cae448e427c..bd5afde9d7f05 100644
--- a/include/swift/AST/Expr.h
+++ b/include/swift/AST/Expr.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -19,15 +19,8 @@
#include "swift/AST/CaptureInfo.h"
#include "swift/AST/ConcreteDeclRef.h"
-#include "swift/AST/DeclContext.h"
-#include "swift/AST/Identifier.h"
-#include "swift/AST/Substitution.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/Availability.h"
-#include "swift/Basic/SourceLoc.h"
-#include "swift/Config.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/StringRef.h"
namespace llvm {
struct fltSemantics;
@@ -54,6 +47,7 @@ namespace swift {
class ConstructorDecl;
class TypeDecl;
class PatternBindingDecl;
+ class ParameterList;
enum class ExprKind : uint8_t {
#define EXPR(Id, Parent) Id,
@@ -931,9 +925,6 @@ class DeclRefExpr : public Expr {
return DOrSpecialized.get();
}
- /// Set the declaration.
- void setDeclRef(ConcreteDeclRef ref);
-
void setSpecialized();
/// \brief Determine whether this declaration reference was immediately
@@ -2778,14 +2769,14 @@ class AbstractClosureExpr : public Expr, public DeclContext {
CaptureInfo Captures;
/// \brief The set of parameters.
- Pattern *ParamPattern;
+ ParameterList *parameterList;
public:
AbstractClosureExpr(ExprKind Kind, Type FnType, bool Implicit,
unsigned Discriminator, DeclContext *Parent)
: Expr(Kind, Implicit, FnType),
DeclContext(DeclContextKind::AbstractClosureExpr, Parent),
- ParamPattern(nullptr) {
+ parameterList(nullptr) {
AbstractClosureExprBits.Discriminator = Discriminator;
}
@@ -2793,9 +2784,9 @@ class AbstractClosureExpr : public Expr, public DeclContext {
const CaptureInfo &getCaptureInfo() const { return Captures; }
/// \brief Retrieve the parameters of this closure.
- Pattern *getParams() { return ParamPattern; }
- const Pattern *getParams() const { return ParamPattern; }
- void setParams(Pattern *P);
+ ParameterList *getParameters() { return parameterList; }
+ const ParameterList *getParameters() const { return parameterList; }
+ void setParameterList(ParameterList *P);
// Expose this to users.
using DeclContext::setParent;
@@ -2828,11 +2819,12 @@ class AbstractClosureExpr : public Expr, public DeclContext {
decltype(AbstractClosureExprBits)::InvalidDiscriminator
};
- ArrayRef getParamPatterns() {
- return ParamPattern ? ParamPattern : ArrayRef ();
+ ArrayRef getParameterLists() {
+ return parameterList ? parameterList : ArrayRef();
}
- ArrayRef getParamPatterns() const {
- return ParamPattern ? ParamPattern : ArrayRef ();
+
+ ArrayRef getParameterLists() const {
+ return parameterList ? parameterList : ArrayRef();
}
unsigned getNaturalArgumentCount() const { return 1; }
@@ -2924,7 +2916,7 @@ class ClosureExpr : public AbstractClosureExpr {
llvm::PointerIntPair Body;
public:
- ClosureExpr(Pattern *params, SourceLoc throwsLoc, SourceLoc arrowLoc,
+ ClosureExpr(ParameterList *params, SourceLoc throwsLoc, SourceLoc arrowLoc,
SourceLoc inLoc, TypeLoc explicitResultType,
unsigned discriminator, DeclContext *parent)
: AbstractClosureExpr(ExprKind::Closure, Type(), /*Implicit=*/false,
@@ -2932,7 +2924,7 @@ class ClosureExpr : public AbstractClosureExpr {
ThrowsLoc(throwsLoc), ArrowLoc(arrowLoc), InLoc(inLoc),
ExplicitResultType(explicitResultType),
Body(nullptr) {
- setParams(params);
+ setParameterList(params);
ClosureExprBits.HasAnonymousClosureVars = false;
ClosureExprBits.IsVoidConversionClosure = false;
}
@@ -3051,7 +3043,7 @@ class ClosureExpr : public AbstractClosureExpr {
/// \brief This is a closure of the contained subexpression that is formed
-/// when an scalar expression is converted to @autoclosure function type.
+/// when a scalar expression is converted to @autoclosure function type.
/// For example:
/// \code
/// @autoclosure var x : () -> Int = 4
@@ -3097,7 +3089,7 @@ class AutoClosureExpr : public AbstractClosureExpr {
/// DynamicTypeExpr - "base.dynamicType" - Produces a metatype value.
///
-/// The metatype value can comes from a evaluating an expression and then
+/// The metatype value can comes from evaluating an expression and then
/// getting its metatype.
class DynamicTypeExpr : public Expr {
Expr *Base;
@@ -3745,6 +3737,7 @@ class EditorPlaceholderExpr : public Expr {
SourceLoc Loc;
TypeLoc PlaceholderTy;
TypeRepr *ExpansionTyR;
+ Expr *SemanticExpr;
public:
EditorPlaceholderExpr(Identifier Placeholder, SourceLoc Loc,
@@ -3753,7 +3746,8 @@ class EditorPlaceholderExpr : public Expr {
: Expr(ExprKind::EditorPlaceholder, /*Implicit=*/false),
Placeholder(Placeholder), Loc(Loc),
PlaceholderTy(PlaceholderTy),
- ExpansionTyR(ExpansionTyR) {
+ ExpansionTyR(ExpansionTyR),
+ SemanticExpr(nullptr) {
}
Identifier getPlaceholder() const { return Placeholder; }
@@ -3767,6 +3761,9 @@ class EditorPlaceholderExpr : public Expr {
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::EditorPlaceholder;
}
+
+ Expr *getSemanticExpr() const { return SemanticExpr; }
+ void setSemanticExpr(Expr *SE) { SemanticExpr = SE; }
};
#undef SWIFT_FORWARD_SOURCE_LOCS_TO
diff --git a/include/swift/AST/ExprHandle.h b/include/swift/AST/ExprHandle.h
index 3b3a1d7aa3aad..6c4b8930d25a6 100644
--- a/include/swift/AST/ExprHandle.h
+++ b/include/swift/AST/ExprHandle.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -26,7 +26,7 @@ namespace swift {
/// ExprHandle - Provides an indirection for expressions, so both a type and a
/// pattern can point at the same expression during type-checking.
-class ExprHandle {
+class alignas(8) ExprHandle {
/// \brief The expression along with a bit saying whether this expression
/// was already type-checked (or not).
llvm::PointerIntPair EAndChecked;
diff --git a/include/swift/AST/ExprNodes.def b/include/swift/AST/ExprNodes.def
index 07d7c110b47f1..149183bb2159f 100644
--- a/include/swift/AST/ExprNodes.def
+++ b/include/swift/AST/ExprNodes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -156,7 +156,7 @@ EXPR(Assign, Expr)
EXPR(DefaultValue, Expr)
EXPR(CodeCompletion, Expr)
UNCHECKED_EXPR(UnresolvedPattern, Expr)
-UNCHECKED_EXPR(EditorPlaceholder, Expr)
+EXPR(EditorPlaceholder, Expr)
#undef EXPR_RANGE
#undef UNCHECKED_EXPR
diff --git a/include/swift/AST/ForeignErrorConvention.h b/include/swift/AST/ForeignErrorConvention.h
index f50ad66b78015..c9023bc4f0137 100644
--- a/include/swift/AST/ForeignErrorConvention.h
+++ b/include/swift/AST/ForeignErrorConvention.h
@@ -1,8 +1,8 @@
-//===--- ForeignErrorConvention.h - Error conventions ----------*- C++ -*-===//
+//===--- ForeignErrorConvention.h - Error conventions -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/GenericSignature.h b/include/swift/AST/GenericSignature.h
index f5ddc2e7629ac..6505f9c70de26 100644
--- a/include/swift/AST/GenericSignature.h
+++ b/include/swift/AST/GenericSignature.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -101,7 +101,7 @@ class GenericSignature : public llvm::FoldingSetNode {
NumGenericParams };
}
- /// Retrieve a mutable verison of the requirements.
+ /// Retrieve a mutable version of the requirements.
MutableArrayRef getRequirementsBuffer() {
void *genericParams = getGenericParamsBuffer().end();
return { reinterpret_cast(genericParams),
@@ -202,9 +202,10 @@ class GenericSignature : public llvm::FoldingSetNode {
/// Determine the superclass bound on the given dependent type.
Type getSuperclassBound(Type type, ModuleDecl &mod);
+ using ConformsToArray = SmallVector;
/// Determine the set of protocols to which the given dependent type
/// must conform.
- SmallVector getConformsTo(Type type, ModuleDecl &mod);
+ ConformsToArray getConformsTo(Type type, ModuleDecl &mod);
/// Determine whether the given dependent type is equal to a concrete type.
bool isConcreteType(Type type, ModuleDecl &mod);
diff --git a/include/swift/AST/IRGenOptions.h b/include/swift/AST/IRGenOptions.h
index 61cac6050adb1..4424c90d72bf4 100644
--- a/include/swift/AST/IRGenOptions.h
+++ b/include/swift/AST/IRGenOptions.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -135,7 +135,8 @@ class IRGenOptions {
DisableLLVMARCOpts(false), DisableLLVMSLPVectorizer(false),
DisableFPElim(true), Playground(false),
EmitStackPromotionChecks(false), GenerateProfile(false),
- EmbedMode(IRGenEmbedMode::None) {}
+ EmbedMode(IRGenEmbedMode::None)
+ {}
/// Gets the name of the specified output filename.
/// If multiple files are specified, the last one is returned.
diff --git a/include/swift/AST/Identifier.h b/include/swift/AST/Identifier.h
index 7cdc01d263ed1..7a38b65dd06a1 100644
--- a/include/swift/AST/Identifier.h
+++ b/include/swift/AST/Identifier.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -18,12 +18,8 @@
#define SWIFT_AST_IDENTIFIER_H
#include "swift/Basic/LLVM.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/PointerUnion.h"
-#include "llvm/ADT/StringRef.h"
-#include
namespace llvm {
class raw_ostream;
@@ -31,6 +27,7 @@ namespace llvm {
namespace swift {
class ASTContext;
+ class ParameterList;
/// DeclRefKind - The kind of reference to an identifier.
enum class DeclRefKind {
@@ -109,9 +106,6 @@ class Identifier {
/// isOperatorContinuationCodePoint - Return true if the specified code point
/// is a valid operator code point.
static bool isOperatorContinuationCodePoint(uint32_t C) {
- // '.' is a special case. It can only appear in '..'.
- if (C == '.')
- return false;
if (isOperatorStartCodePoint(C))
return true;
@@ -246,6 +240,9 @@ class DeclName {
: SimpleOrCompound(decltype(SimpleOrCompound)::getFromOpaqueValue(Opaque))
{}
+ void initialize(ASTContext &C, Identifier baseName,
+ ArrayRef argumentNames);
+
public:
/// Build a null name.
DeclName() : SimpleOrCompound(IdentifierAndCompound()) {}
@@ -256,9 +253,15 @@ class DeclName {
/// Build a compound value name given a base name and a set of argument names.
DeclName(ASTContext &C, Identifier baseName,
- ArrayRef argumentNames);
+ ArrayRef argumentNames) {
+ initialize(C, baseName, argumentNames);
+ }
+
+ /// Build a compound value name given a base name and a set of argument names
+ /// extracted from a parameter list.
+ DeclName(ASTContext &C, Identifier baseName, ParameterList *paramList);
- /// Retrive the 'base' name, i.e., the name that follows the introducer,
+ /// Retrieve the 'base' name, i.e., the name that follows the introducer,
/// such as the 'foo' in 'func foo(x:Int, y:Int)' or the 'bar' in
/// 'var bar: Int'.
Identifier getBaseName() const {
diff --git a/include/swift/AST/Initializer.h b/include/swift/AST/Initializer.h
index 29039412b36b6..f757c9525743f 100644
--- a/include/swift/AST/Initializer.h
+++ b/include/swift/AST/Initializer.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/KnownDecls.def b/include/swift/AST/KnownDecls.def
index a8483d202d7ce..524d0f1478ba4 100644
--- a/include/swift/AST/KnownDecls.def
+++ b/include/swift/AST/KnownDecls.def
@@ -1,8 +1,8 @@
-//===-- KnownDecl.def - Compiler declaration metaprogramming ----*- C++ -*-===//
+//===--- KnownDecls.def - Compiler declaration metaprogramming --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/KnownIdentifiers.def b/include/swift/AST/KnownIdentifiers.def
index 924b01f56596a..a24de752e972d 100644
--- a/include/swift/AST/KnownIdentifiers.def
+++ b/include/swift/AST/KnownIdentifiers.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===//
//
// This file defines macros used for macro-metaprogramming with compiler-known
-// identifers.
+// identifiers.
//
//===----------------------------------------------------------------------===//
diff --git a/include/swift/AST/KnownProtocols.def b/include/swift/AST/KnownProtocols.def
index 1669808d3bd86..615f9d6bd4c65 100644
--- a/include/swift/AST/KnownProtocols.def
+++ b/include/swift/AST/KnownProtocols.def
@@ -1,8 +1,8 @@
-//===-- KnownProtocols.def - Compiler protocol metaprogramming --*- C++ -*-===//
+//===--- KnownProtocols.def - Compiler protocol metaprogramming -*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/KnownProtocols.h b/include/swift/AST/KnownProtocols.h
index a2554fcebf1df..18cd1cb85b0a7 100644
--- a/include/swift/AST/KnownProtocols.h
+++ b/include/swift/AST/KnownProtocols.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/LazyResolver.h b/include/swift/AST/LazyResolver.h
index 3320491f108fa..42ac0d8cc8821 100644
--- a/include/swift/AST/LazyResolver.h
+++ b/include/swift/AST/LazyResolver.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -129,12 +129,8 @@ class alignas(void*) LazyMemberLoader {
/// Populates the given vector with all member decls for \p D.
///
/// The implementation should add the members to D.
- ///
- /// \param[out] hasMissingRequiredMembers If present, set to true if any
- /// members failed to import and were non-optional protocol requirements.
virtual void
- loadAllMembers(Decl *D, uint64_t contextData,
- bool *hasMissingRequiredMembers = nullptr) {
+ loadAllMembers(Decl *D, uint64_t contextData) {
llvm_unreachable("unimplemented");
}
diff --git a/include/swift/AST/LinkLibrary.h b/include/swift/AST/LinkLibrary.h
index df359296a9441..62724a8dd3f1c 100644
--- a/include/swift/AST/LinkLibrary.h
+++ b/include/swift/AST/LinkLibrary.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/Mangle.h b/include/swift/AST/Mangle.h
index 35e01c711bb72..eb974ad42079f 100644
--- a/include/swift/AST/Mangle.h
+++ b/include/swift/AST/Mangle.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -34,17 +34,19 @@ enum class OperatorFixity {
Postfix
};
-/// Defined in include/swift/SIL/Mangle.h
-class SpecializationManglerBase;
-/// A class for mangling declarations.
+/// A class for mangling declarations. The Mangler accumulates name fragments
+/// with the mangleXXX methods, and the final string is constructed with the
+/// `finalize` method, after which the Mangler should not be used.
class Mangler {
struct ArchetypeInfo {
unsigned Depth;
unsigned Index;
};
- raw_ostream &Buffer;
+ llvm::SmallVector Storage;
+ llvm::raw_svector_ostream Buffer;
+
llvm::DenseMap Substitutions;
llvm::DenseMap Archetypes;
CanGenericSignature CurGenericSignature;
@@ -56,8 +58,6 @@ class Mangler {
/// If enabled, non-ASCII names are encoded in modified Punycode.
bool UsePunycode;
- friend class SpecializationManglerBase;
-
public:
enum BindGenerics : unsigned {
/// We don't intend to mangle any sort of type within this context
@@ -88,14 +88,21 @@ class Mangler {
~ContextStack() { M.ArchetypesDepth = OldDepth; }
};
+ /// Finish the mangling of the symbol and return the mangled name.
+ std::string finalize();
+
+ /// Finish the mangling of the symbol and write the mangled name into
+ /// \p stream.
+ void finalize(llvm::raw_ostream &stream);
+
void setModuleContext(ModuleDecl *M) { Mod = M; }
/// \param DWARFMangling - use the 'Qq' mangling format for
/// archetypes and the 'a' mangling for alias types.
/// \param usePunycode - emit modified Punycode instead of UTF-8.
- Mangler(raw_ostream &buffer, bool DWARFMangling = false,
+ Mangler(bool DWARFMangling = false,
bool usePunycode = true)
- : Buffer(buffer), DWARFMangling(DWARFMangling), UsePunycode(usePunycode) {}
+ : Buffer(Storage), DWARFMangling(DWARFMangling), UsePunycode(usePunycode) {}
void mangleContextOf(const ValueDecl *decl, BindGenerics shouldBind);
void mangleContext(const DeclContext *ctx, BindGenerics shouldBind);
void mangleModule(const ModuleDecl *module);
@@ -147,7 +154,24 @@ class Mangler {
void mangleTypeMetadataFull(CanType ty, bool isPattern);
void mangleTypeFullMetadataFull(CanType ty);
void mangleGlobalVariableFull(const VarDecl *decl);
-
+
+ /// Adds the string \p S into the mangled name.
+ void append(StringRef S);
+
+ /// Adds the char \p C into the mangled name.
+ void append(char C);
+
+ /// Add the already mangled symbol \p Name as an identifier. (using the
+ /// length prefix).
+ void mangleIdentifierSymbol(StringRef Name);
+
+ /// Add the already mangled symbol \p Name. This gives the mangler the
+ /// opportunity to decode \p Name before adding it to the mangled name.
+ void appendSymbol(StringRef Name);
+
+ /// Mangle the integer \p Nat into the name.
+ void mangleNatural(const APInt &Nat);
+
/// Mangles globalinit_token and globalinit_func, which are used to
/// initialize global variables.
/// \param decl The global variable or one of the global variables of a
diff --git a/include/swift/AST/Module.h b/include/swift/AST/Module.h
index 5069e1e4cb08a..ec8b5cca8f074 100644
--- a/include/swift/AST/Module.h
+++ b/include/swift/AST/Module.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -572,7 +572,7 @@ class ModuleDecl : public TypeDecl, public DeclContext {
public:
// Only allow allocation of Modules using the allocator in ASTContext
// or by doing a placement new.
- void *operator new(size_t Bytes, ASTContext &C,
+ void *operator new(size_t Bytes, const ASTContext &C,
unsigned Alignment = alignof(ModuleDecl));
};
diff --git a/include/swift/AST/ModuleLoader.h b/include/swift/AST/ModuleLoader.h
index ae3e62490c95f..05bf1b247fa66 100644
--- a/include/swift/AST/ModuleLoader.h
+++ b/include/swift/AST/ModuleLoader.h
@@ -1,8 +1,8 @@
-//===--- ModuleLoader.h - Module Loader Interface ----------- -*- C++ -*- -===//
+//===--- ModuleLoader.h - Module Loader Interface ---------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -95,7 +95,7 @@ class ModuleLoader {
virtual void loadExtensions(NominalTypeDecl *nominal,
unsigned previousGeneration) { }
- /// \brief Load the methods within the given class that that produce
+ /// \brief Load the methods within the given class that produce
/// Objective-C class or instance methods with the given selector.
///
/// \param classDecl The class in which we are searching for @objc methods.
@@ -109,7 +109,7 @@ class ModuleLoader {
///
/// \param previousGeneration The previous generation with which this
/// callback was invoked. The list of methods will already contain all of
- /// the results from generations up and and including \c previousGeneration.
+ /// the results from generations up and including \c previousGeneration.
///
/// \param methods The list of @objc methods in this class that have this
/// selector and are instance/class methods as requested. This list will be
diff --git a/include/swift/AST/NameLookup.h b/include/swift/AST/NameLookup.h
index b1fdf59244411..97b94ab03d4c2 100644
--- a/include/swift/AST/NameLookup.h
+++ b/include/swift/AST/NameLookup.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -140,7 +140,7 @@ enum class DeclVisibilityKind {
MemberOfOutsideNominal,
/// Declaration is visible at the top level because it is declared in this
- /// module or in a imported module.
+ /// module or in an imported module.
VisibleAtTopLevel,
/// Declaration was found via \c AnyObject or \c AnyObject.Type.
diff --git a/include/swift/AST/Ownership.h b/include/swift/AST/Ownership.h
index b329a324201d4..eeea534f3d59a 100644
--- a/include/swift/AST/Ownership.h
+++ b/include/swift/AST/Ownership.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/ParameterList.h b/include/swift/AST/ParameterList.h
new file mode 100644
index 0000000000000..d228151b05a9e
--- /dev/null
+++ b/include/swift/AST/ParameterList.h
@@ -0,0 +1,153 @@
+//===--- ParameterList.h - Functions & closures parameter lists -*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See http://swift.org/LICENSE.txt for license information
+// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ParameterList class and support logic.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_AST_PARAMETERLIST_H
+#define SWIFT_AST_PARAMETERLIST_H
+
+#include "swift/AST/Decl.h"
+#include "swift/Basic/OptionSet.h"
+
+namespace swift {
+
+/// This describes a list of parameters. Each parameter descriptor is tail
+/// allocated onto this list.
+class alignas(alignof(ParamDecl*)) ParameterList {
+ void *operator new(size_t Bytes) throw() = delete;
+ void operator delete(void *Data) throw() = delete;
+ void *operator new(size_t Bytes, void *Mem) throw() = delete;
+ void *operator new(size_t Bytes, ASTContext &C,
+ unsigned Alignment = 8);
+
+ SourceLoc LParenLoc, RParenLoc;
+ size_t numParameters;
+
+ ParameterList(SourceLoc LParenLoc, size_t numParameters, SourceLoc RParenLoc)
+ : LParenLoc(LParenLoc), RParenLoc(RParenLoc), numParameters(numParameters){}
+ void operator=(const ParameterList&) = delete;
+public:
+ /// Create a parameter list with the specified parameters.
+ static ParameterList *create(const ASTContext &C, SourceLoc LParenLoc,
+ ArrayRef params,
+ SourceLoc RParenLoc);
+
+ /// Create a parameter list with the specified parameters, with no location
+ /// info for the parens.
+ static ParameterList *create(const ASTContext &C,
+ ArrayRef params) {
+ return create(C, SourceLoc(), params, SourceLoc());
+ }
+
+ /// Create an empty parameter list.
+ static ParameterList *createEmpty(const ASTContext &C,
+ SourceLoc LParenLoc = SourceLoc(),
+ SourceLoc RParenLoc = SourceLoc()) {
+ return create(C, LParenLoc, {}, RParenLoc);
+ }
+
+ /// Create a parameter list for a single parameter lacking location info.
+ static ParameterList *createWithoutLoc(ParamDecl *decl) {
+ return create(decl->getASTContext(), decl);
+ }
+
+ /// Create an implicit 'self' decl for a method in the specified decl context.
+ /// If 'static' is true, then this is self for a static method in the type.
+ ///
+ /// Note that this decl is created, but it is returned with an incorrect
+ /// DeclContext that needs to be set correctly. This is automatically handled
+ /// when a function is created with this as part of its argument list.
+ ///
+ static ParameterList *createSelf(SourceLoc loc, DeclContext *DC,
+ bool isStaticMethod = false,
+ bool isInOut = false);
+
+ SourceLoc getLParenLoc() const { return LParenLoc; }
+ SourceLoc getRParenLoc() const { return RParenLoc; }
+
+ typedef MutableArrayRef::iterator iterator;
+ typedef ArrayRef::iterator const_iterator;
+ iterator begin() { return getArray().begin(); }
+ iterator end() { return getArray().end(); }
+ const_iterator begin() const { return getArray().begin(); }
+ const_iterator end() const { return getArray().end(); }
+
+ MutableArrayRef getArray() {
+ auto Ptr = reinterpret_cast(this + 1);
+ return { Ptr, numParameters };
+ }
+ ArrayRef getArray() const {
+ auto Ptr = reinterpret_cast(this + 1);
+ return { Ptr, numParameters };
+ }
+
+ size_t size() const {
+ return numParameters;
+ }
+
+ const ParamDecl *get(unsigned i) const {
+ return getArray()[i];
+ }
+
+ ParamDecl *&get(unsigned i) {
+ return getArray()[i];
+ }
+
+ const ParamDecl *operator[](unsigned i) const { return get(i); }
+ ParamDecl *&operator[](unsigned i) { return get(i); }
+
+ /// Change the DeclContext of any contained parameters to the specified
+ /// DeclContext.
+ void setDeclContextOfParamDecls(DeclContext *DC);
+
+
+ /// Flags used to indicate how ParameterList cloning should operate.
+ enum CloneFlags {
+ /// The cloned ParamDecls should be marked implicit.
+ Implicit = 0x01,
+ /// The cloned pattern is for an inherited constructor; mark default
+ /// arguments as inherited, and mark unnamed arguments as named.
+ Inherited = 0x02
+ };
+
+ /// Make a duplicate copy of this parameter list. This allocates copies of
+ /// the ParamDecls, so they can be reparented into a new DeclContext.
+ ParameterList *clone(const ASTContext &C,
+ OptionSet options = None) const;
+
+ /// Return a TupleType or ParenType for this parameter list. This returns a
+ /// null type if one of the ParamDecls does not have a type set for it yet.
+ Type getType(const ASTContext &C) const;
+
+ /// Return the full function type for a set of curried parameter lists that
+ /// returns the specified result type. This returns a null type if one of the
+ /// ParamDecls does not have a type set for it yet.
+ ///
+ static Type getFullType(Type resultType, ArrayRef PL);
+
+
+ /// Return the full source range of this parameter.
+ SourceRange getSourceRange() const;
+ SourceLoc getStartLoc() const { return getSourceRange().Start; }
+ SourceLoc getEndLoc() const { return getSourceRange().End; }
+
+ void dump() const;
+ void dump(raw_ostream &OS, unsigned Indent = 0) const;
+
+ // void print(raw_ostream &OS) const;
+};
+
+} // end namespace swift.
+
+#endif
diff --git a/include/swift/AST/Pattern.h b/include/swift/AST/Pattern.h
index 694e0d54b64e0..e30f875d20be5 100644
--- a/include/swift/AST/Pattern.h
+++ b/include/swift/AST/Pattern.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -20,7 +20,6 @@
#include "swift/Basic/SourceLoc.h"
#include "swift/Basic/type_traits.h"
#include "swift/AST/Decl.h"
-#include "swift/AST/DefaultArgumentKind.h"
#include "swift/AST/Expr.h"
#include "swift/Basic/LLVM.h"
#include "swift/AST/Type.h"
@@ -30,7 +29,6 @@
namespace swift {
class ASTContext;
- class ExprHandle;
/// PatternKind - The classification of different kinds of
/// value-matching pattern.
@@ -120,11 +118,6 @@ class alignas(8) Pattern {
/// identifier if the pattern does not bind a name directly.
Identifier getBoundName() const;
- /// Returns the name directly bound by this pattern within the body of
- /// a function, or the null identifier if the pattern does not bind a name
- /// directly.
- Identifier getBodyName() const;
-
/// If this pattern binds a single variable without any
/// destructuring or conditionalizing, return that variable.
VarDecl *getSingleVar() const;
@@ -169,54 +162,12 @@ class alignas(8) Pattern {
VD->setParentPatternStmt(S);
});
}
-
- /// Return the number of "top-level" variables in the given pattern,
- /// which looks into one level of tuple pattern to determine the #
- /// of variables. If the pattern is not a tuple, the result is one.
- unsigned numTopLevelVariables() const;
-
- /// \brief Build an implicit 'self' parameter for the specified DeclContext.
- static Pattern *buildImplicitSelfParameter(SourceLoc Loc,
- TypeLoc TyLoc,
- DeclContext *CurDeclContext);
-
- /// \brief Build an implicit let parameter pattern for the specified
- /// DeclContext.
- static Pattern *buildImplicitLetParameter(SourceLoc loc, StringRef name,
- TypeLoc TyLoc,
- DeclContext *CurDeclContext);
-
- /// Flags used to indicate how pattern cloning should operate.
- enum CloneFlags {
- /// The cloned pattern should be implicit.
- Implicit = 0x01,
- /// The cloned pattern is for an inherited constructor; mark default
- /// arguments as inherited, and mark unnamed arguments as named.
- Inherited = 0x02,
- /// Whether the named patterns produced from a cloned 'any' pattern is
- /// are 'var'.
- IsVar = 0x04
- };
-
- Pattern *clone(ASTContext &context,
- OptionSet options = None) const;
-
- /// Given that this is a function-parameter pattern, clone it in a
- /// way that permits makeForwardingReference to be called on the
- /// result.
- Pattern *cloneForwardable(ASTContext &context, DeclContext *DC,
- OptionSet options = None) const;
- /// Form an un-typechecked reference to the variables bound by this
- /// pattern in a manner which perfectly forwards the values. Not
- /// all patterns can be forwarded.
- Expr *buildForwardingRefExpr(ASTContext &context) const;
-
static bool classof(const Pattern *P) { return true; }
//*** Allocation Routines ************************************************/
- void *operator new(size_t bytes, ASTContext &C);
+ void *operator new(size_t bytes, const ASTContext &C);
// Make placement new and vanilla new/delete illegal for Patterns.
void *operator new(size_t bytes) = delete;
@@ -271,23 +222,14 @@ class ParenPattern : public Pattern {
class TuplePatternElt {
Identifier Label;
SourceLoc LabelLoc;
- llvm::PointerIntPair ThePatternAndEllipsis;
- SourceLoc EllipsisLoc;
- ExprHandle *Init;
- DefaultArgumentKind DefArgKind;
+ Pattern *ThePattern;
public:
TuplePatternElt() = default;
- explicit TuplePatternElt(Pattern *P)
- : ThePatternAndEllipsis(P, false), Init(nullptr), DefArgKind(DefaultArgumentKind::None) {}
+ explicit TuplePatternElt(Pattern *P) : ThePattern(P) {}
- TuplePatternElt(Identifier Label, SourceLoc LabelLoc,
- Pattern *p, bool hasEllipsis,
- SourceLoc ellipsisLoc = SourceLoc(),
- ExprHandle *init = nullptr,
- DefaultArgumentKind defArgKind = DefaultArgumentKind::None)
- : Label(Label), LabelLoc(LabelLoc), ThePatternAndEllipsis(p, hasEllipsis),
- EllipsisLoc(ellipsisLoc), Init(init), DefArgKind(defArgKind) {}
+ TuplePatternElt(Identifier Label, SourceLoc LabelLoc, Pattern *p)
+ : Label(Label), LabelLoc(LabelLoc), ThePattern(p) {}
Identifier getLabel() const { return Label; }
SourceLoc getLabelLoc() const { return LabelLoc; }
@@ -296,20 +238,12 @@ class TuplePatternElt {
LabelLoc = Loc;
}
- Pattern *getPattern() { return ThePatternAndEllipsis.getPointer(); }
+ Pattern *getPattern() { return ThePattern; }
const Pattern *getPattern() const {
- return ThePatternAndEllipsis.getPointer();
+ return ThePattern;
}
- void setPattern(Pattern *p) { ThePatternAndEllipsis.setPointer(p); }
-
- bool hasEllipsis() const { return ThePatternAndEllipsis.getInt(); }
- SourceLoc getEllipsisLoc() const { return EllipsisLoc; }
-
- ExprHandle *getInit() const { return Init; }
-
- DefaultArgumentKind getDefaultArgKind() const { return DefArgKind; }
- void setDefaultArgKind(DefaultArgumentKind DAK) { DefArgKind = DAK; }
+ void setPattern(Pattern *p) { ThePattern = p; }
};
/// A pattern consisting of a tuple of patterns.
@@ -366,9 +300,6 @@ class TuplePattern : public Pattern {
SourceLoc getRParenLoc() const { return RPLoc; }
SourceRange getSourceRange() const;
- bool hasAnyEllipsis() const;
- SourceLoc getAnyEllipsisLoc() const;
-
static bool classof(const Pattern *P) {
return P->getKind() == PatternKind::Tuple;
}
@@ -387,7 +318,6 @@ class NamedPattern : public Pattern {
VarDecl *getDecl() const { return Var; }
Identifier getBoundName() const;
- Identifier getBodyName() const;
StringRef getNameStr() const { return Var->getNameStr(); }
SourceLoc getLoc() const { return Var->getLoc(); }
@@ -674,6 +604,7 @@ class EnumElementPattern : public Pattern {
}
SourceRange getSourceRange() const { return {getStartLoc(), getEndLoc()}; }
+ TypeLoc &getParentType() { return ParentType; }
TypeLoc getParentType() const { return ParentType; }
static bool classof(const Pattern *P) {
diff --git a/include/swift/AST/PatternNodes.def b/include/swift/AST/PatternNodes.def
index a35385bdd17d6..40dc5926a8f59 100644
--- a/include/swift/AST/PatternNodes.def
+++ b/include/swift/AST/PatternNodes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/PlatformKind.h b/include/swift/AST/PlatformKind.h
index 4ac2580ac3aca..3da2fe800b45b 100644
--- a/include/swift/AST/PlatformKind.h
+++ b/include/swift/AST/PlatformKind.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -32,7 +32,7 @@ enum class PlatformKind {
#include "swift/AST/PlatformKinds.def"
};
-/// Returns the short string representating the platform, suitable for
+/// Returns the short string representing the platform, suitable for
/// use in availability specifications (e.g., "OSX").
StringRef platformString(PlatformKind platform);
@@ -40,7 +40,7 @@ StringRef platformString(PlatformKind platform);
/// or None if such a platform kind does not exist.
Optional platformFromString(StringRef Name);
-/// Returns a human-readiable version of the platform name as a string, suitable
+/// Returns a human-readable version of the platform name as a string, suitable
/// for emission in diagnostics (e.g., "OS X").
StringRef prettyPlatformString(PlatformKind platform);
diff --git a/include/swift/AST/PlatformKinds.def b/include/swift/AST/PlatformKinds.def
index 0a97d241d8907..3325258e5fd16 100644
--- a/include/swift/AST/PlatformKinds.def
+++ b/include/swift/AST/PlatformKinds.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/PrettyStackTrace.h b/include/swift/AST/PrettyStackTrace.h
index 5a0e4ba48d5a9..1456a773965c2 100644
--- a/include/swift/AST/PrettyStackTrace.h
+++ b/include/swift/AST/PrettyStackTrace.h
@@ -1,8 +1,8 @@
-//===- PrettyStackTrace.h - Crash trace information -------------*- C++ -*-===//
+//===--- PrettyStackTrace.h - Crash trace information -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -10,7 +10,7 @@
//
//===----------------------------------------------------------------------===//
//
-// This file defines RAII classes that give better dagnostic output
+// This file defines RAII classes that give better diagnostic output
// about when, exactly, a crash is occurring.
//
//===----------------------------------------------------------------------===//
diff --git a/include/swift/AST/PrintOptions.h b/include/swift/AST/PrintOptions.h
index 22fe00cb924d8..a025e067f42be 100644
--- a/include/swift/AST/PrintOptions.h
+++ b/include/swift/AST/PrintOptions.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -247,7 +247,7 @@ struct PrintOptions {
static PrintOptions printTypeInterface(Type T, DeclContext *DC);
- /// Retrive the print options that are suitable to print the testable interface.
+ /// Retrieve the print options that are suitable to print the testable interface.
static PrintOptions printTestableInterface() {
PrintOptions result = printInterface();
result.AccessibilityFilter = Accessibility::Internal;
diff --git a/include/swift/AST/ProtocolConformance.h b/include/swift/AST/ProtocolConformance.h
index c60c6d74e93a6..aaa68d4d787c6 100644
--- a/include/swift/AST/ProtocolConformance.h
+++ b/include/swift/AST/ProtocolConformance.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -187,7 +187,9 @@ class ProtocolConformance {
/// protocol conformance.
///
/// The function object should accept a \c ValueDecl* for the requirement
- /// followed by the \c ConcreteDeclRef for the witness.
+ /// followed by the \c ConcreteDeclRef for the witness. Note that a generic
+ /// witness will only be specialized if the conformance came from the current
+ /// file.
template
void forEachValueWitness(LazyResolver *resolver, F f) const {
const ProtocolDecl *protocol = getProtocol();
@@ -252,7 +254,7 @@ class ProtocolConformance {
return mem;
}
- /// Print a parsable and human-readable description of the identifying
+ /// Print a parseable and human-readable description of the identifying
/// information of the protocol conformance.
void printName(raw_ostream &os,
const PrintOptions &PO = PrintOptions()) const;
@@ -376,6 +378,9 @@ class NormalProtocolConformance : public ProtocolConformance,
TypeDecl *typeDecl) const;
/// Retrieve the value witness corresponding to the given requirement.
+ ///
+ /// Note that a generic witness will only be specialized if the conformance
+ /// came from the current file.
ConcreteDeclRef getWitness(ValueDecl *requirement,
LazyResolver *resolver) const;
diff --git a/include/swift/AST/RawComment.h b/include/swift/AST/RawComment.h
index 3b83baef652cd..ad51be01ccd54 100644
--- a/include/swift/AST/RawComment.h
+++ b/include/swift/AST/RawComment.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/ReferencedNameTracker.h b/include/swift/AST/ReferencedNameTracker.h
index a1738c6b58871..7864ae1f86486 100644
--- a/include/swift/AST/ReferencedNameTracker.h
+++ b/include/swift/AST/ReferencedNameTracker.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/Requirement.h b/include/swift/AST/Requirement.h
index 41d8a057fda71..9b54fb4642f83 100644
--- a/include/swift/AST/Requirement.h
+++ b/include/swift/AST/Requirement.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/ResilienceExpansion.h b/include/swift/AST/ResilienceExpansion.h
index f861539a8fd38..a8059e86b0827 100644
--- a/include/swift/AST/ResilienceExpansion.h
+++ b/include/swift/AST/ResilienceExpansion.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/SILOptions.h b/include/swift/AST/SILOptions.h
index 9366df5726900..67ff129762d15 100644
--- a/include/swift/AST/SILOptions.h
+++ b/include/swift/AST/SILOptions.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -97,6 +97,13 @@ class SILOptions {
/// Should we use a pass pipeline passed in via a json file? Null by default.
StringRef ExternalPassPipelineFilename;
+
+ /// Use super_method for native super method calls instead of function_ref.
+ bool UseNativeSuperMethod = false;
+
+ /// Emit captures and function contexts using +0 caller-guaranteed ARC
+ /// conventions.
+ bool EnableGuaranteedClosureContexts = false;
};
} // end namespace swift
diff --git a/include/swift/AST/SearchPathOptions.h b/include/swift/AST/SearchPathOptions.h
index 8f558dfbfdf48..e767946540c08 100644
--- a/include/swift/AST/SearchPathOptions.h
+++ b/include/swift/AST/SearchPathOptions.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/Stmt.h b/include/swift/AST/Stmt.h
index f6c50aef97a65..206b184ee7e79 100644
--- a/include/swift/AST/Stmt.h
+++ b/include/swift/AST/Stmt.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -217,7 +217,7 @@ class DeferStmt : public Stmt {
Expr *getCallExpr() const { return callExpr; }
void setCallExpr(Expr *E) { callExpr = E; }
- /// Dig the original users's body of the defer out for AST fidelity.
+ /// Dig the original user's body of the defer out for AST fidelity.
BraceStmt *getBodyAsWritten() const;
static bool classof(const Stmt *S) { return S->getKind() == StmtKind::Defer; }
@@ -800,6 +800,9 @@ class ForStmt : public LabeledStmt {
SourceLoc getStartLoc() const { return getLabelLocOrKeywordLoc(ForLoc); }
SourceLoc getEndLoc() const { return Body->getEndLoc(); }
+
+ SourceLoc getFirstSemicolonLoc() const { return Semi1Loc; }
+ SourceLoc getSecondSemicolonLoc() const { return Semi2Loc; }
NullablePtr getInitializer() const { return Initializer; }
void setInitializer(Expr *V) { Initializer = V; }
diff --git a/include/swift/AST/StmtNodes.def b/include/swift/AST/StmtNodes.def
index 87b8f9a2b0aa1..38676dcbd5903 100644
--- a/include/swift/AST/StmtNodes.def
+++ b/include/swift/AST/StmtNodes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/SubstTypeVisitor.h b/include/swift/AST/SubstTypeVisitor.h
index 2abe6583a1d74..012dead8867c2 100644
--- a/include/swift/AST/SubstTypeVisitor.h
+++ b/include/swift/AST/SubstTypeVisitor.h
@@ -1,8 +1,8 @@
-//===-- SubstTypeVisitor.h - Visitor for substituted types ------*- C++ -*-===//
+//===--- SubstTypeVisitor.h - Visitor for substituted types -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/Substitution.h b/include/swift/AST/Substitution.h
index f6754e520f759..d08de06f4632a 100644
--- a/include/swift/AST/Substitution.h
+++ b/include/swift/AST/Substitution.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/Type.h b/include/swift/AST/Type.h
index 8548667d4bfb8..372eecbdf0eb8 100644
--- a/include/swift/AST/Type.h
+++ b/include/swift/AST/Type.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeAlignments.h b/include/swift/AST/TypeAlignments.h
index b5844c9cd8c91..a40085de9f179 100644
--- a/include/swift/AST/TypeAlignments.h
+++ b/include/swift/AST/TypeAlignments.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeCheckerDebugConsumer.h b/include/swift/AST/TypeCheckerDebugConsumer.h
index b6133e4378af5..00a5d9ec2663b 100644
--- a/include/swift/AST/TypeCheckerDebugConsumer.h
+++ b/include/swift/AST/TypeCheckerDebugConsumer.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeLoc.h b/include/swift/AST/TypeLoc.h
index 8f2f7ef40f49e..a76585e453633 100644
--- a/include/swift/AST/TypeLoc.h
+++ b/include/swift/AST/TypeLoc.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeMatcher.h b/include/swift/AST/TypeMatcher.h
index 70461e6dbf6db..1cf6c940f176d 100644
--- a/include/swift/AST/TypeMatcher.h
+++ b/include/swift/AST/TypeMatcher.h
@@ -1,8 +1,8 @@
-//===-- TypeMatcher.h - Recursive Type Matcher------- -----------*- C++ -*-===//
+//===--- TypeMatcher.h - Recursive Type Matcher -----------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeMemberVisitor.h b/include/swift/AST/TypeMemberVisitor.h
index d6afd46a89bd3..6af30cfc3d8d9 100644
--- a/include/swift/AST/TypeMemberVisitor.h
+++ b/include/swift/AST/TypeMemberVisitor.h
@@ -1,8 +1,8 @@
-//===-- TypeMemberVisitor.h - ASTVisitor specialization ---------*- C++ -*-===//
+//===--- TypeMemberVisitor.h - ASTVisitor specialization --------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeNodes.def b/include/swift/AST/TypeNodes.def
index ebfffbf3baaa6..f9093ca449938 100644
--- a/include/swift/AST/TypeNodes.def
+++ b/include/swift/AST/TypeNodes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeRefinementContext.h b/include/swift/AST/TypeRefinementContext.h
index 14186ca77dd07..63844e750f10e 100644
--- a/include/swift/AST/TypeRefinementContext.h
+++ b/include/swift/AST/TypeRefinementContext.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeRepr.h b/include/swift/AST/TypeRepr.h
index c9fce95d9e67a..1478ba255199e 100644
--- a/include/swift/AST/TypeRepr.h
+++ b/include/swift/AST/TypeRepr.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -85,7 +85,7 @@ class alignas(8) TypeRepr {
//*** Allocation Routines ************************************************/
- void *operator new(size_t bytes, ASTContext &C,
+ void *operator new(size_t bytes, const ASTContext &C,
unsigned Alignment = alignof(TypeRepr));
// Make placement new and vanilla new/delete illegal for TypeReprs.
@@ -98,7 +98,7 @@ class alignas(8) TypeRepr {
void dump() const;
/// Clone the given type representation.
- TypeRepr *clone(ASTContext &ctx) const;
+ TypeRepr *clone(const ASTContext &ctx) const;
/// Visit the top-level types in the given type representation,
/// which includes the types referenced by \c IdentTypeReprs either
@@ -392,44 +392,24 @@ class FunctionTypeRepr : public TypeRepr {
/// [Foo]
/// \endcode
class ArrayTypeRepr : public TypeRepr {
- // FIXME: Tail allocation. Use bits to determine whether Base/Size are
- // availble.
TypeRepr *Base;
- llvm::PointerIntPair SizeAndOldSyntax;
SourceRange Brackets;
public:
- ArrayTypeRepr(TypeRepr *Base, ExprHandle *Size, SourceRange Brackets,
- bool OldSyntax)
- : TypeRepr(TypeReprKind::Array), Base(Base),
- SizeAndOldSyntax(Size, OldSyntax), Brackets(Brackets) { }
+ ArrayTypeRepr(TypeRepr *Base, SourceRange Brackets)
+ : TypeRepr(TypeReprKind::Array), Base(Base), Brackets(Brackets) { }
TypeRepr *getBase() const { return Base; }
- ExprHandle *getSize() const { return SizeAndOldSyntax.getPointer(); }
SourceRange getBrackets() const { return Brackets; }
- bool usesOldSyntax() const { return SizeAndOldSyntax.getInt(); }
-
static bool classof(const TypeRepr *T) {
return T->getKind() == TypeReprKind::Array;
}
static bool classof(const ArrayTypeRepr *T) { return true; }
private:
- SourceLoc getStartLocImpl() const {
- if (usesOldSyntax())
- return Base->getStartLoc();
-
- return Brackets.Start;
- }
- SourceLoc getEndLocImpl() const {
- // This test is necessary because the type Int[4][2] is represented as
- // ArrayTypeRepr(ArrayTypeRepr(Int, 2), 4), so the range needs to cover both
- // sets of brackets.
- if (usesOldSyntax() && isa(Base))
- return Base->getEndLoc();
- return Brackets.End;
- }
+ SourceLoc getStartLocImpl() const { return Brackets.Start; }
+ SourceLoc getEndLocImpl() const { return Brackets.End; }
void printImpl(ASTPrinter &Printer, const PrintOptions &Opts) const;
friend class TypeRepr;
};
@@ -781,10 +761,8 @@ inline bool TypeRepr::isSimple() const {
case TypeReprKind::ProtocolComposition:
case TypeReprKind::Tuple:
case TypeReprKind::Fixed:
- return true;
-
case TypeReprKind::Array:
- return !cast(this)->usesOldSyntax();
+ return true;
}
llvm_unreachable("bad TypeRepr kind");
}
diff --git a/include/swift/AST/TypeReprNodes.def b/include/swift/AST/TypeReprNodes.def
index 1ec3f7879fe30..50404fd9d9d94 100644
--- a/include/swift/AST/TypeReprNodes.def
+++ b/include/swift/AST/TypeReprNodes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeVisitor.h b/include/swift/AST/TypeVisitor.h
index 15be7dc39b574..81f89c3b90639 100644
--- a/include/swift/AST/TypeVisitor.h
+++ b/include/swift/AST/TypeVisitor.h
@@ -1,8 +1,8 @@
-//===-- TypeVisitor.h - Type Visitor ----------------------------*- C++ -*-===//
+//===--- TypeVisitor.h - Type Visitor ---------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/AST/TypeWalker.h b/include/swift/AST/TypeWalker.h
index 1a3d4042babff..7b079c01e604f 100644
--- a/include/swift/AST/TypeWalker.h
+++ b/include/swift/AST/TypeWalker.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -26,11 +26,11 @@ class TypeWalker {
Stop
};
- /// This method is called when first visiting an type before walking into its
+ /// This method is called when first visiting a type before walking into its
/// children.
virtual Action walkToTypePre(Type ty) { return Action::Continue; }
- /// This method is called after visiting an type's children.
+ /// This method is called after visiting a type's children.
virtual Action walkToTypePost(Type ty) { return Action::Continue; }
/// Controls whether the original type of a SubstitutedType is visited.
diff --git a/include/swift/AST/Types.h b/include/swift/AST/Types.h
index 4fc48aeff04ef..3f4e9b948870d 100644
--- a/include/swift/AST/Types.h
+++ b/include/swift/AST/Types.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -47,6 +47,7 @@ namespace swift {
class GenericParamList;
class GenericSignature;
class Identifier;
+ enum class ResilienceExpansion : unsigned;
class SILModule;
class SILType;
class TypeAliasDecl;
@@ -424,7 +425,7 @@ class alignas(1 << TypeAlignInBits) TypeBase {
return getRecursiveProperties().hasOpenedExistential();
}
- /// Determine whether the type involves the given opend existential
+ /// Determine whether the type involves the given opened existential
/// archetype.
bool hasOpenedExistential(ArchetypeType *opened);
@@ -632,7 +633,11 @@ class alignas(1 << TypeAlignInBits) TypeBase {
/// unknown-released.
bool hasRetainablePointerRepresentation();
- /// Determines whether this type has a bridgable object
+ /// \brief Given that this type is a reference type, is it known to use
+ /// Swift-native reference counting?
+ bool usesNativeReferenceCounting(ResilienceExpansion resilience);
+
+ /// Determines whether this type has a bridgeable object
/// representation, i.e., whether it is always represented as a single
/// (non-nil) pointer that can be unknown-retained and
/// unknown-released.
@@ -667,10 +672,6 @@ class alignas(1 << TypeAlignInBits) TypeBase {
/// the result would be the (parenthesized) type ((int, int)).
Type getUnlabeledType(ASTContext &Context);
- /// Relabel the elements of the given type with the given new
- /// (top-level) labels.
- Type getRelabeledType(ASTContext &Context, ArrayRef labels);
-
/// \brief Retrieve the type without any default arguments.
Type getWithoutDefaultArgs(const ASTContext &Context);
@@ -732,7 +733,7 @@ class alignas(1 << TypeAlignInBits) TypeBase {
/// \code
/// struct X { }
/// extension X {
- /// typealias SomeArray = [T];
+ /// typealias SomeArray = [T]
/// }
/// \endcode
///
@@ -834,17 +835,6 @@ class alignas(1 << TypeAlignInBits) TypeBase {
/// Retrieve the type declaration directly referenced by this type, if any.
TypeDecl *getDirectlyReferencedTypeDecl() const;
- /// Retrieve the default argument string that would be inferred for this type,
- /// assuming that we know it is inferred.
- ///
- /// This routine pre-supposes that we know that the given type is the type of
- /// a parameter that has a default, and all we need to figure out is which
- /// default argument should be print.
- ///
- /// FIXME: This should go away when/if inferred default arguments become
- /// "real".
- StringRef getInferredDefaultArgString();
-
private:
// Make vanilla new/delete illegal for Types.
void *operator new(size_t Bytes) throw() = delete;
@@ -1252,9 +1242,11 @@ class TupleTypeElt {
/// is variadic.
llvm::PointerIntPair NameAndVariadic;
- /// \brief This is the type of the field, which is mandatory, along with the
- /// kind of default argument.
- llvm::PointerIntPair TyAndDefaultArg;
+ /// \brief This is the type of the field.
+ Type ElementType;
+
+ /// The default argument,
+ DefaultArgumentKind DefaultArg;
friend class TupleType;
@@ -1268,12 +1260,12 @@ class TupleTypeElt {
/*implicit*/ TupleTypeElt(TypeBase *Ty)
: NameAndVariadic(Identifier(), false),
- TyAndDefaultArg(Ty, DefaultArgumentKind::None) { }
+ ElementType(Ty), DefaultArg(DefaultArgumentKind::None) { }
bool hasName() const { return !NameAndVariadic.getPointer().empty(); }
Identifier getName() const { return NameAndVariadic.getPointer(); }
- Type getType() const { return TyAndDefaultArg.getPointer(); }
+ Type getType() const { return ElementType.getPointer(); }
/// Determine whether this field is variadic.
bool isVararg() const {
@@ -1281,9 +1273,7 @@ class TupleTypeElt {
}
/// Retrieve the kind of default argument available on this field.
- DefaultArgumentKind getDefaultArgKind() const {
- return TyAndDefaultArg.getInt();
- }
+ DefaultArgumentKind getDefaultArgKind() const { return DefaultArg; }
/// Whether we have a default argument.
bool hasDefaultArg() const {
@@ -1303,11 +1293,6 @@ class TupleTypeElt {
TupleTypeElt getWithType(Type T) const {
return TupleTypeElt(T, getName(), getDefaultArgKind(), isVararg());
}
-
- /// Determine whether this tuple element has an initializer.
- bool hasInit() const {
- return getDefaultArgKind() != DefaultArgumentKind::None;
- }
};
inline Type getTupleEltType(const TupleTypeElt &elt) {
@@ -1353,7 +1338,7 @@ class TupleType : public TypeBase, public llvm::FoldingSetNode {
return TupleEltTypeArrayRef(getElements());
}
- /// getNamedElementId - If this tuple has a element with the specified name,
+ /// getNamedElementId - If this tuple has an element with the specified name,
/// return the element index, otherwise return -1.
int getNamedElementId(Identifier I) const;
@@ -2498,10 +2483,18 @@ enum class ParameterConvention {
Indirect_In_Guaranteed,
/// This argument is passed indirectly, i.e. by directly passing the address
- /// of an object in memory. The object is instantaneously valid on entry, and
- /// it must be instantaneously valid on exit. The callee may assume that the
- /// address does not alias any valid object.
+ /// of an object in memory. The object is always valid, but the callee may
+ /// assume that the address does not alias any valid object and reorder loads
+ /// stores to the parameter as long as the whole object remains valid. Invalid
+ /// single-threaded aliasing may produce inconsistent results, but should
+ /// remain memory safe.
Indirect_Inout,
+
+ /// This argument is passed indirectly, i.e. by directly passing the address
+ /// of an object in memory. The object is allowed to be aliased by other
+ /// well-typed references, but is not allowed to be escaped. This is the
+ /// convention used by mutable captures in @noescape closures.
+ Indirect_InoutAliasable,
/// This argument is passed indirectly, i.e. by directly passing the address
/// of an uninitialized object in memory. The callee is responsible for
@@ -2531,6 +2524,7 @@ inline bool isIndirectParameter(ParameterConvention conv) {
switch (conv) {
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_Inout:
+ case ParameterConvention::Indirect_InoutAliasable:
case ParameterConvention::Indirect_Out:
case ParameterConvention::Indirect_In_Guaranteed:
return true;
@@ -2550,6 +2544,7 @@ inline bool isConsumedParameter(ParameterConvention conv) {
return true;
case ParameterConvention::Indirect_Inout:
+ case ParameterConvention::Indirect_InoutAliasable:
case ParameterConvention::Indirect_Out:
case ParameterConvention::Direct_Unowned:
case ParameterConvention::Direct_Guaranteed:
@@ -2560,6 +2555,42 @@ inline bool isConsumedParameter(ParameterConvention conv) {
llvm_unreachable("bad convention kind");
}
+enum class InoutAliasingAssumption {
+ /// Assume that an inout indirect parameter may alias other objects.
+ /// This is the safe assumption an optimizations should make if it may break
+ /// memory safety in case the inout aliasing rule is violation.
+ Aliasing,
+
+ /// Assume that an inout indirect parameter cannot alias other objects.
+ /// Optimizations should only use this if they can guarantee that they will
+ /// not break memory safety even if the inout aliasing rule is violated.
+ NotAliasing
+};
+
+/// Returns true if \p conv is a not-aliasing indirect parameter.
+/// The \p isInoutAliasing specifies what to assume about the inout convention.
+/// See InoutAliasingAssumption.
+inline bool isNotAliasedIndirectParameter(ParameterConvention conv,
+ InoutAliasingAssumption isInoutAliasing) {
+ switch (conv) {
+ case ParameterConvention::Indirect_In:
+ case ParameterConvention::Indirect_Out:
+ case ParameterConvention::Indirect_In_Guaranteed:
+ return true;
+
+ case ParameterConvention::Indirect_Inout:
+ return isInoutAliasing == InoutAliasingAssumption::NotAliasing;
+
+ case ParameterConvention::Indirect_InoutAliasable:
+ case ParameterConvention::Direct_Unowned:
+ case ParameterConvention::Direct_Guaranteed:
+ case ParameterConvention::Direct_Owned:
+ case ParameterConvention::Direct_Deallocating:
+ return false;
+ }
+ llvm_unreachable("covered switch isn't covered?!");
+}
+
/// Returns true if conv is a guaranteed parameter. This may look unnecessary
/// but this will allow code to generalize to handle Indirect_Guaranteed
/// parameters when they are added.
@@ -2570,6 +2601,7 @@ inline bool isGuaranteedParameter(ParameterConvention conv) {
return true;
case ParameterConvention::Indirect_Inout:
+ case ParameterConvention::Indirect_InoutAliasable:
case ParameterConvention::Indirect_Out:
case ParameterConvention::Indirect_In:
case ParameterConvention::Direct_Unowned:
@@ -2587,6 +2619,7 @@ inline bool isDeallocatingParameter(ParameterConvention conv) {
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_Inout:
+ case ParameterConvention::Indirect_InoutAliasable:
case ParameterConvention::Indirect_Out:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Direct_Unowned:
@@ -2599,19 +2632,20 @@ inline bool isDeallocatingParameter(ParameterConvention conv) {
/// A parameter type and the rules for passing it.
class SILParameterInfo {
- llvm::PointerIntPair TypeAndConvention;
+ CanType Ty;
+ ParameterConvention Convention;
public:
- SILParameterInfo() = default;
+ SILParameterInfo() : Ty(), Convention((ParameterConvention)0) {}
SILParameterInfo(CanType type, ParameterConvention conv)
- : TypeAndConvention(type, conv) {
+ : Ty(type), Convention(conv) {
assert(type->isLegalSILType() && "SILParameterInfo has illegal SIL type");
}
CanType getType() const {
- return TypeAndConvention.getPointer();
+ return Ty;
}
ParameterConvention getConvention() const {
- return TypeAndConvention.getInt();
+ return Convention;
}
bool isIndirect() const {
return isIndirectParameter(getConvention());
@@ -2624,6 +2658,10 @@ class SILParameterInfo {
bool isIndirectInOut() const {
return getConvention() == ParameterConvention::Indirect_Inout;
}
+ bool isIndirectMutating() const {
+ return getConvention() == ParameterConvention::Indirect_Inout
+ || getConvention() == ParameterConvention::Indirect_InoutAliasable;
+ }
bool isIndirectResult() const {
return getConvention() == ParameterConvention::Indirect_Out;
}
@@ -2675,7 +2713,8 @@ class SILParameterInfo {
}
void profile(llvm::FoldingSetNodeID &id) {
- id.AddPointer(TypeAndConvention.getOpaqueValue());
+ id.AddPointer(Ty.getPointer());
+ id.AddInteger((unsigned)Convention);
}
void dump() const;
@@ -2689,7 +2728,7 @@ class SILParameterInfo {
}
bool operator==(SILParameterInfo rhs) const {
- return TypeAndConvention == rhs.TypeAndConvention;
+ return Ty == rhs.Ty && Convention == rhs.Convention;
}
bool operator!=(SILParameterInfo rhs) const {
return !(*this == rhs);
@@ -3246,7 +3285,7 @@ class DictionaryType : public TypeBase {
Key(key), Value(value), ImplOrContext(&ctx) {}
public:
- /// Return a uniqued dicitonary type with the specified key and value types.
+ /// Return a uniqued dictionary type with the specified key and value types.
static DictionaryType *get(Type keyTy, Type valueTy);
Type getKeyType() const { return Key; }
@@ -3985,7 +4024,7 @@ BEGIN_CAN_TYPE_WRAPPER(ReferenceStorageType, Type)
PROXY_CAN_TYPE_SIMPLE_GETTER(getReferentType)
END_CAN_TYPE_WRAPPER(ReferenceStorageType, Type)
-/// \brief The storage type of a variable with [unowned] ownership semantics.
+/// \brief The storage type of a variable with @unowned ownership semantics.
class UnownedStorageType : public ReferenceStorageType {
friend class ReferenceStorageType;
UnownedStorageType(Type referent, const ASTContext *C,
@@ -3998,6 +4037,10 @@ class UnownedStorageType : public ReferenceStorageType {
ReferenceStorageType::get(referent, Ownership::Unowned, C));
}
+ /// Is this unowned storage type known to be loadable within the given
+ /// resilience scope?
+ bool isLoadable(ResilienceExpansion resilience) const;
+
// Implement isa/cast/dyncast/etc.
static bool classof(const TypeBase *T) {
return T->getKind() == TypeKind::UnownedStorage;
@@ -4312,7 +4355,7 @@ inline TupleTypeElt::TupleTypeElt(Type ty,
DefaultArgumentKind defArg,
bool isVariadic)
: NameAndVariadic(name, isVariadic),
- TyAndDefaultArg(ty.getPointer(), defArg)
+ ElementType(ty), DefaultArg(defArg)
{
assert(!isVariadic ||
isa(ty.getPointer()) ||
diff --git a/include/swift/AST/USRGeneration.h b/include/swift/AST/USRGeneration.h
index 5eed154d0477b..2e0255ea32cbb 100644
--- a/include/swift/AST/USRGeneration.h
+++ b/include/swift/AST/USRGeneration.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/ASTSectionImporter/ASTSectionImporter.h b/include/swift/ASTSectionImporter/ASTSectionImporter.h
index 5cf16e56e2016..2820bb86494d7 100644
--- a/include/swift/ASTSectionImporter/ASTSectionImporter.h
+++ b/include/swift/ASTSectionImporter/ASTSectionImporter.h
@@ -1,8 +1,8 @@
-//===--- ASTSectionImporter.cpp - Import AST Section Modules ---*- C++ -*--===//
+//===--- ASTSectionImporter.h - Import AST Section Modules ------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -23,7 +23,7 @@
namespace swift {
class SerializedModuleLoader;
- /// \brief Povided a memory buffer with an entire Mach-O __apple_ast
+ /// \brief Provided a memory buffer with an entire Mach-O __apple_ast
/// section, this function makes memory buffer copies of all swift
/// modules found in it and registers them using
/// registerMemoryBuffer() so they can be found by loadModule(). The
diff --git a/include/swift/Basic/Algorithm.h b/include/swift/Basic/Algorithm.h
index a1134e802d7fa..c2cef45aff32a 100644
--- a/include/swift/Basic/Algorithm.h
+++ b/include/swift/Basic/Algorithm.h
@@ -1,8 +1,8 @@
-//===--- Algorithm.h - -------------------------------------------*- C++ -*-==//
+//===--- Algorithm.h - ------------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/ArrayRefView.h b/include/swift/Basic/ArrayRefView.h
index 6cddda4f9296e..f9181db6dc334 100644
--- a/include/swift/Basic/ArrayRefView.h
+++ b/include/swift/Basic/ArrayRefView.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/AssertImplements.h b/include/swift/Basic/AssertImplements.h
index 81894acb6ae5e..d4aa08b42ded1 100644
--- a/include/swift/Basic/AssertImplements.h
+++ b/include/swift/Basic/AssertImplements.h
@@ -1,8 +1,8 @@
-//===- AssertImplements.h - Assert that a class overrides a function ------===//
+//===--- AssertImplements.h - Assert that a class overrides a function ----===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/BlotMapVector.h b/include/swift/Basic/BlotMapVector.h
index 645c2ee1da441..a80be3093cfd6 100644
--- a/include/swift/Basic/BlotMapVector.h
+++ b/include/swift/Basic/BlotMapVector.h
@@ -1,8 +1,8 @@
-//===- BlotMapVector.h - Map vector with "blot" operation -----*- C++ -*--===//
+//===--- BlotMapVector.h - Map vector with "blot" operation ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/BlotSetVector.h b/include/swift/Basic/BlotSetVector.h
index 92ca3dfd4ad53..d4066d501566d 100644
--- a/include/swift/Basic/BlotSetVector.h
+++ b/include/swift/Basic/BlotSetVector.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -99,7 +99,7 @@ class BlotSetVector {
/// V1.
void replace(const ValueT &V1, const ValueT &V2) {
auto Iter1 = Map.find(V1);
- assert(Iter1 != Map.end() && "Can not replace value that is not in set");
+ assert(Iter1 != Map.end() && "Cannot replace value that is not in set");
unsigned V1Index = Iter1->second;
Map.erase(V1);
diff --git a/include/swift/Basic/Cache.h b/include/swift/Basic/Cache.h
index e3dfc995723d0..bcfd357e1eb2d 100644
--- a/include/swift/Basic/Cache.h
+++ b/include/swift/Basic/Cache.h
@@ -1,8 +1,8 @@
-//===--- Cache.h - Caching mechanism interface -------------------*- C++ -*-==//
+//===--- Cache.h - Caching mechanism interface ------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/ClusteredBitVector.h b/include/swift/Basic/ClusteredBitVector.h
index dcc5cfa31868a..99114d9c3e172 100644
--- a/include/swift/Basic/ClusteredBitVector.h
+++ b/include/swift/Basic/ClusteredBitVector.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Defer.h b/include/swift/Basic/Defer.h
index d412db123b503..95e46e7cb2064 100644
--- a/include/swift/Basic/Defer.h
+++ b/include/swift/Basic/Defer.h
@@ -1,8 +1,8 @@
-//===- Defer.h - 'defer' helper macro ---------------------------*- C++ -*-===//
+//===--- Defer.h - 'defer' helper macro -------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -10,7 +10,7 @@
//
//===----------------------------------------------------------------------===//
//
-// This filed defines a 'defer' macro for performing a cleanup on any exit out
+// This file defines a 'defer' macro for performing a cleanup on any exit out
// of a scope.
//
//===----------------------------------------------------------------------===//
@@ -18,11 +18,12 @@
#ifndef __SWIFT_DEFER_H
#define __SWIFT_DEFER_H
+#include
+
namespace swift {
template
class DoAtScopeExit {
F &Fn;
- DoAtScopeExit(DoAtScopeExit&) = delete;
void operator=(DoAtScopeExit&) = delete;
public:
DoAtScopeExit(F &Fn) : Fn(Fn){}
@@ -30,8 +31,17 @@ namespace swift {
Fn();
}
};
+
+ namespace detail {
+ struct DeferTask {};
+ template
+ DoAtScopeExit::type> operator+(DeferTask, F&& fn) {
+ return DoAtScopeExit::type>(fn);
+ }
+ }
}
+
#define DEFER_CONCAT_IMPL(x, y) x##y
#define DEFER_MACRO_CONCAT(x, y) DEFER_CONCAT_IMPL(x, y)
@@ -39,16 +49,13 @@ namespace swift {
/// This macro is used to register a function / lambda to be run on exit from a
/// scope. Its typical use looks like:
///
-/// defer([&]{
+/// defer {
/// stuff
-/// })
+/// };
///
-#define defer(x) \
- auto DEFER_MACRO_CONCAT(defer_func, __LINE__) = (x); \
- swift::DoAtScopeExit \
- DEFER_MACRO_CONCAT(defer_local, __LINE__)\
- (DEFER_MACRO_CONCAT(defer_func, __LINE__));
+#define defer \
+ auto DEFER_MACRO_CONCAT(defer_func, __COUNTER__) = \
+ ::swift::detail::DeferTask() + [&]()
#endif
-
diff --git a/include/swift/Basic/Demangle.h b/include/swift/Basic/Demangle.h
index dba1292b81309..c9d1807a98de2 100644
--- a/include/swift/Basic/Demangle.h
+++ b/include/swift/Basic/Demangle.h
@@ -1,8 +1,8 @@
-//===--- Demangle.h - Interface to Swift symbol demangling -------*- C++ -*-==//
+//===--- Demangle.h - Interface to Swift symbol demangling ------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -78,7 +78,8 @@ enum class FunctionSigSpecializationParamKind : unsigned {
ConstantPropFloat = 3,
ConstantPropString = 4,
ClosureProp = 5,
- InOutToValue = 6,
+ BoxToValue = 6,
+ BoxToStack = 7,
// Option Set Flags use bits 6-31. This gives us 26 bits to use for option
// flags.
@@ -89,7 +90,7 @@ enum class FunctionSigSpecializationParamKind : unsigned {
/// The pass that caused the specialization to occur. We use this to make sure
/// that two passes that generate similar changes do not yield the same
-/// mangling. This currently can not happen, so this is just a safety measure
+/// mangling. This currently cannot happen, so this is just a safety measure
/// that creates separate name spaces.
enum class SpecializationPass : uint8_t {
AllocBoxToStack,
@@ -101,7 +102,7 @@ enum class SpecializationPass : uint8_t {
};
static inline char encodeSpecializationPass(SpecializationPass Pass) {
- return char(uint8_t(Pass)) + 48;
+ return char(uint8_t(Pass)) + '0';
}
enum class ValueWitnessKind {
diff --git a/include/swift/Basic/DemangleNodes.def b/include/swift/Basic/DemangleNodes.def
index 58e5c5752d4d0..0c05714bfda3b 100644
--- a/include/swift/Basic/DemangleNodes.def
+++ b/include/swift/Basic/DemangleNodes.def
@@ -1,8 +1,8 @@
-//===-- DemangleNodes.def - Demangling Tree Metaprogramming -----*- C++ -*-===//
+//===--- DemangleNodes.def - Demangling Tree Metaprogramming ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -30,6 +30,8 @@ NODE(ArchetypeRef)
NODE(ArgumentTuple)
NODE(AssociatedType)
NODE(AssociatedTypeRef)
+NODE(AssociatedTypeMetadataAccessor)
+NODE(AssociatedTypeWitnessTableAccessor)
NODE(AutoClosureType)
NODE(BoundGenericClass)
NODE(BoundGenericEnum)
@@ -49,8 +51,6 @@ NODE(DependentGenericSameTypeRequirement)
NODE(DependentGenericType)
NODE(DependentMemberType)
NODE(DependentGenericParamType)
-NODE(DependentProtocolWitnessTableGenerator)
-NODE(DependentProtocolWitnessTableTemplate)
CONTEXT_NODE(Destructor)
CONTEXT_NODE(DidSet)
NODE(Directness)
@@ -71,6 +71,8 @@ NODE(FunctionSignatureSpecializationParamKind)
NODE(FunctionSignatureSpecializationParamPayload)
NODE(FunctionType)
NODE(Generics)
+NODE(GenericProtocolWitnessTable)
+NODE(GenericProtocolWitnessTableInstantiationFunction)
NODE(GenericSpecialization)
NODE(GenericSpecializationParam)
NODE(GenericType)
@@ -128,6 +130,7 @@ NODE(QualifiedArchetype)
NODE(ReabstractionThunk)
NODE(ReabstractionThunkHelper)
NODE(ReturnType)
+NODE(SILBoxType)
NODE(SelfTypeRef)
CONTEXT_NODE(Setter)
NODE(SpecializationPassID)
diff --git a/include/swift/Basic/DemangleWrappers.h b/include/swift/Basic/DemangleWrappers.h
index 080320d2c2467..07d121994f6bd 100644
--- a/include/swift/Basic/DemangleWrappers.h
+++ b/include/swift/Basic/DemangleWrappers.h
@@ -1,8 +1,8 @@
-//===--- DemangleWrappers.h --------------------------------------*- C++ -*-==//
+//===--- DemangleWrappers.h -------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/DiagnosticConsumer.h b/include/swift/Basic/DiagnosticConsumer.h
index 7a1860ea136b1..80ce1d27ab01e 100644
--- a/include/swift/Basic/DiagnosticConsumer.h
+++ b/include/swift/Basic/DiagnosticConsumer.h
@@ -1,8 +1,8 @@
-//===- DiagnosticConsumer.h - Diagnostic Consumer Interface -----*- C++ -*-===//
+//===--- DiagnosticConsumer.h - Diagnostic Consumer Interface ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -19,12 +19,8 @@
#ifndef SWIFT_BASIC_DIAGNOSTIC_CONSUMER_H
#define SWIFT_BASIC_DIAGNOSTIC_CONSUMER_H
-#include "swift/Basic/LLVM.h"
#include "swift/Basic/SourceLoc.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/StringRef.h"
#include "llvm/Support/SourceMgr.h"
-#include
namespace swift {
class SourceManager;
diff --git a/include/swift/Basic/DiagnosticOptions.h b/include/swift/Basic/DiagnosticOptions.h
index 20b232faf913e..91fb9e4df34d3 100644
--- a/include/swift/Basic/DiagnosticOptions.h
+++ b/include/swift/Basic/DiagnosticOptions.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/DiverseList.h b/include/swift/Basic/DiverseList.h
index 771327bc7bf00..8a2169e35001c 100644
--- a/include/swift/Basic/DiverseList.h
+++ b/include/swift/Basic/DiverseList.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -29,7 +29,7 @@ namespace swift {
template class DiverseListImpl;
-/// DiverseList - A list of heterogenously-typed objects.
+/// DiverseList - A list of heterogeneously-typed objects.
///
/// \tparam T - A common base class of the objects in the list; must
/// provide an allocated_size() const method.
diff --git a/include/swift/Basic/DiverseStack.h b/include/swift/Basic/DiverseStack.h
index a63dd826a76fb..01351273cee65 100644
--- a/include/swift/Basic/DiverseStack.h
+++ b/include/swift/Basic/DiverseStack.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -29,7 +29,7 @@ namespace swift {
template class DiverseStackImpl;
-/// DiverseStack - A stack of heterogenously-typed objects.
+/// DiverseStack - A stack of heterogeneously-typed objects.
///
/// \tparam T - A common base class of the objects on the stack; must
/// provide an allocated_size() const method.
diff --git a/include/swift/Basic/Dwarf.h b/include/swift/Basic/Dwarf.h
index cceb2088e9391..c568990d3e8a0 100644
--- a/include/swift/Basic/Dwarf.h
+++ b/include/swift/Basic/Dwarf.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/EditorPlaceholder.h b/include/swift/Basic/EditorPlaceholder.h
index ea28420b5706c..50df069c15bc0 100644
--- a/include/swift/Basic/EditorPlaceholder.h
+++ b/include/swift/Basic/EditorPlaceholder.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/EncodedSequence.h b/include/swift/Basic/EncodedSequence.h
index b4c0a8d099211..c0a8bfc342e14 100644
--- a/include/swift/Basic/EncodedSequence.h
+++ b/include/swift/Basic/EncodedSequence.h
@@ -1,8 +1,8 @@
-//===--- EncodedSequence.h - A byte-encoded sequence -----------*- C++ -*-===//
+//===--- EncodedSequence.h - A byte-encoded sequence ------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Fallthrough.h b/include/swift/Basic/Fallthrough.h
index 0e28731c6c0a6..c697722545fc9 100644
--- a/include/swift/Basic/Fallthrough.h
+++ b/include/swift/Basic/Fallthrough.h
@@ -1,8 +1,8 @@
-//===- Fallthrough.h - switch fallthrough annotation macro ------*- C++ -*-===//
+//===--- Fallthrough.h - switch fallthrough annotation macro ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -10,7 +10,7 @@
//
//===----------------------------------------------------------------------===//
//
-// This filed defines a SWIFT_FALLTHROUGH macro to annotate intentional
+// This file defines a SWIFT_FALLTHROUGH macro to annotate intentional
// fallthrough between switch cases. For compilers that support the
// "clang::fallthrough" attribute, it expands to an empty statement with the
// attribute applied; otherwise, it expands to just an empty statement.
diff --git a/include/swift/Basic/FileSystem.h b/include/swift/Basic/FileSystem.h
index 59d99df55c928..749818329f166 100644
--- a/include/swift/Basic/FileSystem.h
+++ b/include/swift/Basic/FileSystem.h
@@ -1,8 +1,8 @@
-//===--- FileSystem.cpp - Extra helpers for manipulating files --*- C++ -*-===//
+//===--- FileSystem.h - Extra helpers for manipulating files ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/FlaggedPointer.h b/include/swift/Basic/FlaggedPointer.h
index b70fb8c93d4be..c6d2c349a0b35 100644
--- a/include/swift/Basic/FlaggedPointer.h
+++ b/include/swift/Basic/FlaggedPointer.h
@@ -1,8 +1,8 @@
-//===- FlaggedPointer.h - Explicit pointer tagging container ----*- C++ -*-===//
+//===--- FlaggedPointer.h - Explicit pointer tagging container --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/JSONSerialization.h b/include/swift/Basic/JSONSerialization.h
index 9fd98b9d9bfaf..0663aa5461eb3 100644
--- a/include/swift/Basic/JSONSerialization.h
+++ b/include/swift/Basic/JSONSerialization.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -284,7 +284,7 @@ struct missingTraits : public std::integral_constant::value
&& !has_ScalarTraits::value
&& !has_ObjectTraits::value
- && !has_ArrayTraits::value> {};
+ && !has_ArrayTraits::value> {};
template
struct validatedObjectTraits : public std::integral_constantpostflightKey(SaveInfo);
- }
- else {
+ } else {
if ( UseDefault )
Val = DefaultValue;
}
@@ -614,7 +613,7 @@ operator<<(Output &yout, T &map) {
return yout;
}
-// Define non-member operator<< so that Output can stream out a array.
+// Define non-member operator<< so that Output can stream out an array.
template
inline
typename
diff --git a/include/swift/Basic/LLVM.h b/include/swift/Basic/LLVM.h
index 6537f52ad0037..2bfb5b33755b0 100644
--- a/include/swift/Basic/LLVM.h
+++ b/include/swift/Basic/LLVM.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/LLVMInitialize.h b/include/swift/Basic/LLVMInitialize.h
index 53365f86f5e60..599e78406ae99 100644
--- a/include/swift/Basic/LLVMInitialize.h
+++ b/include/swift/Basic/LLVMInitialize.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/LangOptions.h b/include/swift/Basic/LangOptions.h
index 66dae000800ad..badd9f00afcab 100644
--- a/include/swift/Basic/LangOptions.h
+++ b/include/swift/Basic/LangOptions.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -130,7 +130,7 @@ namespace swift {
/// This is for testing purposes.
std::string DebugForbidTypecheckPrefix;
- /// Number of paralellel processes performing AST verification.
+ /// Number of parallel processes performing AST verification.
unsigned ASTVerifierProcessCount = 1U;
/// ID of the current process for the purposes of AST verification.
@@ -173,7 +173,9 @@ namespace swift {
Target.getiOSVersion(major, minor, revision);
} else if (Target.isWatchOS()) {
Target.getOSVersion(major, minor, revision);
- } else if (Target.isOSLinux() || Target.getTriple().empty()) {
+ } else if (Target.isOSLinux() || Target.isOSFreeBSD() ||
+ Target.getTriple().empty())
+ {
major = minor = revision = 0;
} else {
llvm_unreachable("Unsupported target OS");
diff --git a/include/swift/Basic/Lazy.h b/include/swift/Basic/Lazy.h
index e10afc49b019f..e720a87a1f906 100644
--- a/include/swift/Basic/Lazy.h
+++ b/include/swift/Basic/Lazy.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -74,10 +74,10 @@ template inline T &Lazy::get(void (*initCallback)(void*)) {
} // namespace swift
#define SWIFT_LAZY_CONSTANT(INITIAL_VALUE) \
- ({ \
+ ([]{ \
using T = ::std::remove_reference::type; \
static ::swift::Lazy TheLazy; \
- TheLazy.get([](void *ValueAddr){ ::new(ValueAddr) T{INITIAL_VALUE}; });\
- })
+ return TheLazy.get([](void *ValueAddr){ ::new(ValueAddr) T{INITIAL_VALUE}; });\
+ }())
#endif // SWIFT_BASIC_LAZY_H
diff --git a/include/swift/Basic/Malloc.h b/include/swift/Basic/Malloc.h
index 2ac42e6ef5a79..1f11c133251a0 100644
--- a/include/swift/Basic/Malloc.h
+++ b/include/swift/Basic/Malloc.h
@@ -1,8 +1,8 @@
-//===- Malloc.h - Aligned malloc interface ----------------------*- C++ -*-===//
+//===--- Malloc.h - Aligned malloc interface --------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/NullablePtr.h b/include/swift/Basic/NullablePtr.h
index c39071dc35ac6..8f827a4625f72 100644
--- a/include/swift/Basic/NullablePtr.h
+++ b/include/swift/Basic/NullablePtr.h
@@ -1,8 +1,8 @@
-//===- NullablePtr.h - A pointer that allows null ---------------*- C++ -*-===//
+//===--- NullablePtr.h - A pointer that allows null -------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/OptionSet.h b/include/swift/Basic/OptionSet.h
index 977527e9b19c6..c2763fdf7b600 100644
--- a/include/swift/Basic/OptionSet.h
+++ b/include/swift/Basic/OptionSet.h
@@ -1,8 +1,8 @@
-//===-- OptionSet.h - Sets of boolean options -------------------*- C++ -*-===//
+//===--- OptionSet.h - Sets of boolean options ------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/OptionalEnum.h b/include/swift/Basic/OptionalEnum.h
index cfcd34e9b4e90..3d594ab4d998e 100644
--- a/include/swift/Basic/OptionalEnum.h
+++ b/include/swift/Basic/OptionalEnum.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Platform.h b/include/swift/Basic/Platform.h
index c60444a42ebfe..4b151a7dbc4a4 100644
--- a/include/swift/Basic/Platform.h
+++ b/include/swift/Basic/Platform.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/PointerIntEnum.h b/include/swift/Basic/PointerIntEnum.h
new file mode 100644
index 0000000000000..8e18c2a3a7d7e
--- /dev/null
+++ b/include/swift/Basic/PointerIntEnum.h
@@ -0,0 +1,247 @@
+//===--- PointerIntEnum.h -------------------------------------------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See http://swift.org/LICENSE.txt for license information
+// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+
+#include "swift/Basic/LLVM.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/Support/PointerLikeTypeTraits.h"
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace swift {
+
+/// A tiny meta function to compute the log2 of a compile time constant.
+///
+/// *NOTE* This will be in an updated version of LLVM so this should be removed
+/// at that point in time.
+template
+struct ConstantLog2
+ : std::integral_constant::value + 1> {};
+template <> struct ConstantLog2<1> : std::integral_constant {};
+
+/// A meta function for computing at compile time cleanly the value for an index
+/// kind's value without using cpp macros.
+template
+struct PointerIntEnumIndexKindValue
+ : std::integral_constant::value)) |
+ unsigned(EnumTy::FirstIndexKind)> {};
+
+/// A pointer sized ADT that is able to compactly represent a Swift like enum
+/// that can contain both Integer and Pointer payloads. It attempts to optimize
+/// for the case of being able to represent as many pointer cases as possible
+/// while allowing for indices to be stored as well. Without any loss of
+/// generality assume that T* is our stored pointer. Then this is done as
+/// follows:
+///
+/// 1. A PointerIntEnum for which bits [0, (num_tagged_bits(T*)-1)] are not all
+/// set to 1 represent an enum with a pointer case. This means that one can have
+/// at most ((1 << num_tagged_bits(T*)) - 2) enum cases associated with
+/// pointers.
+///
+/// 2. A PointerIntEnum for which bits [0, (num_tagged_bits(T*)-1)] are all set
+/// is either an invalid PointerIntEnum or an index.
+///
+/// 3. A PointerIntEnum with all bits set is an invalid PointerIntEnum.
+///
+/// 4. A PointerIntEnum for which bits [0, (num_tagged_bits(T*)-1)] are all set
+/// but for which the upper bits are not all set is an index enum. The case bits
+/// for the index PointerIntEnum are stored in bits [num_tagged_bits(T*),
+/// num_tagged_bits(T*) + num_index_case_bits]. Then the actual index is stored
+/// in the remaining top bits. For the case in which this is used in swift
+/// currently, we use 3 index bits meaning that on a 32 bit system we have 26
+/// bits for representing indices meaning we can represent indices up to
+/// 67_108_862. Any index larger than that will result in an invalid
+/// PointerIntEnum. On 64 bit we have many more bits than that.
+///
+/// By using this representation, we can make PointerIntEnum a true value type
+/// that is trivially constructible and destructible without needing to malloc
+/// memory.
+///
+/// In order for all of this to work, the user of this needs to construct an
+/// enum with the appropriate case structure that allows the data structure to
+/// determine what cases are pointer and which are indices. For instance the one
+/// used by Projection in swift is:
+///
+/// enum class NewProjectionKind : unsigned {
+/// // PointerProjectionKinds
+/// Upcast = 0,
+/// RefCast = 1,
+/// BitwiseCast = 2,
+/// FirstPointerKind = Upcast,
+/// LastPointerKind = BitwiseCast,
+///
+///
+/// // This needs to be set to ((1 << num_tagged_bits(T*)) - 1). It
+/// // represents the first NonPointerKind.
+/// FirstIndexKind = 7,
+///
+/// // Index Projection Kinds
+/// Struct = PointerIntEnumIndexKindValue<0, EnumTy>::value,
+/// Tuple = PointerIntEnumIndexKindValue<1, EnumTy>::value,
+/// Index = PointerIntEnumIndexKindValue<2, EnumTy>::value,
+/// Class = PointerIntEnumIndexKindValue<3, EnumTy>::value,
+/// Enum = PointerIntEnumIndexKindValue<4, EnumTy>::value,
+/// LastIndexKind = Enum,
+/// };
+///
+template >
+class PointerIntEnum {
+
+ // Make sure that the enum fits our requirements.
+ static_assert(unsigned(EnumTy::FirstIndexKind) ==
+ ((1U << NumPointerKindBits) - 1U),
+ "Invalid Enum");
+ static_assert(unsigned(EnumTy::FirstIndexKind) <=
+ unsigned(EnumTy::LastIndexKind),
+ "Invalid Enum");
+ static_assert(unsigned(EnumTy::FirstPointerKind) <=
+ unsigned(EnumTy::LastPointerKind),
+ "Invalid Enum");
+ static_assert(unsigned(EnumTy::LastPointerKind) <
+ unsigned(EnumTy::FirstIndexKind),
+ "Invalid Enum");
+
+ /// The offset in bits where an index would be stored.
+ static constexpr unsigned IndexShiftOffset =
+ NumIndexKindBits + NumPointerKindBits;
+
+ /// The number of bits in a PointerIntEnum that can be used to store indices.
+ static constexpr unsigned NumIndexBits =
+ sizeof(uintptr_t) * CHAR_BIT - IndexShiftOffset;
+
+ /// The maximum index that can be stored for an index PointerIntEnum case.
+ static constexpr uintptr_t MaxIndex = (uintptr_t(1) << NumIndexBits) - 2;
+
+ /// The bit representation of an Invalid PointerIntEnum's storage.
+ static constexpr uintptr_t InvalidStorage = uintptr_t(0) - 1;
+
+ /// The pointer sized type used for the actual storage.
+ ///
+ /// Never access this directly. Instead use the following methods:
+ ///
+ /// * getKind(): Same as RawKind except if the kind is LargeIndex, will
+ /// discover the real underlying kind in the malloced memory.
+ /// * getIndex(): Asserts if getKind() is a pointer storing kind.
+ /// * getPointer(): Returns the underlying pointer cast into
+ /// PointerTy. Asserts if getKind() is an index storing kind.
+ uintptr_t Storage;
+
+public:
+ PointerIntEnum() : Storage(InvalidStorage) {}
+
+ PointerIntEnum(EnumTy Kind, uintptr_t NewIndex) {
+ initWithIndex(Kind, NewIndex);
+ }
+
+ PointerIntEnum(EnumTy Kind, PointerTy Ptr) { initWithPointer(Kind, Ptr); }
+
+ PointerIntEnum(PointerIntEnum &&P) = default;
+ PointerIntEnum(const PointerIntEnum &P) = default;
+ ~PointerIntEnum() = default;
+ PointerIntEnum &operator=(const PointerIntEnum &P) = default;
+ PointerIntEnum &operator=(PointerIntEnum &&P) = default;
+
+ bool isValid() const { return Storage != InvalidStorage; }
+
+ bool operator==(const PointerIntEnum &Other) const {
+ // If this value is not valid, it can only equal another invalid
+ // PointerIntEnum.
+ if (!isValid())
+ return !Other.isValid();
+
+ // Otherwise just compare the raw storage.
+ return Other.Storage == Storage;
+ }
+
+ bool operator!=(const PointerIntEnum &Other) const {
+ return !(*this == Other);
+ }
+
+ /// Convenience method for getting the kind of this enum. Returns None if this
+ /// enum is invalid.
+ Optional getKind() const {
+ if (!isValid())
+ return None;
+
+ // Check if the bottom pointer bits are all not set. If that is true then we
+ // know that we have a pointer kind.
+ unsigned PointerBits = Storage & uintptr_t(EnumTy::FirstIndexKind);
+ if (PointerBits != unsigned(EnumTy::FirstIndexKind)) {
+ return EnumTy(PointerBits);
+ }
+
+ // Otherwise, we have an index kind. Just mask off the actual index bits and
+ // return the kind.
+ unsigned Mask = (1 << IndexShiftOffset) - 1;
+ unsigned MaskedStorage = Storage & Mask;
+ return EnumTy(MaskedStorage);
+ }
+
+ /// Convenience method for getting the underlying index. Assumes that this
+ /// projection is valid. Otherwise it asserts.
+ uintptr_t getIndex() const {
+ assert(isValid());
+ assert(unsigned(*getKind()) >= unsigned(EnumTy::FirstIndexKind));
+ return Storage >> IndexShiftOffset;
+ }
+
+ PointerTy getPointer() const {
+ uintptr_t Value = Storage & ~(uintptr_t(EnumTy::FirstIndexKind));
+ return reinterpret_cast(Value);
+ }
+
+ /// Return the raw storage of the type. Used for testing purposes.
+ uintptr_t getStorage() const { return Storage; }
+
+private:
+ void initInvalid() { Storage = InvalidStorage; }
+
+ /// Initialize this PointerIntEnum with the kind \p Kind and the Pointer \p
+ /// Ptr.
+ ///
+ /// This is an internal helper routine that should not be used directly since
+ /// it does not properly handle freeing memory.
+ void initWithIndex(EnumTy Kind, uintptr_t NewIndex) {
+ // If we can not represent this index, make the PointerIntEnum invalid.
+ if (NewIndex > MaxIndex) {
+ Storage = InvalidStorage;
+ return;
+ }
+
+ Storage = uintptr_t(Kind) | (uintptr_t(NewIndex) << IndexShiftOffset);
+ }
+
+ /// Initialize this PointerIntEnum with the kind \p Kind and the Pointer \p
+ /// Ptr.
+ ///
+ /// This is an internal helper routine that should not be used directly since
+ /// it does not properly handle freeing memory.
+ void initWithPointer(EnumTy Kind, PointerTy Ptr) {
+ // Make sure the pointer is at least aligned to NumPointerKindBits.
+ assert((uintptr_t(Ptr) & ((1 << NumPointerKindBits) - 1)) == 0);
+ // Make sure that Kind is a PointerKind.
+ assert(unsigned(Kind) >= unsigned(EnumTy::FirstPointerKind));
+ assert(unsigned(Kind) <= unsigned(EnumTy::LastPointerKind));
+
+ Storage = uintptr_t(Ptr);
+ Storage |= uintptr_t(Kind);
+ }
+};
+
+} // end swift namespace
diff --git a/include/swift/Basic/PrefixMap.h b/include/swift/Basic/PrefixMap.h
index 47e1a55100f73..7841f7267e0f0 100644
--- a/include/swift/Basic/PrefixMap.h
+++ b/include/swift/Basic/PrefixMap.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/PrettyStackTrace.h b/include/swift/Basic/PrettyStackTrace.h
index 536dc3abae0de..7d94fde0f5306 100644
--- a/include/swift/Basic/PrettyStackTrace.h
+++ b/include/swift/Basic/PrettyStackTrace.h
@@ -1,8 +1,8 @@
-//===--- PrettyStackTrace.h - Generic stack-trace prettifiers ----*- C++ -*-==//
+//===--- PrettyStackTrace.h - Generic stack-trace prettifiers ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/PrimitiveParsing.h b/include/swift/Basic/PrimitiveParsing.h
index 90ea9719b5465..780173238e1ec 100644
--- a/include/swift/Basic/PrimitiveParsing.h
+++ b/include/swift/Basic/PrimitiveParsing.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Program.h b/include/swift/Basic/Program.h
index 3d98377e32289..061639afc602c 100644
--- a/include/swift/Basic/Program.h
+++ b/include/swift/Basic/Program.h
@@ -1,8 +1,8 @@
-//===- swift/Basic/Program.h ------------------------------------*- C++ -*-===//
+//===--- Program.h ----------------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Punycode.h b/include/swift/Basic/Punycode.h
index 3fbfcb09475ca..de7974160aadf 100644
--- a/include/swift/Basic/Punycode.h
+++ b/include/swift/Basic/Punycode.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/QuotedString.h b/include/swift/Basic/QuotedString.h
index 5fffc896da3c2..cee2a416b6d60 100644
--- a/include/swift/Basic/QuotedString.h
+++ b/include/swift/Basic/QuotedString.h
@@ -1,8 +1,8 @@
-//===- QuotedString.h - Print a string in double-quotes ---------*- C++ -*-===//
+//===--- QuotedString.h - Print a string in double-quotes -------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Range.h b/include/swift/Basic/Range.h
index efdb6d273a4ea..f27fc738e0428 100644
--- a/include/swift/Basic/Range.h
+++ b/include/swift/Basic/Range.h
@@ -1,8 +1,8 @@
-//===- Range.h - Classes for conveniently working with ranges ---*- C++ -*-===//
+//===--- Range.h - Classes for conveniently working with ranges -*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -61,12 +61,13 @@ namespace swift {
}
/// A range of integers. This type behaves roughly like an ArrayRef.
-template class IntRange {
+template class IntRange {
static_assert(std::is_integral::value, "T must be an integer type");
T Begin;
T End;
public:
IntRange() : Begin(0), End(0) {}
+ IntRange(T end) : Begin(0), End(end) {}
IntRange(T begin, T end) : Begin(begin), End(end) {
assert(begin <= end);
}
@@ -165,6 +166,17 @@ indices(const T &collection) {
return IntRange().size())>(0, collection.size());
}
+/// Returns an Int range [start, end).
+static inline IntRange range(unsigned start, unsigned end) {
+ assert(start <= end && "Invalid integral range");
+ return IntRange(start, end);
+}
+
+/// Returns an Int range [0, end).
+static inline IntRange range(unsigned end) {
+ return range(0, end);
+}
+
/// A random access range that provides iterators that can be used to iterate
/// over the (element, index) pairs of a collection.
template class EnumeratorRange {
@@ -280,6 +292,11 @@ none_of(Range R, Predicate P) {
return std::none_of(R.begin(), R.end(), P);
}
+template
+inline unsigned count_if(Range R, Predicate P) {
+ return std::count_if(R.begin(), R.end(), P);
+}
+
} // namespace swift
#endif
diff --git a/include/swift/Basic/RelativePointer.h b/include/swift/Basic/RelativePointer.h
index 188ddf26d9505..c5c084185a55a 100644
--- a/include/swift/Basic/RelativePointer.h
+++ b/include/swift/Basic/RelativePointer.h
@@ -1,8 +1,8 @@
-//===-- RelativePointer.h - Relative Pointer Support ------------*- C++ -*-===//
+//===--- RelativePointer.h - Relative Pointer Support -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -102,6 +102,10 @@ class RelativeDirectPointerImpl {
return reinterpret_cast(absolute);
}
+ /// A zero relative offset encodes a null reference.
+ bool isNull() const & {
+ return RelativeOffset == 0;
+ }
};
/// A direct relative reference to an object.
@@ -122,6 +126,8 @@ class RelativeDirectPointer :
const typename super::ValueTy *operator->() const & {
return this->get();
}
+
+ using super::isNull;
};
/// A specialization of RelativeDirectPointer for function pointers,
@@ -139,6 +145,8 @@ class RelativeDirectPointer :
RetTy operator()(ArgTy...arg) {
return this->get()(std::forward(arg)...);
}
+
+ using super::isNull;
};
}
diff --git a/include/swift/Basic/STLExtras.h b/include/swift/Basic/STLExtras.h
index f0182b6df52ed..b50af049727cc 100644
--- a/include/swift/Basic/STLExtras.h
+++ b/include/swift/Basic/STLExtras.h
@@ -1,8 +1,8 @@
-//===- STLExtras.h - additions to the STL -----------------------*- C++ -*-===//
+//===--- STLExtras.h - additions to the STL ---------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -352,7 +352,7 @@ makeTransformRange(Range range, Operation op) {
}
/// An iterator that filters and transforms the results of an
-/// underlying forward iterator based on an transformation from the underlying
+/// underlying forward iterator based on a transformation from the underlying
/// value type to an optional result type.
///
/// \tparam Iterator the underlying iterator.
@@ -451,9 +451,9 @@ makeOptionalTransformIterator(Iterator current, Iterator end,
}
/// A range filtered and transformed by the optional transform.
-template
+template
class OptionalTransformRange {
- typedef typename Range::iterator Iterator;
Iterator First, Last;
OptionalTransform Op;
@@ -558,6 +558,21 @@ void sortUnique(
C.erase(std::unique(C.begin(), C.end()), C.end());
}
+/// Sorts and then uniques a container with random access iterators and an erase
+/// method that removes a range specified by random access iterators.
+template
+void sortUnique(
+ Container &C,
+ Comparator Cmp,
+ typename std::enable_if<
+ std::is_same::iterator_category,
+ std::random_access_iterator_tag>::value,
+ void>::type * = nullptr) {
+ std::sort(C.begin(), C.end(), Cmp);
+ C.erase(std::unique(C.begin(), C.end()), C.end());
+}
+
} // end namespace swift
#endif
diff --git a/include/swift/Basic/SourceLoc.h b/include/swift/Basic/SourceLoc.h
index 050033a0c64fc..debb69396b544 100644
--- a/include/swift/Basic/SourceLoc.h
+++ b/include/swift/Basic/SourceLoc.h
@@ -1,8 +1,8 @@
-//===- SourceLoc.h - Source Locations and Ranges ----------------*- C++ -*-===//
+//===--- SourceLoc.h - Source Locations and Ranges --------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/SourceManager.h b/include/swift/Basic/SourceManager.h
index 5ffbe7ab861a5..61ef42d40eb09 100644
--- a/include/swift/Basic/SourceManager.h
+++ b/include/swift/Basic/SourceManager.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/StringExtras.h b/include/swift/Basic/StringExtras.h
index 7d297ce92a0f0..7f3e81db5ddf9 100644
--- a/include/swift/Basic/StringExtras.h
+++ b/include/swift/Basic/StringExtras.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -28,6 +28,11 @@
#include
namespace swift {
+ /// Determine whether the given string can be an argument label.
+ ///
+ /// \seealso Token::canBeArgumentLabel()
+ bool canBeArgumentLabel(StringRef identifier);
+
/// Describes the kind of preposition a word is.
enum PrepositionKind {
PK_None = 0,
@@ -44,7 +49,6 @@ namespace swift {
Unknown,
Preposition,
Verb,
- AuxiliaryVerb,
Gerund,
};
diff --git a/include/swift/Basic/SuccessorMap.h b/include/swift/Basic/SuccessorMap.h
index 7cace7ae8e73f..bc186756de561 100644
--- a/include/swift/Basic/SuccessorMap.h
+++ b/include/swift/Basic/SuccessorMap.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -233,7 +233,7 @@ class SuccessorMap {
return foundUpperBound;
};
- // A heler to finish the operation, given that 'cur' is an upper bound.
+ // A helper to finish the operation, given that 'cur' is an upper bound.
auto finishWithUpperBound = [&] {
assert(cur->Left == nullptr);
return reassemble(true);
diff --git a/include/swift/Basic/TaskQueue.h b/include/swift/Basic/TaskQueue.h
index 2f0a8d2adde2f..27e9e6e2c597e 100644
--- a/include/swift/Basic/TaskQueue.h
+++ b/include/swift/Basic/TaskQueue.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/ThreadSafeRefCounted.h b/include/swift/Basic/ThreadSafeRefCounted.h
index 8bdc3d964e644..f519f7eb60883 100644
--- a/include/swift/Basic/ThreadSafeRefCounted.h
+++ b/include/swift/Basic/ThreadSafeRefCounted.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Timer.h b/include/swift/Basic/Timer.h
new file mode 100644
index 0000000000000..b3efe2f7c4cad
--- /dev/null
+++ b/include/swift/Basic/Timer.h
@@ -0,0 +1,50 @@
+//===--- Timer.h - Shared timers for compilation phases ---------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See http://swift.org/LICENSE.txt for license information
+// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_BASIC_TIMER_H
+#define SWIFT_BASIC_TIMER_H
+
+#include "swift/Basic/LLVM.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/Support/Timer.h"
+
+namespace swift {
+ /// A convenience class for declaring a timer that's part of the Swift
+ /// compilation timers group.
+ class SharedTimer {
+ enum class State {
+ Initial,
+ Skipped,
+ Enabled
+ };
+ static State CompilationTimersEnabled;
+
+ Optional Timer;
+
+ public:
+ explicit SharedTimer(StringRef name) {
+ if (CompilationTimersEnabled == State::Enabled)
+ Timer.emplace(name, StringRef("Swift compilation"));
+ else
+ CompilationTimersEnabled = State::Skipped;
+ }
+
+ /// Must be called before any SharedTimers have been created.
+ static void enableCompilationTimers() {
+ assert(CompilationTimersEnabled != State::Skipped &&
+ "a timer has already been created");
+ CompilationTimersEnabled = State::Enabled;
+ }
+ };
+}
+
+#endif // SWIFT_BASIC_TIMER_H
diff --git a/include/swift/Basic/TreeScopedHashTable.h b/include/swift/Basic/TreeScopedHashTable.h
index 7faa9a6a818d7..2d03b20aba501 100644
--- a/include/swift/Basic/TreeScopedHashTable.h
+++ b/include/swift/Basic/TreeScopedHashTable.h
@@ -1,8 +1,8 @@
-//===- TreeScopedHashTable.h - A scoped hash table with multiple active scopes -===//
+//===--- TreeScopedHashTable.h - Hash table with multiple active scopes ---===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/UUID.h b/include/swift/Basic/UUID.h
index efd7948f5a035..d88fd000dc8c4 100644
--- a/include/swift/Basic/UUID.h
+++ b/include/swift/Basic/UUID.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/Unicode.h b/include/swift/Basic/Unicode.h
index 7a4219284df20..988a4c0da8f32 100644
--- a/include/swift/Basic/Unicode.h
+++ b/include/swift/Basic/Unicode.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/ValueEnumerator.h b/include/swift/Basic/ValueEnumerator.h
new file mode 100644
index 0000000000000..2203304a9dcc8
--- /dev/null
+++ b/include/swift/Basic/ValueEnumerator.h
@@ -0,0 +1,58 @@
+//===--- ValueEnumerator.h --- Enumerates values ----------------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See http://swift.org/LICENSE.txt for license information
+// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_BASIC_VALUEENUMERATOR_H
+#define SWIFT_BASIC_VALUEENUMERATOR_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace swift {
+
+/// / This class maps values to unique indices.
+template
+class ValueEnumerator {
+ /// A running counter to enumerate values.
+ IndexTy counter;
+
+ /// Maps values to unique integers.
+ llvm::DenseMap ValueToIndex;
+
+public:
+ /// Return the index of value \p v.
+ IndexTy getIndex(const ValueTy &v) {
+ // Return the index of this Key, if we've assigned one already.
+ auto It = ValueToIndex.find(v);
+ if (It != ValueToIndex.end()) {
+ return It->second;
+ }
+
+ // Generate a new counter for the key.
+ ValueToIndex[v] = ++counter;
+ return counter;
+ }
+
+ ValueEnumerator() = default;
+
+ /// Forget about key \p v.
+ void invalidateValue(const ValueTy &v) { ValueToIndex.erase(v); }
+
+ /// Clear the enumeration state of the
+ void clear() {
+ ValueToIndex.clear();
+ counter = 0;
+ }
+};
+
+} // end namespace swift
+
+#endif
diff --git a/include/swift/Basic/Version.h b/include/swift/Basic/Version.h
index b4ffcb6e84e4a..e6fc2313baf98 100644
--- a/include/swift/Basic/Version.h
+++ b/include/swift/Basic/Version.h
@@ -1,8 +1,8 @@
-//===- Version.h - Swift Version Number -------------------------*- C++ -*-===//
+//===--- Version.h - Swift Version Number -----------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Basic/type_traits.h b/include/swift/Basic/type_traits.h
index 1270bb5402c71..8aee295aa6de8 100644
--- a/include/swift/Basic/type_traits.h
+++ b/include/swift/Basic/type_traits.h
@@ -1,8 +1,8 @@
-//===--- type_traits.h - Type traits -----------------------------*- C++ -*-==//
+//===--- type_traits.h - Type traits ----------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -22,7 +22,7 @@
namespace swift {
-/// Same as \c std::is_trivially_copyable, which we can not use directly
+/// Same as \c std::is_trivially_copyable, which we cannot use directly
/// because it is not implemented yet in all C++11 standard libraries.
///
/// Unlike \c llvm::isPodLike, this trait should produce a precise result and
diff --git a/include/swift/ClangImporter/BuiltinMappedTypes.def b/include/swift/ClangImporter/BuiltinMappedTypes.def
index 9fd1b2e0a420b..00825c8d8187b 100644
--- a/include/swift/ClangImporter/BuiltinMappedTypes.def
+++ b/include/swift/ClangImporter/BuiltinMappedTypes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/ClangImporter/ClangImporter.h b/include/swift/ClangImporter/ClangImporter.h
index 8720ea5716573..cb4a65a0d1519 100644
--- a/include/swift/ClangImporter/ClangImporter.h
+++ b/include/swift/ClangImporter/ClangImporter.h
@@ -1,8 +1,8 @@
-//===--- ClangImporter.cpp - Import Clang Modules --------------*- C++ -*--===//
+//===--- ClangImporter.h - Import Clang Modules -----------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -114,14 +114,7 @@ class ClangImporter final : public ClangModuleLoader {
/// \brief Look for declarations associated with the given name.
///
/// \param name The name we're searching for.
- void lookupValue(Identifier name, VisibleDeclConsumer &consumer);
-
- /// \brief Look for visible declarations in the Clang translation unit and
- /// import them as Swift decls.
- ///
- /// \param Consumer The VisibleDeclConsumer that will be fed decls as they
- /// are found and imported.
- void lookupVisibleDecls(VisibleDeclConsumer &Consumer) const;
+ void lookupValue(DeclName name, VisibleDeclConsumer &consumer);
/// Look for textually included declarations from the bridging header.
///
diff --git a/include/swift/ClangImporter/ClangImporterOptions.h b/include/swift/ClangImporter/ClangImporterOptions.h
index b15d8ab6a0ead..506dfc0a00a64 100644
--- a/include/swift/ClangImporter/ClangImporterOptions.h
+++ b/include/swift/ClangImporter/ClangImporterOptions.h
@@ -1,8 +1,8 @@
-//===-- ClangImporterOptions.h ---------------------------------*- C++ -*--===//
+//===--- ClangImporterOptions.h ---------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -53,10 +53,6 @@ class ClangImporterOptions {
/// generation.
bool DetailedPreprocessingRecord = false;
- /// If true, matched getter-like and setter-like methods will be imported as
- /// properties.
- bool InferImplicitProperties = false;
-
/// If true, Clang diagnostics will be dumped to stderr using Clang's
/// diagnostic printer as well as being passed to Swift's diagnostic engine.
bool DumpClangDiagnostics = false;
diff --git a/include/swift/ClangImporter/ClangModule.h b/include/swift/ClangImporter/ClangModule.h
index e797db9ac64f9..8fcc9f53654a4 100644
--- a/include/swift/ClangImporter/ClangModule.h
+++ b/include/swift/ClangImporter/ClangModule.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/ClangImporter/SIMDMappedTypes.def b/include/swift/ClangImporter/SIMDMappedTypes.def
index 814f555d9beb5..d020788ae169f 100644
--- a/include/swift/ClangImporter/SIMDMappedTypes.def
+++ b/include/swift/ClangImporter/SIMDMappedTypes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Config.h.in b/include/swift/Config.h.in
index a60eeb78487a2..263e3086c5724 100644
--- a/include/swift/Config.h.in
+++ b/include/swift/Config.h.in
@@ -1,5 +1,5 @@
// This file is processed by CMake.
-// See http://www.cmake.org/cmake/help/v3.0/command/configure_file.html.
+// See https://cmake.org/cmake/help/v3.0/command/configure_file.html.
#ifndef SWIFT_CONFIG_H
#define SWIFT_CONFIG_H
diff --git a/include/swift/Driver/Action.h b/include/swift/Driver/Action.h
index 0104c4138916a..937de8acb7549 100644
--- a/include/swift/Driver/Action.h
+++ b/include/swift/Driver/Action.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -38,6 +38,7 @@ class Action {
enum ActionClass {
Input = 0,
CompileJob,
+ InterpretJob,
BackendJob,
MergeModuleJob,
ModuleWrapJob,
@@ -164,6 +165,19 @@ class CompileJobAction : public JobAction {
}
};
+class InterpretJobAction : public JobAction {
+private:
+ virtual void anchor();
+
+public:
+ explicit InterpretJobAction()
+ : JobAction(Action::InterpretJob, llvm::None, types::TY_Nothing) {}
+
+ static bool classof(const Action *A) {
+ return A->getKind() == Action::InterpretJob;
+ }
+};
+
class BackendJobAction : public JobAction {
private:
virtual void anchor();
diff --git a/include/swift/Driver/Compilation.h b/include/swift/Driver/Compilation.h
index 1c97b80ba9eab..fbd662ba2b067 100644
--- a/include/swift/Driver/Compilation.h
+++ b/include/swift/Driver/Compilation.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Driver/DependencyGraph.h b/include/swift/Driver/DependencyGraph.h
index b6c786b16cb1a..6348f7009424e 100644
--- a/include/swift/Driver/DependencyGraph.h
+++ b/include/swift/Driver/DependencyGraph.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -94,7 +94,7 @@ class DependencyGraphImpl {
static_assert(std::is_move_constructible::value, "");
/// The "outgoing" edge map. This lists all outgoing (kind, string) edges
- /// representing satisified dependencies from a particular node.
+ /// representing satisfied dependencies from a particular node.
///
/// For multiple outgoing edges with the same string, the kinds are combined
/// into one field.
diff --git a/include/swift/Driver/Driver.h b/include/swift/Driver/Driver.h
index 3057df7e30665..44973ade3a0b1 100644
--- a/include/swift/Driver/Driver.h
+++ b/include/swift/Driver/Driver.h
@@ -1,8 +1,8 @@
-//===-- Driver.h - Swift compiler driver -----------------------*- C++ -*--===//
+//===--- Driver.h - Swift compiler driver -----------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Driver/FrontendUtil.h b/include/swift/Driver/FrontendUtil.h
index 5e9791840936b..cb18368c8f379 100644
--- a/include/swift/Driver/FrontendUtil.h
+++ b/include/swift/Driver/FrontendUtil.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Driver/Job.h b/include/swift/Driver/Job.h
index 69a88d8790c80..c3f4c069c008d 100644
--- a/include/swift/Driver/Job.h
+++ b/include/swift/Driver/Job.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -87,6 +87,8 @@ class Job {
NewlyAdded
};
+ using EnvironmentVector = std::vector>;
+
private:
/// The action which caused the creation of this Job, and the conditions
/// under which it must be run.
@@ -103,8 +105,15 @@ class Job {
/// The list of program arguments (not including the implicit first argument,
/// which will be the Executable).
+ ///
+ /// These argument strings must be kept alive as long as the Job is alive.
llvm::opt::ArgStringList Arguments;
+ /// Additional variables to set in the process environment when running.
+ ///
+ /// These strings must be kept alive as long as the Job is alive.
+ EnvironmentVector ExtraEnvironment;
+
/// The modification time of the main input file, if any.
llvm::sys::TimeValue InputModTime = llvm::sys::TimeValue::MaxTime();
@@ -113,10 +122,12 @@ class Job {
SmallVectorImpl &&Inputs,
std::unique_ptr Output,
const char *Executable,
- llvm::opt::ArgStringList Arguments)
+ llvm::opt::ArgStringList Arguments,
+ EnvironmentVector ExtraEnvironment = {})
: SourceAndCondition(&Source, Condition::Always),
Inputs(std::move(Inputs)), Output(std::move(Output)),
- Executable(Executable), Arguments(std::move(Arguments)) {}
+ Executable(Executable), Arguments(std::move(Arguments)),
+ ExtraEnvironment(std::move(ExtraEnvironment)) {}
const Action &getSource() const { return *SourceAndCondition.getPointer(); }
@@ -141,10 +152,21 @@ class Job {
return InputModTime;
}
+ ArrayRef> getExtraEnvironment() const {
+ return ExtraEnvironment;
+ }
+
/// Print the command line for this Job to the given \p stream,
/// terminating output with the given \p terminator.
void printCommandLine(raw_ostream &Stream, StringRef Terminator = "\n") const;
+ /// Print the command line for this Job to the given \p stream,
+ /// and include any extra environment variables that will be set.
+ ///
+ /// \sa printCommandLine
+ void printCommandLineAndEnvironment(raw_ostream &Stream,
+ StringRef Terminator = "\n") const;
+
void dump() const LLVM_ATTRIBUTE_USED;
static void printArguments(raw_ostream &Stream,
diff --git a/include/swift/Driver/OutputFileMap.h b/include/swift/Driver/OutputFileMap.h
index 4afe6d8eb835f..fe6ff7cbaa76e 100644
--- a/include/swift/Driver/OutputFileMap.h
+++ b/include/swift/Driver/OutputFileMap.h
@@ -1,8 +1,8 @@
-//===-- OutputFileMap.h - Driver output file map ---------------*- C++ -*--===//
+//===--- OutputFileMap.h - Driver output file map ---------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Driver/ParseableOutput.h b/include/swift/Driver/ParseableOutput.h
index 6064a97e29221..d878614a0be2c 100644
--- a/include/swift/Driver/ParseableOutput.h
+++ b/include/swift/Driver/ParseableOutput.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Driver/ToolChain.h b/include/swift/Driver/ToolChain.h
index 65321c261934e..975bda6f352bc 100644
--- a/include/swift/Driver/ToolChain.h
+++ b/include/swift/Driver/ToolChain.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -58,30 +58,44 @@ class ToolChain {
const OutputInfo &OI;
};
- virtual std::pair
+ /// Packs together information chosen by toolchains to create jobs.
+ struct InvocationInfo {
+ const char *ExecutableName;
+ llvm::opt::ArgStringList Arguments;
+ std::vector> ExtraEnvironment;
+
+ InvocationInfo(const char *name, llvm::opt::ArgStringList args,
+ decltype(ExtraEnvironment) extraEnv = {})
+ : ExecutableName(name), Arguments(args), ExtraEnvironment(extraEnv) {}
+ };
+
+ virtual InvocationInfo
constructInvocation(const CompileJobAction &job,
const JobContext &context) const;
- virtual std::pair
+ virtual InvocationInfo
+ constructInvocation(const InterpretJobAction &job,
+ const JobContext &context) const;
+ virtual InvocationInfo
constructInvocation(const BackendJobAction &job,
const JobContext &context) const;
- virtual std::pair
+ virtual InvocationInfo
constructInvocation(const MergeModuleJobAction &job,
const JobContext &context) const;
- virtual std::pair
+ virtual InvocationInfo
constructInvocation(const ModuleWrapJobAction &job,
const JobContext &context) const;
- virtual std::pair
+ virtual InvocationInfo
constructInvocation(const REPLJobAction &job,
const JobContext &context) const;
- virtual std::pair
+ virtual InvocationInfo
constructInvocation(const GenerateDSYMJobAction &job,
const JobContext &context) const;
- virtual std::pair
+ virtual InvocationInfo
constructInvocation(const AutolinkExtractJobAction &job,
const JobContext &context) const;
- virtual std::pair
+ virtual InvocationInfo
constructInvocation(const LinkJobAction &job,
const JobContext &context) const;
@@ -117,7 +131,7 @@ class ToolChain {
const llvm::opt::ArgList &args,
const OutputInfo &OI) const;
- /// Return the default langauge type to use for the given extension.
+ /// Return the default language type to use for the given extension.
virtual types::ID lookupTypeForExtension(StringRef Ext) const;
};
} // end namespace driver
diff --git a/include/swift/Driver/Types.def b/include/swift/Driver/Types.def
index 0a6027c70b780..5b01b5f3ba252 100644
--- a/include/swift/Driver/Types.def
+++ b/include/swift/Driver/Types.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Driver/Types.h b/include/swift/Driver/Types.h
index 77e788c299332..c219510af3e1f 100644
--- a/include/swift/Driver/Types.h
+++ b/include/swift/Driver/Types.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -75,7 +75,7 @@ namespace llvm {
}
template
-void swift::driver::types::forAllTypes(const Fn &fn) {
+void swift::driver::types::forAllTypes(const Fn &fn) {
static_assert(std::is_constructible,Fn>::value,
"must have the signature 'void(types::ID)'");
for (uint8_t i = 0; i < static_cast(TY_INVALID); ++i)
diff --git a/include/swift/Driver/Util.h b/include/swift/Driver/Util.h
index ef5b7e7ea32ec..6af4b8d353b72 100644
--- a/include/swift/Driver/Util.h
+++ b/include/swift/Driver/Util.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Frontend/DiagnosticVerifier.h b/include/swift/Frontend/DiagnosticVerifier.h
index 18b9f25d4283d..0ec8ea152c1c3 100644
--- a/include/swift/Frontend/DiagnosticVerifier.h
+++ b/include/swift/Frontend/DiagnosticVerifier.h
@@ -1,8 +1,8 @@
-//===- DiagnosticVerifier.h - Diagnostic Verifier (-verify) -----*- C++ -*-===//
+//===--- DiagnosticVerifier.h - Diagnostic Verifier (-verify) ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Frontend/Frontend.h b/include/swift/Frontend/Frontend.h
index 8c25b9336ddf6..4e08cad86a3bd 100644
--- a/include/swift/Frontend/Frontend.h
+++ b/include/swift/Frontend/Frontend.h
@@ -1,8 +1,8 @@
-//===-- Frontend.h - frontend utility methods ------------------*- C++ -*--===//
+//===--- Frontend.h - frontend utility methods ------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Frontend/FrontendOptions.h b/include/swift/Frontend/FrontendOptions.h
index 4e36b180035c3..baed3cf849b51 100644
--- a/include/swift/Frontend/FrontendOptions.h
+++ b/include/swift/Frontend/FrontendOptions.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -166,6 +166,12 @@ class FrontendOptions {
/// If set, dumps wall time taken to check each function body to llvm::errs().
bool DebugTimeFunctionBodies = false;
+ /// If set, prints the time taken in each major compilation phase to
+ /// llvm::errs().
+ ///
+ /// \sa swift::SharedTimer
+ bool DebugTimeCompilation = false;
+
/// Indicates whether function body parsing should be delayed
/// until the end of all files.
bool DelayedFunctionBodyParsing = false;
diff --git a/include/swift/Frontend/PrintingDiagnosticConsumer.h b/include/swift/Frontend/PrintingDiagnosticConsumer.h
index 14f2ce7f3609a..e714f9d76ce0b 100644
--- a/include/swift/Frontend/PrintingDiagnosticConsumer.h
+++ b/include/swift/Frontend/PrintingDiagnosticConsumer.h
@@ -1,8 +1,8 @@
-//===- PrintingDiagnosticConsumer.h - Print Text Diagnostics ----*- C++ -*-===//
+//===--- PrintingDiagnosticConsumer.h - Print Text Diagnostics --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Frontend/SerializedDiagnosticConsumer.h b/include/swift/Frontend/SerializedDiagnosticConsumer.h
index ad866121f0e56..296b0547c2cc7 100644
--- a/include/swift/Frontend/SerializedDiagnosticConsumer.h
+++ b/include/swift/Frontend/SerializedDiagnosticConsumer.h
@@ -1,8 +1,8 @@
-//===- SerializedDiagnosticConsumer.h - Serialize Diagnostics --*- C++ -*--===//
+//===--- SerializedDiagnosticConsumer.h - Serialize Diagnostics -*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/IDE/CodeCompletion.h b/include/swift/IDE/CodeCompletion.h
index f55b6913fd136..716a78414d402 100644
--- a/include/swift/IDE/CodeCompletion.h
+++ b/include/swift/IDE/CodeCompletion.h
@@ -1,8 +1,8 @@
-//===- CodeCompletion.h - Routines for code completion --------------------===//
+//===--- CodeCompletion.h - Routines for code completion ------------------===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -266,13 +266,13 @@ class CodeCompletionString {
}
static Chunk createWithText(ChunkKind Kind, unsigned NestingLevel,
- StringRef Text, bool isAnnoation = false) {
- return Chunk(Kind, NestingLevel, Text, isAnnoation);
+ StringRef Text, bool isAnnotation = false) {
+ return Chunk(Kind, NestingLevel, Text, isAnnotation);
}
static Chunk createSimple(ChunkKind Kind, unsigned NestingLevel,
- bool isAnnoation = false) {
- return Chunk(Kind, NestingLevel, isAnnoation);
+ bool isAnnotation = false) {
+ return Chunk(Kind, NestingLevel, isAnnotation);
}
};
@@ -701,7 +701,7 @@ class CodeCompletionContext {
/// \brief Return current code completion results.
MutableArrayRef takeResults();
- /// \brief Sort code completion results in an implementetion-defined order
+ /// \brief Sort code completion results in an implementation-defined order
/// in place.
static void sortCompletionResults(
MutableArrayRef Results);
@@ -732,7 +732,7 @@ struct SimpleCachingCodeCompletionConsumer : public CodeCompletionConsumer {
ArrayRef requestedModules,
DeclContext *DCForModules) override;
- /// Clients should overrride this method to receive \p Results.
+ /// Clients should override this method to receive \p Results.
virtual void handleResults(
MutableArrayRef Results) = 0;
};
diff --git a/include/swift/IDE/CodeCompletionCache.h b/include/swift/IDE/CodeCompletionCache.h
index c7fa9c441e592..14e0b7c79fc61 100644
--- a/include/swift/IDE/CodeCompletionCache.h
+++ b/include/swift/IDE/CodeCompletionCache.h
@@ -1,8 +1,8 @@
-//===- CodeCompletionCache.h - Routines for code completion caching -------===//
+//===--- CodeCompletionCache.h - Routines for code completion caching -----===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/IDE/CommentConversion.h b/include/swift/IDE/CommentConversion.h
index 99594c76a2ee2..af87e4aa8844a 100644
--- a/include/swift/IDE/CommentConversion.h
+++ b/include/swift/IDE/CommentConversion.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/IDE/ModuleInterfacePrinting.h b/include/swift/IDE/ModuleInterfacePrinting.h
index 937a64a15d4d1..26d80e9740757 100644
--- a/include/swift/IDE/ModuleInterfacePrinting.h
+++ b/include/swift/IDE/ModuleInterfacePrinting.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/IDE/REPLCodeCompletion.h b/include/swift/IDE/REPLCodeCompletion.h
index f58cb29fd6ac7..834a3d77fd417 100644
--- a/include/swift/IDE/REPLCodeCompletion.h
+++ b/include/swift/IDE/REPLCodeCompletion.h
@@ -1,8 +1,8 @@
-//===--- REPLCodeCompletion.h - Code completion for REPL ----------* C++ *-===//
+//===--- REPLCodeCompletion.h - Code completion for REPL --------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/IDE/SourceEntityWalker.h b/include/swift/IDE/SourceEntityWalker.h
index 4f74a48e10a9f..b604e60a488dc 100644
--- a/include/swift/IDE/SourceEntityWalker.h
+++ b/include/swift/IDE/SourceEntityWalker.h
@@ -1,8 +1,8 @@
-//===- SourceEntityWalker.h - Routines for semantic source info -----------===//
+//===--- SourceEntityWalker.h - Routines for semantic source info ---------===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/IDE/SyntaxModel.h b/include/swift/IDE/SyntaxModel.h
index ccdcd6f67b487..df5eafedccc75 100644
--- a/include/swift/IDE/SyntaxModel.h
+++ b/include/swift/IDE/SyntaxModel.h
@@ -1,8 +1,8 @@
-//===- SyntaxModel.h - Routines for IDE syntax model ---------------------===//
+//===--- SyntaxModel.h - Routines for IDE syntax model -------------------===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/IDE/Utils.h b/include/swift/IDE/Utils.h
index e4552dfec4c30..f906b35259c7a 100644
--- a/include/swift/IDE/Utils.h
+++ b/include/swift/IDE/Utils.h
@@ -1,8 +1,8 @@
-//===- Utils.h - Misc utilities -------------------------------------------===//
+//===--- Utils.h - Misc utilities -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -54,7 +54,7 @@ struct SourceCompleteResult {
// The text to use as the indent string when auto indenting the next line.
// This will contain the exactly what the client typed (any whitespaces and
// tabs) and can be used to indent subsequent lines. It does not include
- // the current indent level, IDE clients should insert the currect indentation
+ // the current indent level, IDE clients should insert the correct indentation
// with spaces or tabs to account for the current indent level. The indent
// prefix will contain the leading space characters of the line that
// contained the '{', '(' or '[' character that was unbalanced.
diff --git a/include/swift/Immediate/Immediate.h b/include/swift/Immediate/Immediate.h
index 6027ea076319d..101aeb416f338 100644
--- a/include/swift/Immediate/Immediate.h
+++ b/include/swift/Immediate/Immediate.h
@@ -1,8 +1,8 @@
-//===-- Immediate.h - Entry point for swift immediate mode -----*- C++ -*--===//
+//===--- Immediate.h - Entry point for swift immediate mode -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/LLVMPasses/Passes.h b/include/swift/LLVMPasses/Passes.h
index d53d69b17f910..0d2f06ea1791e 100644
--- a/include/swift/LLVMPasses/Passes.h
+++ b/include/swift/LLVMPasses/Passes.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/LLVMPasses/PassesFwd.h b/include/swift/LLVMPasses/PassesFwd.h
index f1dcdb6eabb07..3b9500dc151bf 100644
--- a/include/swift/LLVMPasses/PassesFwd.h
+++ b/include/swift/LLVMPasses/PassesFwd.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Markup/AST.h b/include/swift/Markup/AST.h
index 0238e16fe5abd..11357a32c26da 100644
--- a/include/swift/Markup/AST.h
+++ b/include/swift/Markup/AST.h
@@ -1,8 +1,8 @@
-//===--- AST.h - Markup AST nodes ---------------------------------------===//
+//===--- AST.h - Markup AST nodes -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -199,15 +199,19 @@ class Item final : public MarkupASTNode {
class CodeBlock final : public MarkupASTNode {
StringRef LiteralContent;
+ StringRef Language;
- CodeBlock(StringRef LiteralContent)
+ CodeBlock(StringRef LiteralContent, StringRef Language)
: MarkupASTNode(ASTNodeKind::CodeBlock),
- LiteralContent(LiteralContent) {}
+ LiteralContent(LiteralContent),
+ Language(Language) {}
public:
- static CodeBlock *create(MarkupContext &MC, StringRef LiteralContent);
+ static CodeBlock *create(MarkupContext &MC, StringRef LiteralContent,
+ StringRef Language);
StringRef getLiteralContent() const { return LiteralContent; };
+ StringRef getLanguage() const { return Language; };
ArrayRef getChildren() const {
return {};
diff --git a/include/swift/Markup/ASTNodes.def b/include/swift/Markup/ASTNodes.def
index df95413c3f475..b1330bb66ceaa 100644
--- a/include/swift/Markup/ASTNodes.def
+++ b/include/swift/Markup/ASTNodes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Markup/LineList.h b/include/swift/Markup/LineList.h
index 539df74a07587..518264bbe8f8b 100644
--- a/include/swift/Markup/LineList.h
+++ b/include/swift/Markup/LineList.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Markup/Markup.h b/include/swift/Markup/Markup.h
index ace38deee7b63..86640c04f3c21 100644
--- a/include/swift/Markup/Markup.h
+++ b/include/swift/Markup/Markup.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Markup/SimpleFields.def b/include/swift/Markup/SimpleFields.def
index 18a03036b80c9..6ccd4b526869a 100644
--- a/include/swift/Markup/SimpleFields.def
+++ b/include/swift/Markup/SimpleFields.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -14,7 +14,7 @@
// These definitions automatically generate the classes and XML printing
// facilities.
//
-// There must be a correspnding definition of these nodes
+// There must be a corresponding definition of these nodes
// in include/swift/Markup/ASTNodes.def.
//
//===----------------------------------------------------------------------===//
diff --git a/include/swift/Markup/SourceLoc.h b/include/swift/Markup/SourceLoc.h
index 57db0d91f6813..4b383b30917d4 100644
--- a/include/swift/Markup/SourceLoc.h
+++ b/include/swift/Markup/SourceLoc.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Markup/XMLUtils.h b/include/swift/Markup/XMLUtils.h
index 1d3977b705b76..86540acb9bb18 100644
--- a/include/swift/Markup/XMLUtils.h
+++ b/include/swift/Markup/XMLUtils.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Option/FrontendOptions.td b/include/swift/Option/FrontendOptions.td
index cfa1cdc98cefe..b9c600aa647af 100644
--- a/include/swift/Option/FrontendOptions.td
+++ b/include/swift/Option/FrontendOptions.td
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -124,6 +124,8 @@ def debug_forbid_typecheck_prefix : Separate<["-"], "debug-forbid-typecheck-pref
HelpText<"Triggers llvm fatal_error if typechecker tries to typecheck a decl "
"with the provided prefix name">;
+def debug_time_compilation : Flag<["-"], "debug-time-compilation">,
+ HelpText<"Prints the time taken by each compilation phase">;
def debug_time_function_bodies : Flag<["-"], "debug-time-function-bodies">,
HelpText<"Dumps the time it takes to type-check each function body">;
@@ -142,6 +144,9 @@ def debugger_support : Flag<["-"], "debugger-support">,
def disable_arc_opts : Flag<["-"], "disable-arc-opts">,
HelpText<"Don't run SIL ARC optimization passes.">;
+def enable_guaranteed_closure_contexts : Flag<["-"], "enable-guaranteed-closure-contexts">,
+ HelpText<"Use @guaranteed convention for closure context">;
+
def remove_runtime_asserts : Flag<["-"], "remove-runtime-asserts">,
HelpText<"Remove runtime asserts.">;
@@ -187,6 +192,9 @@ def dump_clang_diagnostics : Flag<["-"], "dump-clang-diagnostics">,
def emit_verbose_sil : Flag<["-"], "emit-verbose-sil">,
HelpText<"Emit locations during SIL emission">;
+def use_native_super_method : Flag<["-"], "use-native-super-method">,
+ HelpText<"Use super_method for super calls in native classes">;
+
def disable_self_type_mangling : Flag<["-"], "disable-self-type-mangling">,
HelpText<"Disable including Self type in method type manglings">;
@@ -197,10 +205,6 @@ def disable_availability_checking : Flag<["-"],
"disable-availability-checking">,
HelpText<"Disable checking for potentially unavailable APIs">;
-def enable_objc_implicit_properties :
- Flag<["-"], "enable-objc-implicit-properties">,
- HelpText<"Import Objective-C \"implicit properties\" as properties">;
-
def enable_omit_needless_words :
Flag<["-"], "enable-omit-needless-words">,
HelpText<"Omit needless words when importing Objective-C names">;
@@ -209,6 +213,10 @@ def enable_infer_default_arguments :
Flag<["-"], "enable-infer-default-arguments">,
HelpText<"Infer default arguments for imported parameters">;
+def enable_swift_name_lookup_tables :
+ Flag<["-"], "enable-swift-name-lookup-tables">,
+ HelpText<"Enable Swift name lookup tables in the Clang importer">;
+
def warn_omit_needless_words :
Flag<["-"], "Womit-needless-words">,
HelpText<"Warn about needless words in names">;
diff --git a/include/swift/Option/Options.h b/include/swift/Option/Options.h
index a46922eacfcb0..5a29259e1dc95 100644
--- a/include/swift/Option/Options.h
+++ b/include/swift/Option/Options.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Option/Options.td b/include/swift/Option/Options.td
index 1ade695a92ab1..117e573c1c63a 100644
--- a/include/swift/Option/Options.td
+++ b/include/swift/Option/Options.td
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Parse/CodeCompletionCallbacks.h b/include/swift/Parse/CodeCompletionCallbacks.h
index 58dc1c8ad1d55..3b36640c92f0b 100644
--- a/include/swift/Parse/CodeCompletionCallbacks.h
+++ b/include/swift/Parse/CodeCompletionCallbacks.h
@@ -1,8 +1,8 @@
-//===- CodeCompletionCallbacks.h - Parser's interface to code completion --===//
+//===--- CodeCompletionCallbacks.h - Parser's interface to code completion ===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Parse/DelayedParsingCallbacks.h b/include/swift/Parse/DelayedParsingCallbacks.h
index 05e5987806569..a1ea0031baa8d 100644
--- a/include/swift/Parse/DelayedParsingCallbacks.h
+++ b/include/swift/Parse/DelayedParsingCallbacks.h
@@ -1,8 +1,8 @@
-//===- DelayedParsingCallbacks.h - Callbacks for Parser's delayed parsing -===//
+//===--- DelayedParsingCallbacks.h - Delayed parsing callbacks ------------===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Parse/Lexer.h b/include/swift/Parse/Lexer.h
index b1b01802b9092..bc78a6bf70ef4 100644
--- a/include/swift/Parse/Lexer.h
+++ b/include/swift/Parse/Lexer.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -240,8 +240,17 @@ class Lexer {
restoreState(S);
}
+ /// \brief Retrieve the Token referred to by \c Loc.
+ ///
+ /// \param SM The source manager in which the given source location
+ /// resides.
+ ///
+ /// \param Loc The source location of the beginning of a token.
+ static Token getTokenAtLocation(const SourceManager &SM, SourceLoc Loc);
+
+
/// \brief Retrieve the source location that points just past the
- /// end of the token refered to by \c Loc.
+ /// end of the token referred to by \c Loc.
///
/// \param SM The source manager in which the given source location
/// resides.
@@ -255,8 +264,9 @@ class Lexer {
/// resides.
///
/// \param SR The source range
- static CharSourceRange getCharSourceRangeFromSourceRange(const SourceManager &SM,
- const SourceRange &SR) {
+ static CharSourceRange
+ getCharSourceRangeFromSourceRange(const SourceManager &SM,
+ const SourceRange &SR) {
return CharSourceRange(SM, SR.Start, getLocForEndOfToken(SM, SR.End));
}
@@ -299,6 +309,10 @@ class Lexer {
/// reserved word.
static tok kindOfIdentifier(StringRef Str, bool InSILMode);
+ /// \brief Determines if the given string is a valid operator identifier,
+ /// without escaping characters.
+ static bool isOperator(StringRef string);
+
SourceLoc getLocForStartOfBuffer() const {
return SourceLoc(llvm::SMLoc::getFromPointer(BufferStart));
}
diff --git a/include/swift/Parse/LocalContext.h b/include/swift/Parse/LocalContext.h
index 8bdc36e4759ee..9615b0fc094e7 100644
--- a/include/swift/Parse/LocalContext.h
+++ b/include/swift/Parse/LocalContext.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Parse/Parser.h b/include/swift/Parse/Parser.h
index 3b3468ef4831d..0c22729abf5d6 100644
--- a/include/swift/Parse/Parser.h
+++ b/include/swift/Parse/Parser.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -83,7 +83,7 @@ class Parser {
DeclContext *CurDeclContext;
ASTContext &Context;
CodeCompletionCallbacks *CodeCompletion = nullptr;
- std::vector>> AnonClosureVars;
+ std::vector>> AnonClosureVars;
bool IsParsingInterfaceTokens = false;
@@ -760,18 +760,18 @@ class Parser {
void record(Parser &P, AbstractStorageDecl *storage, bool invalid,
ParseDeclOptions flags, SourceLoc staticLoc,
const DeclAttributes &attrs,
- TypeLoc elementTy, Pattern *indices,
+ TypeLoc elementTy, ParameterList *indices,
SmallVectorImpl &decls);
};
bool parseGetSetImpl(ParseDeclOptions Flags,
- Pattern *Indices, TypeLoc ElementTy,
+ ParameterList *Indices, TypeLoc ElementTy,
ParsedAccessors &accessors,
SourceLoc &LastValidLoc,
SourceLoc StaticLoc, SourceLoc VarLBLoc,
SmallVectorImpl &Decls);
bool parseGetSet(ParseDeclOptions Flags,
- Pattern *Indices, TypeLoc ElementTy,
+ ParameterList *Indices, TypeLoc ElementTy,
ParsedAccessors &accessors,
SourceLoc StaticLoc, SmallVectorImpl &Decls);
void recordAccessors(AbstractStorageDecl *storage, ParseDeclOptions flags,
@@ -803,6 +803,7 @@ class Parser {
parseDeclDeinit(ParseDeclOptions Flags, DeclAttributes &Attributes);
void addPatternVariablesToScope(ArrayRef Patterns);
+ void addParametersToScope(ParameterList *PL);
ParserResult parseDeclOperator(ParseDeclOptions Flags,
DeclAttributes &Attributes);
@@ -859,7 +860,7 @@ class Parser {
ParserResult parseTypeComposition();
ParserResult parseTypeTupleBody();
- ParserResult parseTypeArray(TypeRepr *Base);
+ ParserResult parseTypeArray(TypeRepr *Base);
/// Parse a collection type.
/// type-simple:
@@ -900,8 +901,8 @@ class Parser {
/// function.
void setFunctionContext(DeclContext *DC);
- DefaultArgumentInfo() {
- NextIndex = 0;
+ DefaultArgumentInfo(bool inTypeContext) {
+ NextIndex = inTypeContext ? 1 : 0;
HasDefaultArgument = false;
}
};
@@ -922,10 +923,6 @@ class Parser {
};
SpecifierKindTy SpecifierKind = Let; // Defaults to let.
-
- /// The location of the back-tick preceding the first name, if any.
- SourceLoc PoundLoc;
-
/// The location of the first name.
///
/// \c FirstName is the name.
@@ -997,23 +994,23 @@ class Parser {
DefaultArgumentInfo *defaultArgs,
ParameterContextKind paramContext);
- ParserResult parseSingleParameterClause(
+ ParserResult parseSingleParameterClause(
ParameterContextKind paramContext,
SmallVectorImpl *namePieces = nullptr);
ParserStatus parseFunctionArguments(SmallVectorImpl &NamePieces,
- SmallVectorImpl &BodyPatterns,
+ SmallVectorImpl &BodyParams,
ParameterContextKind paramContext,
DefaultArgumentInfo &defaultArgs);
ParserStatus parseFunctionSignature(Identifier functionName,
DeclName &fullName,
- SmallVectorImpl &bodyPatterns,
+ SmallVectorImpl &bodyParams,
DefaultArgumentInfo &defaultArgs,
SourceLoc &throws,
bool &rethrows,
TypeRepr *&retType);
ParserStatus parseConstructorArguments(DeclName &FullName,
- Pattern *&BodyPattern,
+ ParameterList *&BodyParams,
DefaultArgumentInfo &defaultArgs);
//===--------------------------------------------------------------------===//
@@ -1137,7 +1134,7 @@ class Parser {
/// \returns true if an error occurred, false otherwise.
bool parseClosureSignatureIfPresent(
SmallVectorImpl &captureList,
- Pattern *¶ms,
+ ParameterList *¶ms,
SourceLoc &throwsLoc,
SourceLoc &arrowLoc,
TypeRepr *&explicitResultType,
diff --git a/include/swift/Parse/ParserResult.h b/include/swift/Parse/ParserResult.h
index ef42b3cd82ff1..42ce7f0d53b1d 100644
--- a/include/swift/Parse/ParserResult.h
+++ b/include/swift/Parse/ParserResult.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -49,7 +49,7 @@ template class ParserResult {
/// Construct a successful parser result.
explicit ParserResult(T *Result) : PtrAndBits(Result) {
- assert(Result && "a successful parser result can not be null");
+ assert(Result && "a successful parser result cannot be null");
}
/// Convert from a different but compatible parser result.
@@ -125,8 +125,8 @@ static inline ParserResult makeParserCodeCompletionResult(T *Result =
/// \brief Same as \c ParserResult, but just the status bits without the AST
/// node.
///
-/// Useful when the AST node is returned by some other means (for example, a in
-/// vector out parameter).
+/// Useful when the AST node is returned by some other means (for example, in
+/// a vector out parameter).
///
/// If you want to use 'bool' as a result type in the Parser, consider using
/// ParserStatus instead.
diff --git a/include/swift/Parse/PersistentParserState.h b/include/swift/Parse/PersistentParserState.h
index 4c20d0ab0557c..8971ee1ab25f7 100644
--- a/include/swift/Parse/PersistentParserState.h
+++ b/include/swift/Parse/PersistentParserState.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Parse/Scope.h b/include/swift/Parse/Scope.h
index d375e4a59ba3e..cafd90bef6c91 100644
--- a/include/swift/Parse/Scope.h
+++ b/include/swift/Parse/Scope.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Parse/Token.h b/include/swift/Parse/Token.h
index 5cc1f18ee14e9..8c7a6630b840a 100644
--- a/include/swift/Parse/Token.h
+++ b/include/swift/Parse/Token.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -190,6 +190,22 @@ class Token {
return isAnyOperator() && Text == ContextPunc;
}
+ /// Determine whether the token can be an argument label.
+ ///
+ /// This covers all identifiers and keywords except those keywords
+ /// used
+ bool canBeArgumentLabel() const {
+ // Identifiers, escaped identifiers, and '_' can be argument labels.
+ if (is(tok::identifier) || isEscapedIdentifier() || is(tok::kw__))
+ return true;
+
+ // 'let', 'var', and 'inout' cannot be argument labels.
+ if (isAny(tok::kw_let, tok::kw_var, tok::kw_inout)) return false;
+
+ // All other keywords can be argument labels.
+ return isKeyword();
+ }
+
/// True if the token is an identifier or '_'.
bool isIdentifierOrUnderscore() const {
return isAny(tok::identifier, tok::kw__);
diff --git a/include/swift/Parse/Tokens.def b/include/swift/Parse/Tokens.def
index 834e0a53e0784..c66fb9d63d62e 100644
--- a/include/swift/Parse/Tokens.def
+++ b/include/swift/Parse/Tokens.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/PrintAsObjC/PrintAsObjC.h b/include/swift/PrintAsObjC/PrintAsObjC.h
index 676600c18968f..38788455ce8fa 100644
--- a/include/swift/PrintAsObjC/PrintAsObjC.h
+++ b/include/swift/PrintAsObjC/PrintAsObjC.h
@@ -1,8 +1,8 @@
-//===-- PrintAsObjC.h - Emit a header file for a Swift AST --------------===//
+//===--- PrintAsObjC.h - Emit a header file for a Swift AST ---------------===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Runtime/Concurrent.h b/include/swift/Runtime/Concurrent.h
index 9f9e26125c199..adf8fd31e6e20 100644
--- a/include/swift/Runtime/Concurrent.h
+++ b/include/swift/Runtime/Concurrent.h
@@ -1,8 +1,8 @@
-//===--- Concurrent.h - Concurrent Data Structures ------------*- C++ -*--===//
+//===--- Concurrent.h - Concurrent Data Structures -------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -145,7 +145,7 @@ template struct ConcurrentMapNode {
/// The method findOrAllocateNode searches the binary tree in search of the
/// exact Key value. If it finds an edge that points to NULL that should
/// contain the value then it tries to compare and swap the new node into
-/// place. If it looses the race to a different thread it de-allocates
+/// place. If it loses the race to a different thread it de-allocates
/// the node and starts the search again since the new node should
/// be placed (or found) on the new link. See findOrAllocateNode for more
/// details.
@@ -164,7 +164,7 @@ template class ConcurrentMap {
/// accelerating the search of the same value again and again.
std::atomic LastSearch;
- /// Search a for a node with key value \p. If the node does not exist then
+ /// Search for a node with key value \p. If the node does not exist then
/// allocate a new bucket and add it to the tree.
ConcurrentList &findOrAllocateNode(KeyTy Key) {
// Try looking at the last node we searched.
diff --git a/include/swift/Runtime/Config.h b/include/swift/Runtime/Config.h
index 91a4b62f8f2da..7307a435392f0 100644
--- a/include/swift/Runtime/Config.h
+++ b/include/swift/Runtime/Config.h
@@ -1,8 +1,8 @@
-//===--- Config.h - Swift Language Platform Configuration ------*- C++ -*--===//
+//===--- Config.h - Swift Language Platform Configuration -------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Runtime/Debug.h b/include/swift/Runtime/Debug.h
index 7e9c09a8222ac..86d65960f4b80 100644
--- a/include/swift/Runtime/Debug.h
+++ b/include/swift/Runtime/Debug.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -101,7 +101,10 @@ swift_dynamicCastFailure(const void *sourceType, const char *sourceName,
const void *targetType, const char *targetName,
const char *message = nullptr);
+extern "C"
+void swift_reportError(const char *message);
+
// namespace swift
-};
+}
#endif // _SWIFT_RUNTIME_DEBUG_HELPERS_
diff --git a/include/swift/Runtime/Enum.h b/include/swift/Runtime/Enum.h
index 887ecad99cd3c..95ad9c8e0f6c4 100644
--- a/include/swift/Runtime/Enum.h
+++ b/include/swift/Runtime/Enum.h
@@ -1,8 +1,8 @@
-//===--- Enum.h - Runtime declarations for enums ---------------*- C++ -*--===//
+//===--- Enum.h - Runtime declarations for enums ----------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Runtime/Heap.h b/include/swift/Runtime/Heap.h
index fc6f30e25ad4b..749eb7f9337e8 100644
--- a/include/swift/Runtime/Heap.h
+++ b/include/swift/Runtime/Heap.h
@@ -1,8 +1,8 @@
-//===--- Heap.h - Swift Language Heap ABI ----------------------*- C++ -*--===//
+//===--- Heap.h - Swift Language Heap ABI -----------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Runtime/HeapObject.h b/include/swift/Runtime/HeapObject.h
index 7e28ccb22ba4d..4ec557716b52b 100644
--- a/include/swift/Runtime/HeapObject.h
+++ b/include/swift/Runtime/HeapObject.h
@@ -1,8 +1,8 @@
-//===--- Alloc.h - Swift Language Allocation ABI ---------------*- C++ -*--===//
+//===--- HeapObject.h - Swift Language Allocation ABI -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -123,26 +123,6 @@ inline TwoWordPair::TwoWordPair(A first, B second)
using BoxPair = TwoWordPair;
-/// Allocates a heap object with POD value semantics. The returned memory is
-/// uninitialized outside of the heap object header. The object has an
-/// initial retain count of 1, and its metadata is set to a predefined
-/// POD heap metadata for which destruction is a no-op.
-///
-/// \param dataSize The size of the data area for the allocation.
-/// Excludes the heap metadata header.
-/// \param dataAlignmentMask The alignment of the data area.
-///
-/// \returns a BoxPair in which the heapObject field points to the newly-created
-/// HeapObject and the value field points to the data area inside the
-/// allocation. The value pointer will have the alignment specified
-/// by the dataAlignmentMask and point to dataSize bytes of memory.
-extern "C" BoxPair::Return
-swift_allocPOD(size_t dataSize, size_t dataAlignmentMask);
-
-/// Deallocates a heap object known to have been allocated by swift_allocPOD and
-/// to have no remaining owners.
-extern "C" void swift_deallocPOD(HeapObject *obj);
-
/// Allocates a heap object that can contain a value of the given type.
/// Returns a Box structure containing a HeapObject* pointer to the
/// allocated object, and a pointer to the value inside the heap object.
@@ -226,10 +206,6 @@ extern "C" void swift_release(HeapObject *object);
/// count reaches zero, the object is destroyed
extern "C" void swift_release_n(HeapObject *object, uint32_t n);
-/// ObjC compatibility. Never call this.
-extern "C" size_t swift_retainCount(HeapObject *object);
-extern "C" size_t swift_weakRetainCount(HeapObject *object);
-
/// Is this pointer a non-null unique reference to an object
/// that uses Swift reference counting?
extern "C" bool swift_isUniquelyReferencedNonObjC(const void *);
@@ -381,24 +357,103 @@ class SwiftRAII {
HeapObject *operator *() const { return object; }
};
-/// Increment the weak retain count.
-extern "C" void swift_weakRetain(HeapObject *value);
+/*****************************************************************************/
+/**************************** UNOWNED REFERENCES *****************************/
+/*****************************************************************************/
+
+/// An unowned reference in memory. This is ABI.
+struct UnownedReference {
+ HeapObject *Value;
+};
-/// Decrement the weak retain count.
-extern "C" void swift_weakRelease(HeapObject *value);
+/// Increment the weak/unowned retain count.
+extern "C" void swift_unownedRetain(HeapObject *value);
-/// Increment the weak retain count by n.
-extern "C" void swift_weakRetain_n(HeapObject *value, int n);
+/// Decrement the weak/unowned retain count.
+extern "C" void swift_unownedRelease(HeapObject *value);
-/// Decrement the weak retain count by n.
-extern "C" void swift_weakRelease_n(HeapObject *value, int n);
+/// Increment the weak/unowned retain count by n.
+extern "C" void swift_unownedRetain_n(HeapObject *value, int n);
+
+/// Decrement the weak/unowned retain count by n.
+extern "C" void swift_unownedRelease_n(HeapObject *value, int n);
+
+/// Increment the strong retain count of an object, aborting if it has
+/// been deallocated.
+extern "C" void swift_unownedRetainStrong(HeapObject *value);
/// Increment the strong retain count of an object which may have been
-/// deallocated.
-extern "C" void swift_retainUnowned(HeapObject *value);
+/// deallocated, aborting if it has been deallocated, and decrement its
+/// weak/unowned reference count.
+extern "C" void swift_unownedRetainStrongAndRelease(HeapObject *value);
/// Aborts if the object has been deallocated.
-extern "C" void swift_checkUnowned(HeapObject *value);
+extern "C" void swift_unownedCheck(HeapObject *value);
+
+static inline void swift_unownedInit(UnownedReference *ref, HeapObject *value) {
+ ref->Value = value;
+ swift_unownedRetain(value);
+}
+
+static inline void swift_unownedAssign(UnownedReference *ref,
+ HeapObject *value) {
+ auto oldValue = ref->Value;
+ if (value != oldValue) {
+ swift_unownedRetain(value);
+ ref->Value = value;
+ swift_unownedRelease(oldValue);
+ }
+}
+
+static inline HeapObject *swift_unownedLoadStrong(UnownedReference *ref) {
+ auto value = ref->Value;
+ swift_unownedRetainStrong(value);
+ return value;
+}
+
+static inline void *swift_unownedTakeStrong(UnownedReference *ref) {
+ auto value = ref->Value;
+ swift_unownedRetainStrongAndRelease(value);
+ return value;
+}
+
+static inline void swift_unownedDestroy(UnownedReference *ref) {
+ swift_unownedRelease(ref->Value);
+}
+
+static inline void swift_unownedCopyInit(UnownedReference *dest,
+ UnownedReference *src) {
+ dest->Value = src->Value;
+ swift_unownedRetain(dest->Value);
+}
+
+static inline void swift_unownedTakeInit(UnownedReference *dest,
+ UnownedReference *src) {
+ dest->Value = src->Value;
+}
+
+static inline void swift_unownedCopyAssign(UnownedReference *dest,
+ UnownedReference *src) {
+ auto newValue = src->Value;
+ auto oldValue = dest->Value;
+ if (newValue != oldValue) {
+ dest->Value = newValue;
+ swift_unownedRetain(newValue);
+ swift_unownedRelease(oldValue);
+ }
+}
+
+static inline void swift_unownedTakeAssign(UnownedReference *dest,
+ UnownedReference *src) {
+ auto newValue = src->Value;
+ auto oldValue = dest->Value;
+ dest->Value = newValue;
+ swift_unownedRelease(oldValue);
+}
+
+/*****************************************************************************/
+/****************************** WEAK REFERENCES ******************************/
+/*****************************************************************************/
/// A weak reference value object. This is ABI.
struct WeakReference {
@@ -461,10 +516,18 @@ extern "C" void swift_weakCopyAssign(WeakReference *dest, WeakReference *src);
/// \param src - never null, but can refer to a null object
extern "C" void swift_weakTakeAssign(WeakReference *dest, WeakReference *src);
+/*****************************************************************************/
+/************************* OTHER REFERENCE-COUNTING **************************/
+/*****************************************************************************/
+
extern "C" void *swift_bridgeObjectRetain(void *value);
/// Increment the strong retain count of a bridged object by n.
extern "C" void *swift_bridgeObjectRetain_n(void *value, int n);
+/*****************************************************************************/
+/************************ UNKNOWN REFERENCE-COUNTING *************************/
+/*****************************************************************************/
+
#if SWIFT_OBJC_INTEROP
/// Increment the strong retain count of an object which might not be a native
@@ -511,47 +574,9 @@ static inline void swift_unknownRelease_n(void *value, int n) {
#endif /* SWIFT_OBJC_INTEROP */
-#if SWIFT_OBJC_INTEROP
-
-/// Increment the strong retain count of an object which may have been
-/// deallocated and which might not be a native Swift object.
-extern "C" void swift_unknownRetainUnowned(void *value);
-
-#else
-
-static inline void swift_unknownRetainUnowned(void *value) {
- swift_retainUnowned(static_cast(value));
-}
-
-#endif /* SWIFT_OBJC_INTEROP */
-
-#if SWIFT_OBJC_INTEROP
-
-/// Increment the weak-reference count of an object that might not be
-/// a native Swift object.
-extern "C" void swift_unknownWeakRetain(void *value);
-
-#else
-
-static inline void swift_unknownWeakRetain(void *value) {
- swift_weakRetain(static_cast(value));
-}
-
-#endif /* SWIFT_OBJC_INTEROP */
-
-#if SWIFT_OBJC_INTEROP
-
-/// Decrement the weak-reference count of an object that might not be
-/// a native Swift object.
-extern "C" void swift_unknownWeakRelease(void *value);
-
-#else
-
-static inline void swift_unknownWeakRelease(void *value) {
- swift_weakRelease(static_cast(value));
-}
-
-#endif /* SWIFT_OBJC_INTEROP */
+/*****************************************************************************/
+/************************** UNKNOWN WEAK REFERENCES **************************/
+/*****************************************************************************/
#if SWIFT_OBJC_INTEROP
@@ -690,6 +715,146 @@ static inline void swift_unknownWeakTakeAssign(WeakReference *dest, WeakReferenc
#endif /* SWIFT_OBJC_INTEROP */
+/*****************************************************************************/
+/************************ UNKNOWN UNOWNED REFERENCES *************************/
+/*****************************************************************************/
+
+#if SWIFT_OBJC_INTEROP
+
+/// Initialize an unowned reference to an object with unknown reference
+/// counting.
+extern "C" void swift_unknownUnownedInit(UnownedReference *ref, void *value);
+
+#else
+
+static inline void swift_unknownUnownedInit(UnownedReference *ref,
+ void *value) {
+ swift_unownedInit(ref, static_cast(value));
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Assign to an unowned reference holding an object with unknown reference
+/// counting.
+extern "C" void swift_unknownUnownedAssign(UnownedReference *ref, void *value);
+
+#else
+
+static inline void swift_unknownUnownedAssign(UnownedReference *ref,
+ void *value) {
+ swift_unownedAssign(ref, static_cast(value));
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Load from an unowned reference to an object with unknown reference
+/// counting.
+extern "C" void *swift_unknownUnownedLoadStrong(UnownedReference *ref);
+
+#else
+
+static inline void *swift_unknownUnownedLoadStrong(UnownedReference *ref) {
+ return swift_unownedLoadStrong(ref);
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Take from an unowned reference to an object with unknown reference
+/// counting.
+extern "C" void *swift_unknownUnownedTakeStrong(UnownedReference *ref);
+
+#else
+
+static inline void *swift_unknownUnownedTakeStrong(UnownedReference *ref) {
+ return swift_unownedTakeStrong(ref);
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Destroy an unowned reference to an object with unknown reference counting.
+extern "C" void swift_unknownUnownedDestroy(UnownedReference *ref);
+
+#else
+
+static inline void swift_unknownUnownedDestroy(UnownedReference *ref) {
+ swift_unownedDestroy(ref);
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Copy-initialize an unowned reference variable from one that might not
+/// refer to a native Swift object.
+extern "C" void swift_unknownUnownedCopyInit(UnownedReference *dest,
+ UnownedReference *src);
+
+#else
+
+static inline void swift_unknownUnownedCopyInit(UnownedReference *dest,
+ UnownedReference *src) {
+ swift_unownedCopyInit(dest, src);
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Take-initialize an unowned reference variable from one that might not
+/// refer to a native Swift object.
+extern "C" void swift_unknownUnownedTakeInit(UnownedReference *dest,
+ UnownedReference *src);
+
+#else
+
+static inline void swift_unknownUnownedTakeInit(UnownedReference *dest,
+ UnownedReference *src) {
+ swift_unownedTakeInit(dest, src);
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Copy-assign an unowned reference variable from another when either
+/// or both variables might not refer to a native Swift object.
+extern "C" void swift_unknownUnownedCopyAssign(UnownedReference *dest,
+ UnownedReference *src);
+
+#else
+
+static inline void swift_unknownUnownedCopyAssign(UnownedReference *dest,
+ UnownedReference *src) {
+ swift_unownedCopyAssign(dest, src);
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+#if SWIFT_OBJC_INTEROP
+
+/// Take-assign an unowned reference variable from another when either
+/// or both variables might not refer to a native Swift object.
+extern "C" void swift_unknownUnownedTakeAssign(UnownedReference *dest,
+ UnownedReference *src);
+
+#else
+
+static inline void swift_unknownUnownedTakeAssign(UnownedReference *dest,
+ UnownedReference *src) {
+ swift_unownedTakeAssign(dest, src);
+}
+
+#endif /* SWIFT_OBJC_INTEROP */
+
+
} // end namespace swift
#endif /* SWIFT_RUNTIME_ALLOC_H */
diff --git a/include/swift/Runtime/InstrumentsSupport.h b/include/swift/Runtime/InstrumentsSupport.h
index 78218ce206223..3b5dbc9901930 100644
--- a/include/swift/Runtime/InstrumentsSupport.h
+++ b/include/swift/Runtime/InstrumentsSupport.h
@@ -1,8 +1,8 @@
-//===--- InstrumentsSupport.h - Support for Instruments.app ------ C++ -*--===//
+//===--- InstrumentsSupport.h - Support for Instruments.app -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Runtime/Metadata.h b/include/swift/Runtime/Metadata.h
index 41a31d11c648a..71dfeac68b2fe 100644
--- a/include/swift/Runtime/Metadata.h
+++ b/include/swift/Runtime/Metadata.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -93,7 +93,7 @@ struct OpaqueValue;
/// A buffer can be in one of three states:
/// - An unallocated buffer has a completely unspecified state.
/// - An allocated buffer has been initialized so that it
-/// owns unintialized value storage for the stored type.
+/// owns uninitialized value storage for the stored type.
/// - An initialized buffer is an allocated buffer whose value
/// storage has been initialized.
struct ValueBuffer {
@@ -192,7 +192,7 @@ class ValueWitnessFlags {
/// available in this type's value witness table.
bool hasExtraInhabitants() const { return Data & HasExtraInhabitants; }
/// True if this type's binary representation is that of an enum, and the
- /// enum value witness table entries are avaialble in this type's value
+ /// enum value witness table entries are available in this type's value
/// witness table.
bool hasEnumWitnesses() const { return Data & HasEnumWitnesses; }
constexpr ValueWitnessFlags
@@ -247,9 +247,9 @@ typedef void destroyBuffer(ValueBuffer *buffer, const Metadata *self);
/// Given an unallocated buffer, initialize it as a copy of the
/// object in the source buffer. This can be decomposed as:
///
-/// self->initalizeBufferWithCopy(dest, self->projectBuffer(src), self)
+/// self->initializeBufferWithCopy(dest, self->projectBuffer(src), self)
///
-/// This operation does not need to be safe aginst 'dest' and 'src' aliasing.
+/// This operation does not need to be safe against 'dest' and 'src' aliasing.
///
/// Preconditions:
/// 'dest' is an unallocated buffer
@@ -305,7 +305,7 @@ typedef OpaqueValue *initializeBufferWithCopy(ValueBuffer *dest,
/// Given an uninitialized object and an initialized object, copy
/// the value.
///
-/// This operation does not need to be safe aginst 'dest' and 'src' aliasing.
+/// This operation does not need to be safe against 'dest' and 'src' aliasing.
///
/// Returns the dest object.
///
@@ -322,7 +322,7 @@ typedef OpaqueValue *initializeWithCopy(OpaqueValue *dest,
/// Given two initialized objects, copy the value from one to the
/// other.
///
-/// This operation must be safe aginst 'dest' and 'src' aliasing.
+/// This operation must be safe against 'dest' and 'src' aliasing.
///
/// Returns the dest object.
///
@@ -337,7 +337,7 @@ typedef OpaqueValue *assignWithCopy(OpaqueValue *dest,
/// the value from the object to the buffer, leaving the source object
/// uninitialized.
///
-/// This operation does not need to be safe aginst 'dest' and 'src' aliasing.
+/// This operation does not need to be safe against 'dest' and 'src' aliasing.
///
/// Returns the dest object.
///
@@ -355,11 +355,11 @@ typedef OpaqueValue *initializeBufferWithTake(ValueBuffer *dest,
/// the value from one to the other, leaving the source object
/// uninitialized.
///
-/// There is no need for a initializeBufferWithTakeOfBuffer, because that
+/// There is no need for an initializeBufferWithTakeOfBuffer, because that
/// can simply be a pointer-aligned memcpy of sizeof(ValueBuffer)
/// bytes.
///
-/// This operation does not need to be safe aginst 'dest' and 'src' aliasing.
+/// This operation does not need to be safe against 'dest' and 'src' aliasing.
///
/// Returns the dest object.
///
@@ -377,7 +377,7 @@ typedef OpaqueValue *initializeWithTake(OpaqueValue *dest,
/// the value from one to the other, leaving the source object
/// uninitialized.
///
-/// This operation does not need to be safe aginst 'dest' and 'src' aliasing.
+/// This operation does not need to be safe against 'dest' and 'src' aliasing.
/// Therefore this can be decomposed as:
///
/// self->destroy(dest, self);
@@ -411,10 +411,10 @@ typedef OpaqueValue *allocateBuffer(ValueBuffer *buffer,
/// value from one buffer to the other, leaving the source buffer
/// unallocated.
///
-/// This operation does not need to be safe aginst 'dest' and 'src' aliasing.
+/// This operation does not need to be safe against 'dest' and 'src' aliasing.
/// Therefore this can be decomposed as:
///
-/// self->initalizeBufferWithTake(dest, self->projectBuffer(src), self)
+/// self->initializeBufferWithTake(dest, self->projectBuffer(src), self)
/// self->deallocateBuffer(src, self)
///
/// However, it may be more efficient because values stored out-of-line
@@ -447,7 +447,7 @@ typedef void destroyArray(OpaqueValue *array, size_t n,
/// Given an uninitialized array and an initialized array, copy
/// the value.
///
-/// This operation does not need to be safe aginst 'dest' and 'src' aliasing.
+/// This operation does not need to be safe against 'dest' and 'src' aliasing.
///
/// Returns the dest object.
///
@@ -545,6 +545,13 @@ typedef unsigned getEnumTag(const OpaqueValue *src,
typedef void destructiveProjectEnumData(OpaqueValue *src,
const Metadata *self);
+/// Given a valid object of an enum case payload's type, destructively add
+/// the tag bits for the given case, leaving behind a fully-formed value of
+/// the enum type. If the enum case does not have a payload, the initial
+/// state of the value can be undefined.
+typedef void destructiveInjectEnumTag(OpaqueValue *src,
+ unsigned tag,
+ const Metadata *self);
} // end namespace value_witness_types
@@ -702,18 +709,22 @@ struct ExtraInhabitantsValueWitnessTable : ValueWitnessTable {
struct EnumValueWitnessTable : ExtraInhabitantsValueWitnessTable {
value_witness_types::getEnumTag *getEnumTag;
value_witness_types::destructiveProjectEnumData *destructiveProjectEnumData;
+ value_witness_types::destructiveInjectEnumTag *destructiveInjectEnumTag;
constexpr EnumValueWitnessTable()
: ExtraInhabitantsValueWitnessTable(),
getEnumTag(nullptr),
- destructiveProjectEnumData(nullptr) {}
+ destructiveProjectEnumData(nullptr),
+ destructiveInjectEnumTag(nullptr) {}
constexpr EnumValueWitnessTable(
const ExtraInhabitantsValueWitnessTable &base,
value_witness_types::getEnumTag *getEnumTag,
- value_witness_types::destructiveProjectEnumData *destructiveProjectEnumData)
+ value_witness_types::destructiveProjectEnumData *destructiveProjectEnumData,
+ value_witness_types::destructiveInjectEnumTag *destructiveInjectEnumTag)
: ExtraInhabitantsValueWitnessTable(base),
getEnumTag(getEnumTag),
- destructiveProjectEnumData(destructiveProjectEnumData) {}
+ destructiveProjectEnumData(destructiveProjectEnumData),
+ destructiveInjectEnumTag(destructiveInjectEnumTag) {}
static bool classof(const ValueWitnessTable *table) {
return table->flags.hasEnumWitnesses();
@@ -992,6 +1003,7 @@ struct Metadata {
case MetadataKind::Function:
case MetadataKind::Struct:
case MetadataKind::Enum:
+ case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
case MetadataKind::Existential:
@@ -1018,6 +1030,7 @@ struct Metadata {
case MetadataKind::ForeignClass:
case MetadataKind::Struct:
case MetadataKind::Enum:
+ case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
case MetadataKind::Function:
@@ -1070,6 +1083,9 @@ struct Metadata {
void vw_destructiveProjectEnumData(OpaqueValue *value) const {
getValueWitnesses()->_asEVWT()->destructiveProjectEnumData(value, this);
}
+ void vw_destructiveInjectEnumTag(OpaqueValue *value, unsigned tag) const {
+ getValueWitnesses()->_asEVWT()->destructiveInjectEnumTag(value, tag, this);
+ }
/// Get the nominal type descriptor if this metadata describes a nominal type,
/// or return null if it does not.
@@ -1732,7 +1748,8 @@ struct EnumMetadata : public Metadata {
}
static bool classof(const Metadata *metadata) {
- return metadata->getKind() == MetadataKind::Enum;
+ return metadata->getKind() == MetadataKind::Enum
+ || metadata->getKind() == MetadataKind::Optional;
}
};
@@ -2089,6 +2106,25 @@ struct GenericMetadata {
}
};
+/// \brief The control structure of a generic protocol conformance.
+struct GenericWitnessTable {
+ /// The size of the witness table in words.
+ uint16_t WitnessTableSizeInWords;
+
+ /// The amount to copy from the pattern in words. The rest is zeroed.
+ uint16_t WitnessTableSizeInWordsToCopy;
+
+ /// The pattern.
+ RelativeDirectPointer Pattern;
+
+ /// The instantiation function, which is called after the template is copied.
+ RelativeDirectPointer Instantiator;
+
+ void *PrivateData[swift::NumGenericMetadataPrivateDataWords];
+};
+
/// The structure of a protocol conformance record.
///
/// This contains enough static information to recover the witness table for a
@@ -2316,6 +2352,20 @@ swift_allocateGenericClassMetadata(GenericMetadata *pattern,
extern "C" Metadata *
swift_allocateGenericValueMetadata(GenericMetadata *pattern,
const void *arguments);
+
+/// Instantiate a generic protocol witness table.
+///
+///
+/// \param instantiationArgs - An opaque pointer that's forwarded to
+/// the instantiation function, used for conditional conformances.
+/// This API implicitly embeds an assumption that these arguments
+/// never form part of the uniquing key for the conformance, which
+/// is ultimately a statement about the user model of overlapping
+/// conformances.
+extern "C" const WitnessTable *
+swift_getGenericWitnessTable(GenericWitnessTable *genericTable,
+ const Metadata *type,
+ void * const *instantiationArgs);
/// \brief Fetch a uniqued metadata for a function type.
extern "C" const FunctionTypeMetadata *
@@ -2474,7 +2524,6 @@ struct ClassFieldLayout {
/// Initialize the field offset vector for a dependent-layout class, using the
/// "Universal" layout strategy.
extern "C" void swift_initClassMetadata_UniversalStrategy(ClassMetadata *self,
- const ClassMetadata *super,
size_t numFields,
const ClassFieldLayout *fieldLayouts,
size_t *fieldOffsets);
@@ -2769,17 +2818,6 @@ extern "C"
void swift_registerProtocolConformances(const ProtocolConformanceRecord *begin,
const ProtocolConformanceRecord *end);
-/// FIXME: This doesn't belong in the runtime.
-extern "C" void swift_printAny(OpaqueValue *value, const Metadata *type);
-
-/// \brief Demangle a mangled class name into module+class.
-/// Returns true if the name was successfully decoded.
-/// On success, *outModule and *outClass must be freed with free().
-extern "C" bool
-swift_demangleSimpleClass(const char *mangledName,
- char **outModule, char **outClass);
-
-
/// Return the type name for a given type metadata.
std::string nameForMetadata(const Metadata *type,
bool qualified = true);
diff --git a/include/swift/Runtime/ObjCBridge.h b/include/swift/Runtime/ObjCBridge.h
index 01949cabdaba5..44f2ad4b7a3b3 100644
--- a/include/swift/Runtime/ObjCBridge.h
+++ b/include/swift/Runtime/ObjCBridge.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -54,7 +54,7 @@ typedef struct objc_image_info {
} objc_image_info;
// Class and metaclass construction from a compiler-generated memory image.
-// cls and cls->isa must each be OBJC_MAX_CLASS_SIZE bytes.·
+// cls and cls->isa must each be OBJC_MAX_CLASS_SIZE bytes.
// Extra bytes not used the metadata must be zero.
// info is the same objc_image_info that would be emitted by a static compiler.
// Returns nil if a class with the same name already exists.
diff --git a/include/swift/Runtime/Once.h b/include/swift/Runtime/Once.h
index c31f0623a96e3..ee546272a46a4 100644
--- a/include/swift/Runtime/Once.h
+++ b/include/swift/Runtime/Once.h
@@ -1,8 +1,8 @@
-//===--- Once.h - Runtime support for lazy initialization ------*- C++ -*--===//
+//===--- Once.h - Runtime support for lazy initialization -------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/Runtime/Reflection.h b/include/swift/Runtime/Reflection.h
index 7a948faf57792..e29ad6242fb76 100644
--- a/include/swift/Runtime/Reflection.h
+++ b/include/swift/Runtime/Reflection.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/SIL/AbstractionPattern.h b/include/swift/SIL/AbstractionPattern.h
index 8849874e8fc3b..dcd3f81e3811e 100644
--- a/include/swift/SIL/AbstractionPattern.h
+++ b/include/swift/SIL/AbstractionPattern.h
@@ -1,8 +1,8 @@
-//===--- AbstractionPattern.h - SIL type abstraction pattersn ---*- C++ -*-===//
+//===--- AbstractionPattern.h - SIL type abstraction patterns ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -267,13 +267,6 @@ class AbstractionPattern {
Kind getKind() const { return Kind(TheKind); }
- CanGenericSignature getGenericSignature() const {
- assert(getKind() == Kind::Type ||
- hasStoredClangType() ||
- hasStoredObjCMethod());
- return CanGenericSignature(GenericSig);
- }
-
CanGenericSignature getGenericSignatureForFunctionComponent() const {
if (auto genericFn = dyn_cast(getType())) {
return genericFn.getGenericSignature();
@@ -362,6 +355,13 @@ class AbstractionPattern {
return AbstractionPattern(Kind::Invalid);
}
+ CanGenericSignature getGenericSignature() const {
+ assert(getKind() == Kind::Type ||
+ hasStoredClangType() ||
+ hasStoredObjCMethod());
+ return CanGenericSignature(GenericSig);
+ }
+
/// Return an open-coded abstraction pattern for a tuple. The
/// caller is responsible for ensuring that the storage for the
/// tuple elements is valid for as long as the abstraction pattern is.
diff --git a/include/swift/SIL/BridgedTypes.def b/include/swift/SIL/BridgedTypes.def
index 0b725397e1ac7..9e95c144233cd 100644
--- a/include/swift/SIL/BridgedTypes.def
+++ b/include/swift/SIL/BridgedTypes.def
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/SIL/CFG.h b/include/swift/SIL/CFG.h
index b253fcb5858e9..281ccb4d5ff84 100644
--- a/include/swift/SIL/CFG.h
+++ b/include/swift/SIL/CFG.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/SIL/Consumption.h b/include/swift/SIL/Consumption.h
index 7a6b34ff8ac50..31ac3541b4c29 100644
--- a/include/swift/SIL/Consumption.h
+++ b/include/swift/SIL/Consumption.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
diff --git a/include/swift/SIL/DebugUtils.h b/include/swift/SIL/DebugUtils.h
index 492a9b51ebab0..16a2601b2339c 100644
--- a/include/swift/SIL/DebugUtils.h
+++ b/include/swift/SIL/DebugUtils.h
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -158,6 +158,17 @@ inline bool hasOneNonDebugUse(const V &value) {
return ++I == E;
}
+// Returns the use if the value has only one non debug user.
+template
+inline SILInstruction *getSingleNonDebugUser(const V &value) {
+ auto Range = getNonDebugUses(value);
+ auto I = Range.begin(), E = Range.end();
+ if (I == E) return nullptr;
+ if (std::next(I) != E)
+ return nullptr;
+ return I->getUser();
+}
+
/// Erases the instruction \p I from it's parent block and deletes it, including
/// all debug instructions which use \p I.
/// Precondition: The instruction may only have debug instructions as uses.
diff --git a/include/swift/SIL/Dominance.h b/include/swift/SIL/Dominance.h
index 03a1b307e1136..62da9a5f15912 100644
--- a/include/swift/SIL/Dominance.h
+++ b/include/swift/SIL/Dominance.h
@@ -1,8 +1,8 @@
-//===--- Dominance.h - SIL dominance analysis ------------------*- C++ -*-===//
+//===--- Dominance.h - SIL dominance analysis -------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
-// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
@@ -41,7 +41,7 @@ class DominanceInfo : public llvm::DominatorTreeBase {
/// Return true if the other dominator tree does not match this dominator
/// tree.
- inline bool errorOccuredOnComparison(const DominanceInfo &Other) const {
+ inline bool errorOccurredOnComparison(const DominanceInfo &Other) const {
const auto *R = getRootNode();
const auto *OtherR = Other.getRootNode();
@@ -131,13 +131,23 @@ class PostDominanceInfo : public llvm::DominatorTreeBase]