# Swift Language Reference

## Declarations

        decl ::= decl-class
        decl ::= decl-constructor
        decl ::= decl-deinit
        decl ::= decl-extension
        decl ::= decl-func
        decl ::= decl-import
        decl ::= decl-enum
        decl ::= decl-enum-element
        decl ::= decl-protocol
        decl ::= decl-struct
        decl ::= decl-typealias
        decl ::= decl-let
        decl ::= decl-var
        decl ::= decl-subscript

### Module-Scope Declarations

        top-level ::= brace-item*

The top level of a swift source file is grammatically identical to the contents of a func decl. Some declarations, however, are restricted to module scope.

#### Brace Enclosed Items

        brace-item-list ::= '{' brace-item* '}'

        brace-item      ::= decl
        brace-item      ::= expr
        brace-item      ::= stmt

The brace item list provides a sequencing operation which evaluates the members of its body in order. Function bodies and the bodies of control flow statements use braces. Also, the source file itself is effectively a brace item list, but without the braces.

### import Declarations

        decl-import ::=  attribute-list 'import' import-kind? import-path

        import-kind ::= 'typealias'
        import-kind ::= 'struct'
        import-kind ::= 'class'
        import-kind ::= 'enum'
        import-kind ::= 'protocol'
        import-kind ::= 'var'
        import-kind ::= 'func'

        import-path ::= any-identifier ('.' any-identifier)*

'import' declarations allow named values and types to be accessed with local names, even when they are defined in other modules and namespaces. See the section on name binding for more information on how these work. import declarations are only allowed at module scope.

'import' directives only impact a single source file: imports in one swift file do not affect name lookup in another file. import directives can only occur at the top level of a file, not within a function or namespace.

An import without an explicit import-kind names a module; all of the module's members are imported into the current scope. The module's name is also imported into the current scope in order to allow qualified access to the module's members, which can be useful for disambiguation.

If an import-kind is provided, the last element of the import path is taken to be the name of a decl within the module named by the rest of the path. Only that name is introduced into the current scope; the name of the module itself is not accessible, nor any other decls within the module.

Different import-kinds perform different filters on the decls within a module:

- `typealias` can be used to import any concrete type (struct, class, enum, or another typealias). It cannot be used to import protocols, which are often used for more than just their existential type.
- `struct`, `class`, `enum` can be used to import any type whose canonical type is a struct, class, or enum, respectively. (This allows "Int" to be imported as a struct, for example, even though its definition in the standard library may be a typealias for another struct type.)
- `protocol` is used to import a protocol
- `var` is used to import a module-scoped variable
- `func` will import all overloads of a function

        // Import all of the top level symbols and types in a module.
        import Swift

        // Import a single type.
        import typealias Swift.BufferedStream

        // Import all addition overloads.
        import func Swift.+

### extension Declarations

        decl-extension ::= 'extension' type-identifier inheritance? '{' decl* '}'

'extension' declarations allow adding member declarations to existing types, even in other source files and modules. There are different semantic rules for each type that is extended.

#### enum, struct, and class declaration extensions

FIXME: Write this section.

### let Declarations

        decl-let    ::= attribute-list 'let' pattern initializer?  (',' pattern initializer?)*
        initializer ::= '=' expr

'let' declarations define an immutable binding between an initializer value and a name.

Here are some examples of 'let' declarations:

      // Simple examples.
      let a = 4
      let c : Int = 42

      // This decodes the tuple return value into independently named parts
      // and both 'val' and 'err' are in scope after this line.
      let (val, err) = foo()

      // let declarations require an initializer (though the type is optional).
      let b : Int        // error: let requires an initializer

      // Let bindings of classes make the binding immutable, not the object.
      class Rocket {
        func blastOff() { ... }
      }
      let rocket = Rocket()
      rocket.blastOff()      // okay
      rocket = Rocket()   // error, cannot change a let binding

### func Declarations

#### Function signatures

        func-signature ::= func-arguments func-signature-result?
        func-arguments ::= pattern-tuple+
        func-arguments ::= selector-tuple
        selector-tuple ::= '(' pattern-tuple-element ')' (identifier-or-any '(' pattern-tuple-element ')')+
        func-signature-result ::= '->' type

A function signature specifies one or more sets of parameter patterns, plus an optional result type.

When a result type is not written, it is implicitly the empty tuple type, `()`.

In the body of the function described by a particular signature, all the variables bound by all of the parameter patterns are in scope, and the function must return a value of the result type.

An outermost pattern in a function signature must be fully-typed and irrefutable. If a result type is given, it must also be fully-typed.

The type of a function with signature `(P0)(P1)...(Pn) -> R` is `T0 -> T1 -> ... -> Tn -> R`, where `Ti` is the bottom-up type of the pattern `Pi`. This is called "currying". The behavior of all the intermediate functions (those which do not return `R`) is to capture their arguments, plus any arguments from prior patterns, and returns a function which takes the next set of arguments. When the "uncurried" function is called (the one taking `Tn` and returning `R`), all of the arguments are then available and the function body is finally evaluated as normal.

A function declared with a selector-style signature `func(a0:T0) name1(a1:T1) ... namen(an:Tn) -> R` has the type `(_:T0, name1:T1, ... namen:Tn) -> R`, that is, the names of the fields in the argument tuple are the `namen` identifiers preceding each argument pattern. However, in the body of a function described by a signature, those arguments will be bound using the corresponding `an` patterns inside the arguments. This allows for Cocoa-style keyword function names such as `doThing(x, withThing:y)` to be defined without requiring that an awkward keyword name be the same as the variable name.

Here are some examples of func definitions:

        // Implicitly returns (), aka Void
        func a() {}

        // Same as 'a'
        func a1() -> Void {}

        // Function pointers to a function expression.
        var a2 = func ()->() {}
        var a3 = func () {}
        var a4 = func {}

        // Really simple function
        func c(_ arg : Int) -> Int { return arg+4 }

        // Simple operators.
        func [infix_left=190] +  (lhs : Int, rhs : Int) -> Int
        func [infix_left=160] == (lhs : Int, rhs : Int) -> Bool

        // Curried function with multiple return values:
        func d(_ a : Int) (b : Int) -> (res1 : Int, res2 : Int) {
          return (a,b)
        }

        // A more realistic example on a trivial type.
        struct bankaccount {
          amount : Int

         static func bankaccount() -> bankaccount {
            // Custom 'constructor' logic goes here.
          }
          func deposit(_ arg : Int) {
            amount = amount + arg
          }

          static func someMetatypeMethod() {}
        }

        // Dot syntax on metatype.
        bankaccount.someMetatypeMethod()

        // A function with selector-style signature.

        enum PersonOfInterest {
          case ColonelMustard
          case MissScarlet
        }
        enum Room {
          case Conservatory
          case Ballroom
        }
        enum Weapon {
          case Candlestick
          case LeadPipe
        }

        func accuseSuspect(_ suspect:PersonOfInterest)
            inRoom(room:Room)
            withWeapon(weapon:Weapon) {
          print("It was \(suspect) in the \(room) with the \(weapon)")
        }

        // Calling a selector-style function.
        accuseSuspect(.ColonelMustard, inRoom:.Ballroom, withWeapon:.LeadPipe)

### typealias Declarations

We use the keyword "typealias" instead of "typedef" because it really is an alias for an existing type, not a "definition" of a new type.

        decl-typealias ::= typealias-head '=' type
        typealias-head ::= 'typealias' identifier inheritance?

'typealias' makes a named alias of a type, like a typedef in C. From that point on, the alias may be used in all situations the specified name is. If an inheritance clause is provided, it specifies protocols to which the aliased type shall conform.

Here are some examples of type aliases:

        // location is an alias for a tuple of ints.
        typealias location = (x : Int, y : Int)

        // pair_fn is a function that takes two ints and returns a tuple.
        typealias pair_fn = (Int) -> (Int) -> (first : Int, second : Int)

### enum Declarations

        decl-enum ::= attribute-list 'enum' identifier generic-params? inheritance? enum-body
        enum-body ::= '{' decl* '}'

        decl-enum-element ::= attribute-list 'case' enum-case (',' enum-case)*
        enum-case ::= identifier type-tuple? ('->' type)?

An `enum` declaration creates a enum type. Here are some examples of enum declarations:

        // Declares three enums.
        enum DataSearchFlags {
          case None
          case Backward
          case Anchored
        }

        // Shorthand for the above.
        enum DataSearchFlags {
          case None, Backward, Anchored
        }

        // Declare discriminated union with enum decl.
        enum SomeInts {
          case None
          case One(Int)
          case Two(Int, Int)
        }

        func f1(_ searchpolicy : DataSearchFlags)  // DataSearchFlags is a valid type name
        func test1() {
          f1(DataSearchFlags.None)  // Use of constructor with qualified identifier
          f1(.None)                 // Use of constructor with context sensitive type inference

          // "None" has no type argument, so the constructor's type is "DataSearchFlags".
          var a : DataSearchFlags = .None
        }

        enum SomeMoreInts {
          case None           // Doesn't conflict with previous "None".
          case One(Int)
          case Two(Int, Int)
        }

        func f2(_ a : SomeMoreInts)

        func test2() {
          // Constructors for enum element can be used in the obvious way.
          f2(.None)
          f2(.One(4))
          f2(.Two(1, 2))

          // Constructor for None has type "SomeMoreInts".
          var a : SomeMoreInts = SomeMoreInts.None

          // Constructor for One has type "(Int) -> SomeMoreInts".
          var b : (Int) -> SomeMoreInts = SomeMoreInts.One

          // Constructor for Two has type "(Int,Int) -> SomeMoreInts".
          var c : (Int,Int) -> SomeMoreInts = SomeMoreInts.Two
        }

### struct Declarations

        decl-struct ::= attribute-list 'struct' identifier generic-params? inheritance? '{' decl-struct-body '}'
        decl-struct-body ::= decl*

A struct declares a simple value type that can contain data members and have methods.

The body of a 'struct' is a list of decls. Stored (non-computed) 'var' decls declare members with storage in the struct. Other declarations act like they would in an extension of the struct type.

Here are a few simple examples:

        struct S1 {
          var a : Int, b : Int
        }

        struct S2 {
          var a : Int
          func f() -> Int { return b }
          var b : Int
        }

Here are some more realistic examples of structs:

        struct Point { x : Int, y : Int }
        struct Size { width : Int, height : Int }
        struct Rect {
          origin : Point,
          size : Size

          typealias CoordinateType = Int

          func area() -> Int { return size.width*size.height }
        }

        func test4() {
          var a : Point
          var b = Point.Point(1, 2)    // Silly but fine.
          var c = Point(y = 1, x = 2)  // Using metatype.

          var x1 = Rect(a, Size(42, 123))
          var x2 = Rect(size = Size(width = 42, height=123), origin = a)

          var x1_area = x1.width*x1.height
          var x1_area2 = x1.area()
        }

Structs do not support inheritance due to undesirable ripple effects across the design of the language. For example, method dispatch would arguably need to become virtual, not static. The storage of the type would arguably need to become indirected so that an array of T could be implemented sanely (because we don't know if T is actually a T, or a subclass of T). We'd need to store the "isa"/vtable in the struct so that virtual method dispatch could be implemented, and this has additional storage costs. None of these tradeoffs make sense for the intended use cases we have in mind for structs (Ints, Floats, Points, Rects, UUIDs, IP addresses, C struct interop, etc, etc). Said differently: we're trying to force a hard wall between types that need indirect access by their nature and those types that need direct access by their nature. The former are called classes. The latter are called structs.

### class Declarations

        decl-class ::= attribute-list 'class' identifier generic-params? inheritance? '{' decl-class-body '}'
        decl-class-body ::= decl*

A class declares a reference type referring to an object which can contain data members and have methods. Classes support single inheritance; a parent class should be listed as the first type in the inheritance list.

The body of a 'class' is a list of decls. Stored (non-computed) 'var' decls declare members with storage in the class. Non-type 'var' and 'func' decls declare instance members;type 'var' and 'func' decls declare members of the class itself. Both class and instance members can be overridden by a subclass.

Type declarations inside a class act essentially the same way as type declarations outside a class.

FIXME: For the moment, see classes.rst for more details on the class system.

FIXME: Add a reference to the section on generics.

The only way to create a new instance of a class is with a call to one of the class's constructors.

Here is a simple example:

        class C1 {
          var a : Int
          var b : Int
        }

### Protocol Declarations

        decl-protocol ::= attribute-list 'protocol' identifier inheritance? '{' protocol-member* '}'

A protocol declaration describes an abstract interface implemented by another type. It consists of a set of declarations, which may be instance methods or properties. A type conforms to a protocol if it provides declarations that correspond to each of the declarations in a protocol.

Here are some examples of protocols:

        protocol Document {
          var title : String
        }

#### 'func' protocol elements

        protocol-member ::= decl-func

'func' members of a protocol define a value of function type that may be accessed with dot syntax on a value of the protocol's type. The function gets an implicit "self" argument of the protocol type or (for a type function) of the metatype of the protocol.

#### 'var' protocol elements

        protocol-member ::= decl-var

'var' members of a protocol define "property" values that may be accessed with dot syntax on a value of the protocol's type. The actual variables may have no storage, and will always be accessed by a getter and setter. Thus, the variables shall have neither an initializer nor a getter/setter clause.

#### 'subscript' protocol elements

        protocol-member ::= subscript-head

'subscript' members of a protocol define subscripting operations that may be accessed with the subscript operator ('[]') applied to a value of the protocol's type.

TODO: There is currently no way to express a requirement for a read-only or write-only subscript operation or variable. We may end up doing this with some kind of 'const' or 'immutable' attribute.

#### 'typealias' protocol elements (associated types)

        protocol-member ::= typealias-head ('=' type)?

'typealias' members of a protocol define associated types, which are types used within the description of a protocol (typically in the inputs and outputs of 'func' members) that vary from one conforming type to another. When an associated type has an inheritance clause, any type meant to satisfy the associated type requirement must conform to each of the protocols specified within that inheritance clause. If a type is provided after the '=', it is a default definition for the associated type that will be used as the type witness if the type witness cannot be determined in any other way.

        protocol SequenceType {
          typename Iterator : IteratorProtocol
          func makeIterator() -> Iterator
        }

### constructor Declarations

        decl-constructor ::= attribute-list 'init' generic-params? constructor-signature brace-item-list

        constructor-signature ::= pattern-tuple constructor-result?
        constructor-signature ::= identifier-or-any selector-tuple constructor-result?

        constructor-result ::= '->' 'Self'

'constructor' declares a constructor for a class, struct, or enum. Such a declaration is used whenever an object is constructed. Specifically, for classes, it is used when a new expression is written, and for structs and enums, it is used for function application when the "function" is a metatype.

FIXME: We haven't decided the precise rules for when constructors are implicitly declared. Default construction doesn't work right for structs or enums. We haven't decided what the restrictions are if a member isn't default-constructible.

A simple example:

        struct X {
          var member : Int
          init(x : Int) {
            member = x
          }
        }
        var a = X(10)

If a class is derived from a superclass, it must explicitly invoke a superclass constructor using the `super.init` syntax. `super.init` may only be used in a subclass constructor; it is not valid in a struct, enum, or root class constructor. Additionally, `super.init` may only be referenced exactly once per derived constructor. An example:

        class View {
          var bounds : Rect
          init(bounds:Rect) {
            self.bounds = bounds
          }
        }

        class Button : View {
          var onClick : () -> ()
          init(bounds:Rect, onClick:() -> ()) {
            super.init(bounds)
            self.onClick = onClick
          }
        }

### deinitializer Declarations

        decl-deinit ::= attribute-list 'deinit' brace-item-list

'deinit' declares a deinitializer for a class. This function is called when there are no longer any references to a class object, just before it is destroyed. Note that deinitializers can only be declared for classes, and cannot be declared in extensions. Subclass deinitializers implicitly invoke their superclass deinitializers after executing.

FIXME: We haven't really decided the precise rules here, but it's probably a fatal error to either throw an exception or stash a reference to 'self' in a deinitializer. Not sure what happens when we cause the reference count of another object to reach zero inside a deinitializer. We might eventually allow deinitializers in extensions once we have ivars in extensions.

A simple example:

        class X {
          var fd : Int
          deinit {
            close(fd)
          }
        }

### Attribute Lists

        attribute-list        ::= /*empty*/
        attribute-list        ::= attribute-list-clause attribute-list
        attribute-list-clause ::= '@' attribute
        attribute-list-clause ::= '@' attribute ','? attribute-list-clause

        attribute      ::= attribute-infix
        attribute      ::= attribute-resilience
        attribute      ::= attribute-inout
        attribute      ::= attribute-autoclosure
        attribute      ::= attribute-noreturn

An attribute list is written as a sequence of attributes, each of which has a leading '@' sign. Attributes can be optionally comma separated. Attributes may not be repeated within a list.

#### Infix Attributes

        attribute-infix ::= 'infix_left'  '=' integer_literal
        attribute-infix ::= 'infix_right' '=' integer_literal
        attribute-infix ::= 'infix        '=' integer_literal

The infix attributes may only be applied to the declaration of a function of binary operator type whose name is an `operator`. The name indicates the associativity of the operator, either left associative, right associative, or non-associative.

FIXME: Implement these restrictions.

#### Resilience Attribute

        attribute-resilience ::= 'resilient'
        attribute-resilience ::= 'fragile'
        attribute-resilience ::= 'born_fragile'

See the resilience design.

#### `inout` Attribute

        attribute-inout ::= 'inout'

`inout` is only valid in a `type` that appears within either a `pattern` of a `function-signature` or the input type of a function type.

`inout` indicates that the argument will be passed as an "in-out" 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 indistinguishable from pass-by-reference semantics.

`inout` differs from traditional pass-by-reference when closures are involved. If a closure captures an `inout` parameter, the local value is captured, not the reference. The local value at the time of function exit is written back to the lvalue. If the closure outlives the lifetime of the call, the local value lives independent of the original lvalue; further mutations within the closure do not affect the lvalue that was passed as the byref argument. For example, the following code:

        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.
        print("global x = \(x)")
        // These calls only update the captured local 'x', which is now independent
        // of the inout parameter.
        print("local x = \(f())")
        print("local x = \(f())")
        print("local x = \(f())")

        print("global x = \(x)")

will print:

        global x = 220
        local x = 221
        local x = 222
        local x = 223
        global x = 220

The type being annotated must be 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). We may also need some way of representing this will be consumed by the nth curry.

#### autoclosure Attribute

        attribute-autoclosure ::= 'autoclosure'

The `autoclosure` attribute modifies a function type, changing the behavior of any assignment into (or initialization of) a value with the function type. Instead of requiring that the rvalue and lvalue have the same function type, an "auto closing" function type requires its initializer expression to have the same type as the function's result type, and it implicitly binds a closure over this expression. This is typically useful for function arguments that want to capture computation that can be run lazily.

`autoclosure` is only valid in a `type` of a syntactic function type that is defined to take a syntactic empty tuple.

      // An auto closure value.  This captures an implicit closure over the
      // specified expression, instead of the expression itself.
      var a : @autoclosure () -> Int = 4

      // Definition of an 'assert' function.  Assertions and logging routines
      // often want to conditionally evaluate their argument.
      func assert(_ condition : @autoclosure () -> Bool)

      // Definition of the || operator - it captures its right hand side as
      // an autoclosure so it can short-circuit evaluate it.
      func [infix_left=110] || (lhs: Bool, rhs: @autoclosure ()->Bool) -> Bool

      // Example uses of these functions:
      assert(i < j)
      if (a == 0 || b == 42) { ... }

#### No Return Attribute

        attribute-noreturn ::= 'noreturn'

Attribute `noreturn` is only valid in the attribute list of a function declaration or in the attribute list of a `type` that describes a syntactic function type.

`noreturn` indicates to the compiler that the function will not return to the caller. This attribute should be used to suppress the uninitialized variable, missing return warnings and errors. The compiler is also allowed to more aggressively optimize the code in presence of this attribute.

If a function with no a `noreturn` attribute contains a `return` statement, an error will be raised.

## Types

        type ::= attribute-list type-function
        type ::= attribute-list type-array

        type-simple ::= type-identifier
        type-simple ::= type-tuple
        type-simple ::= type-composition
        type-simple ::= type-metatype
        type-simple ::= type-optional

Swift has a small collection of core datatypes that are built into the compiler. Most user-facing datatypes are defined by the standard library or declared as a user defined types.

### Metatypes

Each type has a corresponding metatype, with the same name as the type, that is injected into the standard name lookup scope when a type is declared. This allows access to 'static functions' through dot syntax. For example:

        // Declares a type 'foo' as well as its metatype.
        struct foo {
          static func bar() {}
        }

        // Declares x to be of type foo.  A reference to a name in type context
        // refers to the type itself.
        var x : foo

        // Accesses a static function on the foo metatype.  In a value context, the
        // name of its type refers to its metatype.
        foo.bar()

### Fully-Typed Types

A type may be fully-typed. A type is fully-typed unless one of the following conditions hold:

1. It is a function type whose result or input type is not fully-typed.
2. It is a tuple type with an element that is not fully-typed. A tuple element is fully-typed unless it has no explicit type (which is permitted for defaultable elements) or its explicit type is not fully-typed. In other words, a type is fully-typed unless it syntactically contains a tuple element with no explicit type annotation.

A type being 'fully-typed' informally means that the type is specified directly from its type annotation without needing contextual or other information to resolve its type.

### Materializable Types

A type may be materializable. A type is materializable unless it is 1) annotated with a `inout` attribute or 2) a tuple with a non-materializable element type. In general, variables must have materializable type.

### Named Types

        type-identifier ::= type-identifier-component ('.' type-identifier-component)*
        type-identifier-component ::= identifier generic-args?

Named types may be used simply by using their name. Named types are introduced by typealias declarations or through type declarations that expand to one.

        typealias location = (x : Int, y : Int)
        var x : location      // use of a named type.

Type names may use dot syntax to refer to names types declared in other modules or types nested within other types.

        // Direct reference to a member of another module.
        var x : Swift.Int

Each component of a named type may be followed by a list of generic parameters for that component enclosed in angle brackets `<>`.

        // A generic class definition.
        class Dict<K, V> { }

        // A variable of a generic instance type.
        var map : Dict<String, Int>

### Tuple Types

Tuples are everywhere in Swift: even the argument list of a function is a tuple of those arguments.

        type-tuple ::= '(' type-tuple-body? ')'
        type-tuple-body ::= type-tuple-element (',' type-tuple-element)* '...'?
        type-tuple-element ::= identifier ':' type
        type-tuple-element ::= type

Syntactically, tuple types are simply a (possibly empty) list of elements enclosed in parentheses. A tuple type with a single, anonymous element is exactly that type: the parentheses are treated as grouping parentheses.

Tuples are the low-level form of data aggregation in Swift, and are used as the building block of function argument lists, multiple return values, enum bodies, etc. Because tuples are widely accessible and available everywhere in the language, aggregate data access and transformation is uniform and powerful.

Each element of a tuple contains an optional name followed by a type.

If the tuple body ends with '...', the tuple is a varargs tuple. The type of the last element is changed from T to T[], and there are special rules for converting an expression to varargs tuple type.

      // Variable definitions.
      var a : ()
      var b : (Int, Int)
      var c : (x : (), y : Int)

      // Tuple type inferred from an initializers:
      var m = ()                     // Type = ()
      var n = (x: 1, y: 2)           // Type = (x : Int, y : Int)
      var o = (1, 2, 3)              // Type = (Int, Int, Int)

      // Function argument and result is a tuple type.
      func foo(_ x : Int, y : Int) -> (val : Int, err : Int)

      // enum and struct declarations with tuple values.
      struct S {
        var (a : Int, b : Int)
      }
      enum Vertex {
        case Point2(x : Int, y : Int)
        case Point3(x : Int, y : Int, z : Int)
        case Point4(w : Int, x : Int, y : Int, z : Int)
      }

### Function Types

        type-function ::= type-tuple '->' type

Function types have a single input and single result type, separated by an arrow. Because each of the types is allowed to be a tuple, we trivially support multiple arguments and multiple results. "Function" types are more properly known as a "closure" type, because they can embody any context captured when the function value was formed.

The result type of a function type must be materializable. The argument type of a function is always required to be parenthesized (a tuple). The behavior of function types may be modified with the `autoclosure` attribute.

Because of the grammar structure, a nested function type like "(a) -> (b) -> c" is parsed as "(a) -> ((b) -> c)". This means that if you declare this that you can pass it one argument to get a function that "takes b and returns c" or you can pass two arguments to "get a c". This is known as currying. For example:

        // A simple function that takes a tuple and returns Int:
        var a : (a : Int, b : Int) -> Int

        // A simple function that returns multiple values:
        var a : (a : Int, b : Int) -> (val: Int, err: Int)

        // Declare a function that returns a function:
        var x : (Int) -> (Int) -> Int

        // y has type (Int) -> Int
        var y = x(1)

        // z1 and z2 both has type Int, and both have the same value (assuming
        // the function had no side effects).
        var z1 = x(1)(2)
        var z2 = y(2)

        // An auto closure value.  This captures an implicit closure over the
        // specified expression, instead of the expression itself.
        var a : @autoclosure () -> Int = 4

### Enum Types

'enum' types are known as algebraic data types (ADTs) by the broader programming language community. We name them 'enum' after C enums, because ADTs fulfill many of the same roles as enums in the C tradition.

an enum type is a simple discriminated union: the runtime representation of a value of enum type only has one of the specified elements at a time.

All of the element types of an enum type must be materializable.

an enum type is defined by a enum decl.

Values of enum type may not be default initialized unless the user provides a no-argument constructor.

The enum metatype has a member corresponding to each declared element. For elements with a declared type, this member is a function which can construct an enum containing that element. For elements without a declared type, the member is simply an enum value for that element. A enum value has no accessible members except those explicitly defined by the user.

A reference to a member of the enum metatype can be shortened using delayed identifier resolution with context sensitive type inference.

The enum's value can be tested and accessed by pattern-matching the enum against a enum element pattern.

TODO: Should attributes be allowed on enum elements? TODO: Eventually, with generics we'll have equality and inequality operators. Enum decls should be able to implicitly define these for their types. TODO: Need pattern matching and element extraction.

### Array Types

Note that array types are parsed inside-out, with the first bounds clause being the outermost one. This little oddity is required for the bounds of nested arrays to correspond in sequence to subscript indexes. That is, given an array "x : Int[5][7][11][13]" and a chained subscript expression of the form "x[i][j][k][l]", we really want "i" to be bounded by 5, "j" by 7, and so on. This is probably the only case where C's rule of "declaration follows use" really makes sense. There's precedent for this in many languages, including Java and C#.

        type-array ::= type-simple
        type-array ::= type-array '[' ']'
        type-array ::= type-array '[' expr ']'

Array types include a base type and an optional size. Array types indicate 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).

While they look syntactically very similar, an array type with a size has very different semantics than an array without. In the former case, the type indicates a declaration of actual storage space. In the later case, the type indicates storage space allocated elsewhere of runtime-specified size.

For an array with a size, the size must be more than zero (no indices would be valid). For now, the array size must be a literal integer. TODO: Define a notion like C's integer-constant-expression for how constant folding works.

The element type of an array type must be materializable.

FIXME: Int[][] not valid because the element type isn't sized. We need some constraint to reject this, or do we?

Some example array types:

        // A simple array declaration:
        var a : Int[4]

        // A reference to another array:
        var b : Int[] = a

        // Declare a two dimensional array:
        var c : Int[4][4]

        // Declare a reference to another array, two dimensional:
        var d : Int[4][]

        // Declare an array of function pointers:
        var array_fn_ptrs : (: (Int) -> Int)[42]
        var g = array_fn_ptrs[12](4)

        // Without parens, this is a function that returns a fixed size array:
        var fn_returning_array : (Int) -> Int[42]
        var h : Int[42] = fn_returning_array(4)

        // You can even have arrays of tuples and other things, these work right
        // through composition:
        var array_of_tuples : (a : Int, b : Int)[42]
        var tuple_of_arrays : (a : Int[42], b : Int[42])

        array_of_tuples[12].a = array_of_tuples[13].b
        tuple_of_arrays.a[12] = array_of_tuples.b[13]

### Metatype Types

        type-metatype ::= type-simple '.' 'Type'

Every type has an associated metatype `type(of: T)`. A value of the metatype type is a reference to a global object which describes the type. Most metatype types are singleton and therefore require no storage, but metatypes associated with class types follow the same subtyping rules as their associated class types and therefore are not singleton.

### Optional Types

Similar constructs exist in Haskell (Maybe), the Boost library (Optional), and C++14 (optional).

          type-optional ::= type-simple '?'-postfix

An optional type is syntactic sugar for the library type Optional<T>. This is a enum with two cases: None and Some, used to represent a value that may or may not be present.

Swift provides a number of special, builtin behaviors involving this library type:

- There is an implicit conversion from any type `T` to the corresponding optional type `T?`.
- `weak` variables must have type `T?` and automatically become `None` when the referent begins deallocation.
- The optional-chaining operator works on values of type `T?`.
- Several other expressions generate values of type `T?`.

To support these intrinsic use cases, the library is required to provide functions with these exact signatures:

- `func _doesOptionalHaveValueAsBool<T>(v : T?) -> Bool`
- `func _diagnoseUnexpectedNilOptional()`
- `func _getOptionalValue<T>(v : T?) -> T`

Since optional types are part of the type-simple grammar, it is not possible to write `T[]?` for an optional array. Use `(T[]?)` instead.

Some example optional types:

          // A simple optional declaration:
          var a : Int? // equivalent to Optional<Int>

          // An empty optional:
          var b : Int? = .None

          // Declare an array of optionals:
          var c : [Int?] = [10, nil, 42]

### Protocol Composition Types

       type-composition ::= type-identifier ('&' type-identifier)*

A protocol composition type composes together a number of protocols to describe a type that meets the requirements of each of those protocols. A protocol composition type `A & B` is similar to an explicitly-defined protocol that inherits both `A` and `B`

    protocol C : A, B { }

but without the need to introduce a new name.

If we drop implicit conformance to protocols, protocol composition types become much more important, because they allow you to give a name to a composition without requiring types to explicitly conform to that name.

Each of the types named in the `type-composition` shall refer to either a protocol or to a protocol composition. The empty protocol composition is the keyword `Any` and every type conforms to it.

        // A value that represents any type
        var any : Any = 17

        // A value that conforms to both the Document and Enumerator protocols
        var doc : Document & Enumerator
        doc.isEmpty()       // uses Enumerator.isEmpty()
        doc.title = "Hello" // uses Document.title

### Type Inheritance

        inheritance ::= ':' type-identifier (',' type-identifier)*

A named type (e.g., a class, struct, enum, or protocol) can "inherit" some set of protocols, which implies that any object of that type conforms to each of those protocols. When a protocol inherits other protocols, the set of requirements from all of those protocols is effectivel aggregated into the protocol, and a type that conforms to the current protocol shall conform to each of the protocols that it inherits.

When a non-protocol type inherits a protocol, it is specifying explicitly that it conforms to that protocol. The program is ill-formed if the type does not conform to the protocol.

        protocol VersionedDocument : Document { // every VersionedDocument is a Document
          func bumpVersion()
        }

        func print(_ doc : Document) { /* ... */ }

        var myDocument : VersionedDocument;
        print(myDocument) // okay: a VersionedDocument is a Document

        class StoredHTML : VersionedDocument { // okay: StoredHTML conforms to VersionedDocument
          var Title : String
          func bumpVersion()
        }

## Expressions

Support for user-defined operators causes some amount of parsing to be delayed until after name resolution has occurred. Other restrictions and disambiguations in the grammar permit the parser to decide all other aspects of parsing, such as where statements must be divided.
Semicolons in C are generally just clutter. Swift generally tries to define away the need for them.

        expr          ::= expr-basic
        expr          ::= expr-trailing-closure expr-cast?

        expr-basic    ::= expr-sequence expr-cast?

        expr-sequence ::= expr-unary expr-binary*

        expr-primary  ::= expr-literal
        expr-primary  ::= expr-identifier
        expr-primary  ::= expr-super
        expr-primary  ::= expr-closure
        expr-primary  ::= expr-anon-closure-arg
        expr-primary  ::= expr-paren
        expr-primary  ::= expr-delayed-identifier

        expr-postfix  ::= expr-primary
        expr-postfix  ::= expr-postfix operator-postfix
        expr-postfix  ::= expr-new
        expr-postfix  ::= expr-dot
        expr-postfix  ::= expr-metatype
        expr-postfix  ::= expr-init
        expr-postfix  ::= expr-subscript
        expr-postfix  ::= expr-call
        expr-postfix  ::= expr-optional
        expr-force-value  ::= expr-force-value

At the top level of the expression grammar, expressions are a sequence of unary expressions joined by binary operators. When parsing an expr, a binary operator immediately following an expr-unary continues the expression, and the program is ill-formed if it is not then followed by another expr-unary. This resolves an ambiguity which could otherwise arise in statement contexts due to semicolon elision.

        5 !- +~123 -+- ~+6
        (foo)(())
        bar(49+1)
        baz()

A unary or binary expression may optionally be followed by a cast operator.

### Binary Operators

Should this use the expr-identifier production to allow qualified identifiers? This would allow "foo Swift.+ bar". Is ADL or something like it enough?

        expr-binary ::= op-binary-or-ternary expr-unary expr-cast?

        op-binary-or-ternary ::= operator-binary
        op-binary-or-ternary ::= '='
        op-binary-or-ternary ::= '?'-infix expr-sequence ':'

        expr-cast ::= 'is' type
        expr-cast ::= 'as' type

Infix binary expressions are not formed during parsing. Instead, they are formed after name resolution by building a tree from an operator-delimited sequence of unary expressions. Precedence and associativity are determined by the infix attribute on the resolved names, which must fully agree.

If an operator is used as a binary operator, but name resolution does not find at least one function of binary operator type, the expression is ill-formed.

A simple example is:

        4 + 5 * 123

### Builtin Binary Operators

In addition to user-defined operators, a handful of builtin operators are defined that parse inside binary expressions with predefined precedence and associativity.

#### Assignment operator

The assignment operator `a = b` updates the value of `a` with the value of `b`. Its precedence is hardcoded as if declared as follows:

        // Not valid Swift code
        infix operator = {
          precedence 90
          associativity right
        }

The left-hand operand must be an lvalue, or a tuple of lvalues. Assigning to a tuple of lvalues performs destructuring reassignment.

        var (a, b) = (1, 2)

        // Swap two values.
        (a, b) = (b, a)

        // Reassign two values.
        (a, b) = (11, 22)

        // Reassign two values by destructuring a tuple.
        var tuple = (111, 222)
        (a, b) = tuple

An assignment expression evaluates to void. Unlike C, productions such as these are invalid:

        // Error: x = y doesn't return Bool
        if x = y { }

        // Error: (y = z) doesn't return Int
        var x, y, z : Int
        x = y = z

#### Ternary operator

The ternary operator `a ? b : c` conditionally evaluates its middle or right operand based on the value of its left operand. Its precedence is hardcoded as if the middle `? b :` subexpression were a binary operator declared as follows:

        // Not valid Swift code
        infix operator ?...: {
          precedence 100
          associativity right
        }

The subexpression to the left of the '?' is evaluated, and is converted to 'Bool' using the result's 'boolValue' property if it is not already 'Bool'. If the condition is true, the subexpression to the right of '?' is evaluated, and its result becomes the result of the expression. If the condition is false, the subexpression to the right of ':' is evaluated, and its result becomes the result of the expression. Only one of the '?' or ':' subexpressions will be evaluated. The results of the '?' and ':' subexpressions must be implicitly convertible to a common type, which becomes the type of the ternary expression.

        x += b ? y : z
        x += a ? b ? y : z : w

        for i in 1...101 {
          print(i % 15      ? "fizzbuzz"
                : i %  3 == 0 ? "fizz"
                : i %  5 == 0 ? "buzz"
                : "\(i)")
        }

#### Cast operators

Cast expressions influence the types of their subexpressions. They can appear at the end of a binary operator sequence; their left operand is parsed as if the cast operators were declared as follows:

        // Not valid Swift code
        infix operator as {
          precedence 95
          associativity none
        }

The right operand of all operators is parsed as a type.

- `x as T` will try to cast the value of the expression `x` to the type `T`. If the type of `x` is implicitly convertible to `T`, the conversion is performed and the result of the expression is of type `T`. Otherwise, the result of the expression is of type `T?`. In this case, the type of the operand is checked at runtime, and if it is castable to `T`, the `Optional` result contains the result of the cast. If the cast fails, the result contains `.None`. The latter is only permissible when `T` is a subtype of the compile-time type of `x`. An example:

          var b: B = D()
          var d: D? = b as D
          var b2 = d! as B

- `x is T` will query the type of the value of `x` at runtime. `T` must be a subtype of the compile-time type of `x`. If the runtime value of `x` is `T`, the `is` expression evaluates to true; otherwise, it evaluates to false.

          if b is D {
            var d = (b as D)!
          }

`as` and `is` both parse a type for their right-hand argument. They must be parenthesized if followed by subsequent operators:

        (b as D)?.derivedMethod()
        ((B as D) as D2)
        (b is D) ? (b as D)! : D()

### Unary Operators

        expr-unary   ::= operator-prefix* expr-postfix

If an operator is used as a unary operator, but name resolution does not find at least one function that takes a single argument, the expression is ill-formed.

Simple examples:

        i = -j

### Literals

The type of a literal is inferred from its context, to allow things like "4" to be compatible with any width integer type without 'promotion' rules or casting. In ambiguous cases like "var x = 4", the literals are forced to a default type specified by the standard library.

        expr-literal ::= integer_literal
        expr-literal ::= floating_literal
        expr-literal ::= string_literal
        expr-literal ::= expr-array
        expr-literal ::= expr-dictionary
        expr-literal ::= '__FILE__'
        expr-literal ::= '__LINE__'
        expr-literal ::= '__COLUMN__'

        expr-array ::= '[' expr (',' expr)* ','? ']'
        expr-array ::= '[' ']'

        expr-dictionary ::= '[' expr ':' expr (',' expr ':' expr)* ','? ']'
        expr-dictionary ::= '[' ':' ']'

Numeric literals are either integer, floating point, character, or string depending on its lexical form. The type of the literal is inferred based on its context. If there is no contextual type information for an expression, all unresolved types are inferred to 'IntegerLiteralType' type, to 'FloatLiteralType', and to 'StringLiteralType', respectively. If a literal is used and these types are not defined, then the code is malformed.

A literal is compatible with its inferred type if that type implements an informal protocol required by literals. This informal protocol requires that the type have an unambiguous "type" function defined whose result type is the same as the inferred type, and that takes a single argument that is either itself literal compatible, or is a builtin integer type.

The '`__FILE__`', '`__LINE__`', and '`__COLUMN__`' magic identifiers expand to a literal representation of their position in the source code. '`__FILE__`' expands to a string literal; '`__LINE__`' and '`__COLUMN__`' each expand to an integer literal.

        // File foo.swift

        var file = __FILE__  // file : String = "foo.swift"
        var line = __LINE__  // line : Int = 4
        var col = __COLUMN__ // column : Int = 11

If '`__FILE__`', '`__LINE__`', and/or '`__COLUMN__`' are used as default argument values in a function declaration, they instead expand to the source location of each function call that instantiates the default argument.

        func log(_ message:String,
                 file:String = __FILE__,
                 line:Int = __LINE__) {
          print("\(file):\(line): \(message)")
        }

        log("Orders received")
        doIt()
        log("Job's finished")

### Identifiers

        expr-identifier ::= identifier generic-args?

A raw identifier refers to a value found via unqualified value lookup, and has the type of the declaration returned by name lookup and overload resolution. Value declarations are installed with var and the syntactic sugar forms like func declarations.

If an identifier refers to a generic type, an instance of that generic may be referenced by following the identifier with a list of type parameters enclosed in angle brackets `<>`:

        // A generic struct.
        struct Dict<K,V> {
          init() {}
          static func fromKeysAndValues(_ keys:K[], values:T[]) -> Dict<K,V> {}
        }

        // Construct an instance of the generic struct.
        var foo = Dict<String, Int>()
        // Invoke a type method of an instance of the generic struct.
        var bar = Dict<String, Int>.fromKeysAndValues(
          ["zim", "zang", "zung"],
          [ 123,    456,    789 ])

#### Generic disambiguation

Note that `<` and `>` are used as both angle brackets in generic identifiers and as characters in binary operator names. Because of this, there are potential parsing ambiguities. Swift uses a context-free heuristic to determine whether to parse an expression involving `<` and `>` as a generic parameter list or a binary operator:

- When an identifier is followed by `<`, Swift attempts to parse starting from the `<` as a generic parameter list.
- If it succeeds in parsing a generic parameter list, it looks at the token after the closing `>`. If it sees one of the following tokens:

  > `( [ { } ] ) . , ;`

  then the expression is parsed as a generic parameter list.
- If Swift cannot parse a generic parameter list after the `<`, or the matching `>` is not followed by one of the above tokens, the `<` is parsed as an operator character.

These rules assume that, in most cases, generic type names will be used in constructor expressions as in `Foo<T>(x)` or to access type members as in `Foo<T>.bar()`. Referring to a generic metatype as a value in an expression may require parentheses around the type name.

        // An operator that operates on metatypes.
        infix func +-+ <T, U>(t:T.Type, u:U.Type) -> Foo { }

        var foo = (Dict<String, Int>) +-+ (Array<UnicodeScalar>)
        print(foo)

On the other hand, some expressions involving `<` and `>` operators may misparse as generic arguments as well. These can also be corrected by adding or removing parentheses.

        func foo(_ x:Bool, y:Bool)
        var a,b,c,d,e : Int

        foo(a < b, c > (d + e)) // ERROR: Misparses as (a<b,c>)(d + e)
        foo((a < b), c > (d + e)) // Force parsing as (a < b), (c > (d + e))
        foo(a < b, c > d + e) // Also parses as (a < b), (c > (d + e))

### Super

        expr-super ::= expr-super-method
        expr-super ::= expr-super-subscript
        expr-super ::= expr-super-constructor

        expr-super-method ::= 'super' '.' expr-identifier
        expr-super-subscript ::= 'super' '[' expr ']'
        expr-super-constructor ::= 'super' '.' 'init'

The keyword `super` is used to refer to superclass members from a subclass method. This can be used to access members of a superclass overridden by the subclass. The following forms are allowed:

- A superclass property or method can be accessed with the form `super.name`.
- A superclass subscript accessor can be accessed with the form `super[index]`.
- Within a constructor, a superclass constructor can be accessed with the form `super.init`.

`super` expressions are invalid outside of a subclass method. `super.init` is invalid outside of a subclass constructor. `super.init` furthermore may only be called once per derived constructor, and must be called before the derived constructor accesses `self` or any instance variables.

### Closure Expression

        expr-closure ::= '{' closure-signature? brace-item-list '}'

        closure-signature ::= pattern-tuple func-signature-result? 'in'
        closure-signature ::= identifier (',' identifier*) func-signature-result? 'in'

A closure defines an anonymous function as an expression. Like a func declaration, a closure has parameters, a return type, and some number of statements that are executed when the closure is called. Like local functions, closures can capture values from its enclosing function and closure scopes. Closures are often used in lieu of local functions when the function name would only be used once, to be called by some other function. As a syntax optimization, when the closure contains only a single expression, it's value is used as the result of the closure. Thus, the closure `{ 5 }` is equivalent to `{ return 5 }`.

Unlike func declarations, the return type, parameter types, and even the names of parameters can be omitted from the definition of the closure, making it a concise syntax for small closures. In such cases, the context in which the closure is used must provide information about the parameter and return types. In the special case where the closure consists of only a single expression, that expression participates in the type checking of its context.

        // Takes a closure that it calls to determine an ordering relation.
        func magic(_ val : Int, predicate : (a : Int, b : Int) -> Bool)

        func f() {
          // Compare one way.  Closure is inferred to return Bool and take two ints
          // from the argument context.  This same information infers that $0 and $1
          // both have type 'Int'.
          magic(42, { $0 < $1 })

          // Compare the other way.
          magic(42, { $1 < $0 })

          // Provide parameter names, but infer the types.
          magic(42, { x, y in y < x })

          // Provide parameter names and types.
          magic(42, { (x : Int, y : Int) in y < x })

          // Provide parameter names and types, and return type, with multiple statements.
          magic(42, { (x : Int, y : Int) -> Bool in
            print("Comparing \(x) to \(y).\n")
            return y < x
          })

          // Error, not enough context to infer the type of $0.
          var x = { $0 }
        }

### Anonymous Closure Arguments

        expr-anon-closure-arg ::= dollarident

A use of an identifier whose name fits the "$[0-9]+" regular expression is a reference to an anonymous closure argument that is formed when the containing expression is coerced into a closure context. All other dollar identifiers are invalid.

This can only be used in the body of a closure (expr-closure) that does not have explicitly-specified parameters.

### Delayed Identifier Resolution

The ".bar" syntax was picked because it is related to the syntax of a fully qualified "foo.bar" reference.

        expr-delayed-identifier ::= '.' identifier expr-paren?

A delayed identifier expression refers to a case of an enum type or a type member of a nominal type, without knowing which type it is referring to. The expression is resolved to a member of a concrete type through context-sensitive type inference. When it is followed by an expr-paren, the member must either be an enum case that carries a value or a (type) member function.

        enum Direction { case Up, Down }
        func search(_ val : Int, direction : Direction)

        func f() {
          search(42, .Up)
          search(17, .Down)
        }

### Parenthesized Expressions

        expr-paren      ::= '(' ')'
        expr-paren      ::= '(' expr-paren-element (',' expr-paren-element)* ')'
        expr-paren-element ::= (identifier ':')? expr

Parentheses expressions contain an (optionally empty) list of optionally named values. Parentheses in an expression context denote one of two things: 1) grouping parentheses, or 2) a tuple literal.

Grouping parentheses occur when there is exactly one value in the list and that value does not have a name. In this case, the type of the parenthesis expression is the type of the single value.

All other cases are tuple literals. The type of the expression is a tuple type whose elements and order match that of the initializer. If there are any named elements, those elements become names for the tuple type. A parenthesis expression with no value has a type of the empty tuple.

Some examples:

        // Simple grouping parenthesis.
        var a = (4)             // Type = Int
        var b = (4+a)           // Type = Int

        // Tuple literals.
        var c = ()               // Type = ()
        var d = (4, 5)           // Type = (Int, Int)
        var e = (c, d)           // Type = ((), (Int, Int))

        var f = (x : 4, y : 5)   // Type = (x : Int, y : Int)
        var g = (4, y : 5, 6)    // Type = (Int, y : Int, Int)

        // Named arguments to functions.
        func foo(_ a : Int, b : Int)
        foo(b = 4, a = 1)

### Dot Expressions

        expr-dot ::= expr-postfix '.' integer_literal

If the base expression has tuple type, then the magic identifier "[0-9]+" accesses the specified anonymous member of the tuple. Otherwise, this form is invalid.

        expr-dot ::= expr-postfix '.' expr-identifier

If the base expression has tuple type and if the identifier is the name of a field in the tuple, then this is a reference to the specified field.

Otherwise, dot name lookup is performed, and this expression is treated as function application. This allows looking up members in modules, metatypes, etc.

### Initializer Expressions

        expr-init ::= expr-postfix '.' 'init'

An initializer reference refers to a set of initializers of the base expression. The base expression must be the `self` parameter of an initializer, which is used to delegate the initialization of the object to another initializer.

        class X {
          init() {
            self.init(5) // delegate to initializer below
          }

          init(value: Int) { /* ... */ }
        }

### Subscript Expressions

There is no "built-in" semantics for subscripting. Rather, all subscripting semantics is implemented via subscript declarations in the library.
We require that the '[' not be the first token on a line, so that a statement can begin with an array expression.

        expr-subscript ::= expr-postfix '[' expr ']'

A subscript expression invokes a subscript getter or setter on the type of the `expr-postfix`. The `expr` is used as the subscript argument, which will be provided to either the getter or setter depending on whether the subscript expression is used as an rvalue (reading) or lvalue (writing), respectively. A subscript expression that resolves to a subscript declaration with no setter cannot be modified.

### New Expressions

It's not really clear what the behavior of multiple bounds should be.
We should probably allow an initializer. The semantics would be to evaluate that constructor for each element constructed.

        expr-new        ::= 'new' type-identifier expr-new-bounds

        expr-new-bounds ::= expr-new-bound
        expr-new-bounds ::= expr-new-bounds expr-new-bound
        expr-new-bound  ::= '[' expr? ']'

Allocates and initializes a new array of objects. The first clause must be an expression; subsequent bounds, if present, must be constant under the usual rules for array types. The opening square bracket must be on the same line as the type name.

### Function Application

        expr-call ::= expr-postfix expr-paren

The leading `'('` of the `expr-paren` must not be the first token on a line. This greatly reduces the likelihood of confusion from semicolon elision, without requiring feedback from the typechecker or more aggressive whitespace sensitivity.

If the `expr-postfix` refers to a (possibly parenthesized) name of a type, the `expr-paren` is first coerced to the type named by `expr-postfix`. If that coercion fails, then the `expr-postfix` refers to the set of constructors for that type.

Simple examples:

        // Application of an empty tuple to the function f.
        f()
        // Application of 4 to the function f.
        g(4)

        // Application of 4 to the function returned by h().
        var h : (Int) -> (Int) -> Int
        ...
        h()(4)

        // Two separate statements
        i()
        (j <+ 2)()

### Trailing Closures

It is possible to model trailing closures as simply another way to perform a function call, forgoing the syntactic transformation for expr-call, if functions meant to be used with trailing closures are written as curried functions, e.g.,

    func map<T, U>(_ array : T[])(fn : (T) -> U) -> U[] { ... }

There are two problems with this (admittedly simpler) design. First, functions imported from C, C++, and Objective-C won't ever be written in this curried syntax, so we would have to implement redundant entry points to enable this syntax. Second, this design forces the idea of currying front and center for Swift programmers who otherwise wouldn't care, for mostly theoretical reasons.

        expr-trailing-closure ::= expr-postfix expr-closure+

A postfix expression followed by a closure will be invoked with the closure as its argument. This syntax is referred to as a "trailing" closure, because the closure itself is outside the parentheses used to call the expression. Trailing closures are syntactic sugar that eliminates the awkwardness of closing a function call with "})", where the "}" ends the closure and the ")" ends the call.

Trailing closures use a simple syntactic translation, making them purely syntactic sugar. If the postfix expression preceding the trailing closure is an expr-call, the closure is added to the end of the expr-paren of that call. Otherwise, the postfix expression is (implicitly) called with the trailing closure as its only argument.

      dispatch_async(q) {
        print("Whenever you get around to it\n")
      }

### Optional Chaining

        expr-optional ::= expr-postfix '?'-postfix

The optional-chaining operator provides a convenient syntax for dereferencing, calling, or subscripting optional values.

Informally, the operator attempts to strip one level of `Optional` from its operand, and if that fails, all the following postfix operators are skipped and just evaluate to `None`.

More formally:

- The operand must be convertible to type `T?` for some type `T`. As a special rule, the expression is ill-formed if the operand is converted to optional type by the implicit conversion from `T` to `T?`.
- The expression itself then has type `T` (and is an r-value).
- A `postfix-expression` E1 is said to directly chain to a `postfix-expression` E2 if E1 is syntactically the `postfix-expression` base of `E2`; note that this does not include any syntactic nesting, e.g. via parentheses. E1 chains to E2 if they are the same expression or E1 directly chains to an expression which chains to E2. This relation has a maximum, called the largest chained expression.
- The largest chained expression of an `expr-optional` must be convertible to an r-value of type `U?` for some type `U`. Note that a single expression may be the largest chained expression of multiple `expr-optional`s.
- If the operand evaluates to `Some(x) : T?` for some value `x : T`, the expression yields `x`.
- If the operand evaluates to `None : T?`, evaluation of all the chained expressions immediately terminates, and the largest chained expression yields the value `None : U?`.

### Forcing an expression's value

        expr-force-value ::= expr-postfix '!'

The postfix '!' forces an optional value to its stored value (i.e., the `x` in `.Some(x)`), failing at runtime if the optional is `.None`.

## Statements

Statements can only exist in contexts that are themselves a stmt. Statements have no type, they just induce control flow changes. We choose to use constructs that will be familiar to a broad range of C/Java programmers.

        stmt ::= stmt-semicolon
        stmt ::= stmt-if
        stmt ::= stmt-while
        stmt ::= stmt-repeat-while
        stmt ::= stmt-for-c-style
        stmt ::= stmt-for-each
        stmt ::= stmt-switch
        stmt ::= stmt-control-transfer

        stmt-control-transfer ::= stmt-return
        stmt-control-transfer ::= stmt-break
        stmt-control-transfer ::= stmt-continue
        stmt-control-transfer ::= stmt-fallthrough

Statements provide the control flow constructs of function bodies and top-level code.

        // A function with some statements.
        func fib(_ v : Int) -> Int {
          if v < 2 {
            return v
          }
          return fib(v-1)+fib(v-2)
        }

### Semicolon Statement

Allowing semicolons as statements causes us to allow semicolons as statement separators as well. This, in turn, means that we don't reject code that has semicolons after each statement, which will be common when people first start getting used to Swift.

        stmt-semicolon ::= ';'

The semicolon statement has no effect.

### 'return' Statement

        stmt-return ::= 'return' expr
        stmt-return ::= 'return'

The return statement sets the return value of the current func declaration or closure expression and transfers control out of the function. It sets the return value by converting the specified expression result (or '()' if none is specified) to the return type of the 'func'.

The stmt-return grammar is ambiguous: "{ return 4 }" could be parsed as {"return" "4"} or as a single statement. Ambiguity here is resolved toward the first production, because control flow can't transfer to an subexpression.

### 'if' Statement

We require braces around the body of an 'if' for two reasons: first, it eliminates the need for parentheses around the condition by making them visually distinctive. Second, it will eliminate all the dithering about whether and when people should, or should not, use braces for if bodies.

        stmt-if      ::= 'if' expr-basic brace-item-list stmt-if-else?
        stmt-if-else ::= 'else' brace-item-list
        stmt-if-else ::= 'else' stmt-if

'if' statements provide a simple control transfer operations that evaluates the condition, gets the 'boolValue' property of the result if the result not a 'Bool', then determines the direction of the branch based on the result. (Internally, the standard library type 'Bool' has a boolValue property that returns a 'Builtin.Int1'.) It is an error if the type of the expression is context-dependent or some non-Bool type.

Some examples include:

        if true {
          /*...*/
        }

        if X == 4 {
        } else {
        }

        if X == 4 {
        } else if X == 5 {
        } else {
        }

### 'while' Statement

        stmt-while ::= 'while' expr-basic brace-item-list

'while' statements provide simple loop construct which (on each iteration 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 the expression is context-dependent or some non-Bool type.

Some examples include:

        while true {
          /*...*/
        }

        while X == 4 {
          X = 3
        }

### 'repeat-while' Statement

        stmt-repeat-while ::= 'repeat' brace-item-list 'while' 'expr

'repeat-while' statements provide simple loop construct which (on each iteration of the loop) evaluates the body, then evaluates the condition, getting 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 the expression is context-dependent or some non-Bool type.

Some examples include:

        repeat {
          /*...*/
        } while true

        repeat {
          X = 3
        } while X == 4

### C-Style 'for' Statement

        stmt-for-c-style    ::= 'for'     stmt-for-c-style-init? ';' expr? ';' stmt-for-c-style-inc? brace-item-list
        stmt-for-c-style    ::= 'for' '(' stmt-for-c-style-init? ';' expr? ';' stmt-for-c-style-inc? ')' brace-item-list
        stmt-for-c-style-init ::= decl-var
        stmt-for-c-style-init ::= expr (',' expr)*
        stmt-for-c-style-inc ::= expr-basic (',' expr-basic)*

C-Style 'for' statements provide simple loop construct which evaluates 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.

Some examples include:

        for i = 0; i != 10; ++i {
          /*...*/
        }

        for (i = 0; i != 10; ++i) {
          /*...*/
        }

        for var (i,j) = (0,1); i != 10; ++i {
          /*...*/
        }

### 'for-each' Statement

        stmt-for-each ::= 'for' pattern 'in' expr-basic brace-item-list

Enumerator-based 'for' statements provide enumeration over the values in a container. The `expr` is either a container or an enumerator; and respectively, it either conforms to the formal Enumeration or formal Enumerator protocol.

Note that each iteration of the loop declares a distinct variable for each variable in the pattern. For example, in a loop like "for i in 0...10", if i is captured inside the loop, each iteration captures a different "i", so there would be a total of ten versions generated each time the loop runs.

Some examples include:

        for i in 0...100 {
          print(String(i));
        }

## Protocols

## Objects

## Generics

### Generic Parameters

        generic-params ::= '<' generic-param (',' generic-param)* where-clause? '>'

        generic-param ::= identifier
        generic-param ::= identifier ':' type-identifier
        generic-param ::= identifier ':' type-composition

        where-clause ::= 'where' requirement (',' requirement) *

        requirement ::= conformance-requirement
                    ::= same-type-requirement

        conformance-requirement ::= type-identifier ':' type-identifier
        conformance-requirement ::= type-identifier ':' type-composition

        same-type-requirement ::= type-identifier '==' type-identifier

A generic function or type is parameterized by a given set of generic parameters. The generic parameters each have a name as well as some set of requirements that specify the capabilities that any corresponding generic argument might have. For example, the generic parameter `T : CustomStringConvertible` requires that any generic argument substituted for the generic parameter `T` conform to the protocol `CustomStringConvertible`. Similarly, a generic parameter `U : SomeClass` requires that any generic argument substituted for the generic parameter `U` inherit from the class `SomeClass`.

Additional requirements on generic parameters and associated types of generic parameters can be introduced via the "where" clause, which can include additional protocol-conformance requirements (e.g., the generic parameter list `<T where T : CustomStringConvertible>`, which is equivalent to `<T : CustomStringConvertible>`), as well as same-type requirements that require two types to be identical (e.g., `<T : Collection, U : Collection where T.Element == U.Element>`).

### Generic Arguments

        generic-args ::= '<' generic-arg (',' generic-arg)* '>'

        generic-arg ::= type

Generic argument lists specify the generic arguments to be provided to a generic type or function, which replace the generic parameters of that type or function to produce a specialized version of that type or function. For example, given a generic class:

        class Dictionary<Key : Hashable, Value> { /* ... */ }

The type `Dictionary<String, Int>`, replaces the generic parameter `Key` with `String` and the generic parameter `Value` with `Int`. Each generic argument must satisfy all of the requirements of its corresponding generic parameter (e.g., `String` must conform to the `Hashable` protocol), and all generic arguments, when taken together, must satisfy the additional requirements specified in the `where` clause.

## Name Binding

Name binding in swift is performed in different ways depending on what language entity is being considered:

Value names (for var and func declarations) and type names (for typealias, enum, and struct declarations) follow the same scope and name lookup rules as described below.

tuple element names

scope within enum decls

Context sensitive member references are resolved during type checking.

### Scopes for Type and Value Names

### Name Lookup Unqualified Value Names

### "dot" Name Lookup Value Names

### Name Lookup for Type and Value Names

Basic algo:

- Search the current scope tree for a local name. Local names cannot be forward referenced.
- Bind to names defined in the current component, including the current module. TODO: is this a good thing? We could require explicit imports if we wanted to.
- Bind to identifiers that are imported with an import directive. Imports are searched in order of introduction (top-down). The location of an import directive in a file (e.g. between func decls) does not affect name lookup, but the order of imports w.r.t. each other does.

Shadowing: Given a ValueDecl D1 in the current module and a ValueDecl D2 in an imported module with the same name and a member of the same type (if relevant): 1. If D1 is a TypeDecl, D2 is shadowed. 2. If neither D1 nor D2 is a TypeDecl, and they have the same type, D2 is shadowed. If a declaration in an imported module is shadowed by any declaration in the current module, it is not found by unqualified global lookup or lookup for members of a type.

### Name Lookup for Dot Expressions

Dot Expressions bind to name of tuple elements.

## Type Checking

Binary expressions, function application, etc.

### Standard Conversions

### Anonymous Argument Resolution

### Context Sensitive Type Resolution