Create a scope for each case block to contain bindings from its patterns, and invoke addVarsToScope after parsing case label patterns to introduce vars into that scope. Refactor addVarsToScope to use an ASTWalker so it finds pattern vars embedded in expr patterns.
Swift SVN r5899
If we're under a 'var' pattern, reinterpret bare identifier exprs early on as variable bindings so we will be able to add them to the case scope.
Swift SVN r5898
Parse patterns as top-level expression productions, for name binding to validate and convert into proper patterns later. If the type-checker sees an UnboundPattern production survive name binding (currently always), then raise a helpful "patterns don't belong here" error.
Swift SVN r5842
Because of '~=' lookahead and precedence parsing, we need to be able to parse pattern productions in expression position and validate them after name binding. Add an unresolved Expr node that can hold a subpattern for this purpose.
Swift SVN r5825
Currently not only we insert names in non-resolvable scopes, but every
overloaded name gets stored only once (the last one wins). Everything just
happens to work, because we never do name lookup in these scopes.
I also added a ScopeKind to every Scope (instead of just adding the bit --
isResolvableScope), because this provides a better debugging experience, and
centralizes knowledge about what scope kind is resolvable in the function
isResolvableScope(ScopeKind).
Swift SVN r5822
I talked to John about parsing patterns today, and because of the magnitude of name-lookup-dependent ambiguities between patterns and expressions, we agreed that at least for a first-pass implementation it makes sense to parse patterns as extensions of the expr grammar and charge name binding with distinguishing patterns from expressions. This gets us out of needing the concept of an "unresolved pattern", at least in the short term.
Swift SVN r5808
Introduce Pattern subclasses for the 'is T', 'T(<pattern>)', and '<expr>' pattern syntaxes we'll be introducing for pattern-matching "switch" statements. Also add an 'UnresolvedCalLPattern' to act as an intermediate for name lookup to resolve to a nominal type, oneof element, or function call expression pattern. Since we'll need to be able to rewrite patterns like we do expressions, add setters to AST nodes that contain references to subpatterns. Implement some basic walking logic in places we search patterns for var decls, but punt on any more complex type-checking or SILGen derived from these nodes until we actually use them.
Swift SVN r5780
parser state. Backtracking will be used a lot when we implement delayed
parsing for function bodies, and we don't want to leak lexer and parser state
details to AST classes when we store the state for the first and last token for
the function body.
Swift SVN r5759
Sub-patterns are now considered part of the enclosing pattern, so if the
parent pattern pointer is const, the child pointer will be too.
I changed the minimal number of files to make this work, but future code
should use "const Pattern *" when intended, and "Pattern *" only if they
intend to modify the pattern.
Swift SVN r5743
Improve our representations of casts in the AST and SIL so that 'as!' and 'is' (and eventually 'as?') can share almost all of the same type-checking, SILGen, and IRGen code.
In the AST, we now represent 'as!' and 'is' as UnconditionalCheckedCastExpr and IsaExpr, respectively, with the semantic variations of cast (downcast, super-to-archetype, archetype-to-concrete, etc.) discriminated by an enum field. This keeps the user-visible syntactic and type behavior differences of the two forms cleanly separated for AST consumers.
At the SIL level, we transpose the representation so that the different cast semantics get their own instructions and the conditional/unconditional cast behavior is indicated by an enum, making it easy for IRGen to discriminate the different code paths for the different semantics. We also add an 'IsNonnull' instruction to cover the conditional-cast-result-to-boolean conversion common to all the forms of 'is'.
The upshot of all this is that 'x is T' now works for all the new archetype and existential cast forms supported by 'as!'.
Swift SVN r5737
Open us 'a as! T' to allow dynamic casts from archetypes to archetypes, archetypes to concrete types, existentials to archetypes, and existentials to concrete types. When the type-checker finds these cases, generate new Unchecked*To*Expr node types for each case.
We don't yet check whether the target type actually makes sense with the constraints of the archetype or existential, nor do we implement the SILGen/IRGen backends for these operations. We also don't extend 'x is T' to query the new operation kinds. There's a better factoring that would allow 'as!' and 'is' to share more code. For now, I want to make sure 'x as! T' continues to work for ObjC APIs when we flip the switch to import protocol types.
Swift SVN r5611
Treat 'as' and 'is' as fixed-precedence binary operators, like we now do '=' and '? ... :'. However, since 'as' and 'is' max-munch-parse a type name on their RHS, we only parse them at the tail end of a SequenceExpr. This not only makes 'a = b as T' work as expected again, but also makes 'a += b as T' work, fixing <rdar://problem/13772819>.
Swift SVN r5514
We can save some source code noise and ASTContext allocation traffic by representing unsequenced assignments and ternaries using AssignExpr/IfExpr with the left and right subnodes nulled out, filling them in during sequence folding.
Swift SVN r5509
Parse '=' as a binary operator with fixed precedence, parsing it into a temporary UnsequencedAssignExpr that gets matched to operands and turned into an AssignExpr during sequence expr folding. This makes '=' behave like library-defined assignment-like binary operators.
This temporarily puts '=' at the wrong precedence relative to 'as' and 'is', until 'as' and 'is' can be integrated into sequence parsing as well.
Swift SVN r5508
Set up constraints for AssignExprs within the constraint system instead of using typeCheckAssignment to set up their own isolated system. Kill the goofy hack not to consider a single-AssignExpr closure to be single-expression-body, because single-assign-expr-body closures now type-check successfully.
typeCheckAssignment still lingers because of a couple uses in typeCheckConstructorBody, but those should be easy to kill off next.
Swift SVN r5504
Change AssignStmt into AssignExpr; this will make assignment behave more consistently with assignment-like operators, and is a first step toward integrating '=' parsing with SequenceExpr resolution so that '=' can obey precedence rules. This also nicely simplifies the AST representation of c-style ForStmts; the initializer and increment need only be Expr* instead of awkward Expr*/AssignStmt* unions.
This doesn't actually change any user-visible behavior yet; AssignExpr is still only parsed at statement scope, and typeCheckAssignment is still segregrated from the constraint checker at large. (In particular, a PipeClosureExpr containing a single assign expr in its body still doesn't use the assign expr to resolve its own type.) The parsing issue will be addressed by handling '=' during SequenceExpr resolution. typeCheckAssignment can hopefully be reworked to work within the constraint checker too.
Swift SVN r5500
Instead of trying to parse '?' and ':' as separate placeholder exprs and matching them up during binary expr resolution, it's a bit cleaner to parse the entire '? ... :' middle expr of the ternary into a single placeholder node at parse time. Then binary expr resolution only ever has to consider a single sequence element.
Swift SVN r5499
This moves trailing closures from expr-postfix up to the level of
expr, and introduces an intermediate level (expr-basic) for places
that need to parse expressions followed by curly braces, such as
if/while/switch/for. Trailing closures are still restricted to occur
after expr-postfix, although the parser itself parses a slightly more
general and then complains if it got more than an expr-postfix.
Swift SVN r5256
Trailing closure syntax allows one to write a closure following any
other postfix expression, which passes the closure to that postfix
expression as an arguments. For example:
sort(fruits) { |lhs, rhs|
print("Comparing \(lhs) to \(rhs)\n")
return lhs > rhs
}
As a temporary limitation to work around the ambiguity with
if foo { ... } { ... }
we require trailing closures to have an explicit parameter list, e.g.,
if foo { || ... } { ... }
Swift SVN r5210
Because we synthesize AST nodes fairly often, and those synthesized
AST nodes rarely have useful source-location information, we shouldn't
be using the validity of source locations to describe the AST. In the
case of closures, use a bit instead. No functionality change.
Swift SVN r5205
'|' is part of the character set for operators, but within the
signature of a closure we need to treat the first non-nested '|' as
the closing delimiter for the closure parameter list. For example,
{ |x = 1| 2 + x}
parses with the default value of '1' for x, with the body 2 + x. If
the '|' operator is needed in the default value, it can be wrapped in
parentheses:
{ |x = (1|2)| x }
Note that we have problems with both name binding and type checking
for default values in closures (<rdar://problem/13372694>), so they
aren't actually enabled. However, this allows us to parse them and
recover better in their presence.
Swift SVN r5202
This commit implements closure syntax that places the (optional)
parameter list in pipes within the curly braces of a closure. This
syntax "slides" well from very simple closures with anonymous
arguments, e.g.,
sort(array, {$1 > $0})
to naming the arguments
sort(array, {|x, y| x > y})
to adding a return type and/or parameter types
sort(array, {|x : String, y : String| -> Bool x > y})
and with multiple statements in the body:
sort(array, {|x, y|
print("Comparing \(x) and \(y)\n")
return x > y
})
When the body contains only a single expression, that expression
participates in type inference with its enclosing expression, which
allows one to type-check, e.g.,
map(strings, {|x| x.toUpper()})
without context. If one has multiple statements, however, one will
need to provide additional type information either with context
strings = map(strings, {
return $0.toUpper()
})
or via annotations
map(strings, {|x| -> String
return x.toUpper()
}
because we don't perform inter-statement type inference.
The new closure expressions are only available with the new type
checker, where they completely displace the existing { $0 + $1 }
anonymous closures. 'func' expressions remain unchanged.
The tiny test changes (in SIL output and the constraint-checker test)
are due to the PipeClosureExpr AST storing anonymous closure arguments
($0, $1, etc.) within a pattern in the AST. It's far cleaner to
implement this way.
The testing here is still fairly light. In particular, we need better
testing of parser recovery, name lookup for closures with local types,
more deduction scenarios, and multi-statement closures (which don't
get exercised beyond the unit tests).
Swift SVN r5169
Replace the few uses of it with calls to typeof. We need to keep MetatypeExpr around in the AST because it's consed up by the type checker to represent implicit metatypes that arise in type-checked expressions.
Swift SVN r5017
Fixes <rdar://problem/13723781>.
T(x) still has some lingering conversion behavior, so there's a type-checking ambiguity in classes that are constructible from super- or subclasses, like stdlib's File is from VFSObject. I cheesed around this for now by using keywords in the constructor forms that have ambiguities. This issue should go away when we finish making T(x) mean only construction.
Swift SVN r5002
Original message:
SIL Parsing: add plumbing to know when we're parsing a .sil file
Enhance the lexer to lex "sil" as a keyword in sil mode.
Swift SVN r4988
Give the ternary a fixed precedence, parse '?' and ':' into SequenceExprs, and fold them into IfExprs as part of sequence folding. This allows assignment operators like '+=' to have precedence below the ternary as in C. Fixes <rdar://problem/13756211>.
Swift SVN r4983
Per Chris's feedback and suggestions on the verbose fix-it API, convert
diagnostics over to using the builder pattern instead of Clang's streaming
pattern (<<) for fix-its and ranges. Ranges are included because
otherwise it's syntactically difficult to add a fix-it after a range.
New syntax:
diagnose(Loc, diag::warn_problem)
.highlight(E->getRange())
.fixItRemove(E->getLHS()->getRange())
.fixItInsert(E->getRHS()->getLoc(), "&")
.fixItReplace(E->getOp()->getRange(), "++");
These builder functions only exist on InFlightDiagnostic; while you can
still modify a plain Diagnostic, you have to do it with plain accessors
and a raw DiagnosticInfo::FixIt.
Swift SVN r4894
This will be necessary for things like typo-correction, but currently
serves no purpose because all of our diagnostics are token-based. It's
going to be the base range type for Swift fix-its, though, so I thought I'd
get it in place now.
Swift SVN r4750
Fix array/dictionary literal parsing robustness by consolidating and improving
the parsing of lists in general (tuples/array/dictionary literals, attribute
lists, statement lists, declaration lists, etc).
Missing commas in tuple/array/dictionary literals or declaration attributes
are now detected, reported, and recovered from.
Premature ellipsis in tuples are now detected, reported, and recovered from.
Swift SVN r4631
NOTE: A nice side effect of this change is that f(x:&y) and g(x:<) parse
correctly regardless of whitespace, unlike f(x=&y) and g(x=<).
Swift SVN r4579
Now that we enforce semicolon or newline separation between statements, we can relax the whitespace requirements on '(' and '[' tokens. A "following" token is now just a token that isn't at the start of a line, and any token can be a "starting" token. This allows for:
a(b)
a (b)
a[b]
a [b]
to parse as applications and subscripts, and:
a
(b)
a
[b]
to parse as an expr followed by a tuple or an expr followed by a container literal.
Swift SVN r4573
Provide distinct syntax 'a as T' for coercions and 'a as! T' for unchecked downcasts, and add type-checker logic specialized to coercions and downcasts for these expressions. Change the AST representation of ExplicitCastExpr to keep the destination type as a TypeLoc rather than a subexpression, and change the names of the nodes to UncheckedDowncast and UncheckedSuperToArchetype to make their unchecked-ness explicit and disambiguate them from future checked casts.
In order to keep the changes staged, this doesn't yet affect the T(x) constructor syntax, which will for the time being still perform any construction, coercion, or cast.
Swift SVN r4498