Commit Graph

594 Commits

Author SHA1 Message Date
Joe Groff
53221db84c AST: Add 'VarPattern' node.
We decided to go with 'var' as a distributive pattern introducer which applies to bare identifiers within the subpattern. For example, 'var (a, b)' and '(var a, var b)' would be equivalent patterns. To model this, give 'var' its own AST node with a subpattern and remove the introducer loc from NamedPattern.

Swift SVN r5824
2013-06-26 23:01:47 +00:00
Joe Groff
e460a01af6 Remove the 'UnresolvedCallPattern' I stubbed out.
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
2013-06-26 04:23:47 +00:00
Joe Groff
8deec52b17 Rework AST representation of CaseStmts.
A single case block can have one or more 'case ...:' labels. 'case' labels contain patterns instead of exprs. 'default:' is a funny spelling for 'case _:'. Change the CaseStmt representation and rip out all the parsing, type-checking, and SILGen built off the old representation.

Swift SVN r5795
2013-06-25 00:31:42 +00:00
Joe Groff
5a83193796 Remove dead code from ASTWalker.cpp.
Swift SVN r5782
2013-06-24 17:51:06 +00:00
Joe Groff
7ba95cfd26 Add AST nodes for refutable patterns.
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
2013-06-24 17:17:34 +00:00
Joe Groff
f072c48e45 Refactor cast representation in AST and SIL, and implement 'is'.
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
2013-06-21 05:54:03 +00:00
Joe Groff
f2500d79b7 Sema: Allow dynamic casts from generics to concrete types.
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
2013-06-16 21:54:13 +00:00
Joe Groff
8512777d31 Parse 'as' and 'is' as sequence exprs.
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
2013-06-07 19:21:02 +00:00
Joe Groff
3e44152023 Replace Unsequenced* placeholders with partial AssignExpr/IfExpr nodes.
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
2013-06-07 16:49:57 +00:00
Joe Groff
6dcf8ae206 Parse assignments as part of expr-sequence.
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
2013-06-07 16:15:40 +00:00
Joe Groff
cb1f81db84 Make assignment an expression.
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
2013-06-06 22:18:54 +00:00
Joe Groff
2606b7ca57 Simplify handling of ternaries in SequenceExprs.
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
2013-06-06 22:18:48 +00:00
Doug Gregor
dea2ad1932 Zap OverloadedSubscriptExpr.
Swift SVN r5414
2013-05-30 20:50:22 +00:00
Doug Gregor
e06f54273a Zap ExplicitClosureExpr; it was only used in the old type checker.
Swift SVN r5388
2013-05-29 22:25:14 +00:00
Doug Gregor
db5ab01682 Allow ASTWalkers to replace statements and expressions without visiting their children first.
Swift SVN r5375
2013-05-29 17:16:33 +00:00
Doug Gregor
59ef7ca5ee Don't use source location information to distinguish single-expression closures.
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
2013-05-17 17:27:34 +00:00
Doug Gregor
ce3fe3ae92 Implement Ruby-inspired closure syntax.
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
2013-05-14 05:17:10 +00:00
Doug Gregor
80b7001cea Implement support for member initializers.
One can now attach an initializer to a member variable. That value
will used as the default initialization for the member variable(s) it
initializes. Fixes <rdar://problem/12597404>.


Swift SVN r4989
2013-04-30 00:32:12 +00:00
Joe Groff
f026e44c18 Integrate ternary parsing with precedence parsing.
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
2013-04-29 22:15:52 +00:00
Doug Gregor
a91941b635 Introduce assignments into the implicitly-defined default constructor body.
Add assignment statements into the implicitly-defined default
constructor body to initialize all of the members appropriately, e.g.,
by calling the default constructor. For builtin types and class types,
introduce ZeroValueInitExpr to produce a "zero" value.

ZeroValueInitExpr still needs a representation in SIL. Until then,
actual generation of this AST is suppressed.



Swift SVN r4895
2013-04-25 00:00:28 +00:00
Joe Groff
e7f7df3027 Implement 'x is T' in SILGen.
Add an IsaInst to represent type tests, and implement SILGen for IsSubtypeExpr AST nodes. Get rid of SuperIsArchetypeExpr because it's not really necessary to have it different from IsaSubtype--the SIL and IR behavior is identical.

Swift SVN r4855
2013-04-21 20:33:54 +00:00
Joe Groff
bfd2f85b5c Parse 'fallthrough' statements.
Create a new FallthroughStmt, which transfers control from a 'case' or 'default' block to the next 'case' or 'default' block within a switch. Implement parsing and sema for FallthroughStmt, which syntactically consists of a single 'fallthrough' keyword. Sema verifies that 'fallthrough' actually appears inside a switch statement and that there is a following case or default block to pass control to.

SILGen/IRGen support forthcoming.

Swift SVN r4653
2013-04-10 17:30:42 +00:00
Chris Lattner
b4fd6dd04a Change TopLevelCodeDecl to allow it to hold a sequence of different exprs and statements in one unit, wrapping them into a BraceStmt. This makes it more similar to other decls (e.g. funcdecl, ctor decls, etc) and will be useful for future sil work.
Unfortunately, this regresses the repl when expressions like (1,2) are entered. This is because the repl is violating some invariants (forming dags out of ASTs, making ASDAG's which upset the type checker).  I'm going to fix this next, but can't bring myself to do it in the same commit.



Swift SVN r4617
2013-04-05 22:33:14 +00:00
Joe Groff
9667bda089 Implement 'as' syntax for coercions and casts.
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
2013-03-27 22:27:11 +00:00
Joe Groff
4c09ef61e3 Add conditional expressions.
Implement the syntax 'if x then y else z', which evaluates to 'y' if 'x' is true or 'z' if 'x' is false. 'x' must be a valid logic value, and 'y' and 'z' must be implicitly convertible to a common type.

Swift SVN r4407
2013-03-16 20:28:58 +00:00
Joe Groff
062ad267c4 Value-only switch statements.
Implement switch statements with simple value comparison to get the drudge work of parsing and generating switches in place. Cases are checked using a '=~' operator to compare the subject of the switch to the value in the case. Unlike a C switch, cases each have their own scope and don't fall through. 'break' and 'continue' apply to an outer loop rather to the switch itself. Multiple case values can be specified in a comma-separated list, as in 'case 1, 2, 3, 4:'. Currently no effort is made to check for duplicate cases or to rank cases by match strength; cases are just checked in source order, and the first one wins (aside from 'default', which is branched to if all cases fail).

Swift SVN r4359
2013-03-12 04:43:01 +00:00
Joe Groff
8fb9a46f95 AST: Wrap super.ctor calls in a RebindThis node.
'super.constructor' shouldn't be referenceable without being called, and 'super.constructor(...)' shouldn't return a value. Require super.constructor expressions to be called at parse time, and wrap the call expression in a new RebindThisInConstructorExpr that represents consuming the delegated-to constructor by using it to reassign 'this'. This should theoretically allow super.constructor to an ill-behaved self-modifying ObjC class to work. It's also necessary to support delegating constructors of value types.

Swift SVN r4326
2013-03-08 00:09:39 +00:00
Joe Groff
f489f2a6fd Clean up AST representation of 'super'.
Replace the more specific Super*RefExpr nodes with a single SuperRefExpr that resolves members of 'this' relative to its superclass. Add an OtherConstructorDeclRefExpr for referring to a constructor as called from another constructor, and use it to represent resolved 'super.constructor' expressions. (It should also be able to represent delegating constructors for free, if we decide we want to add syntax for that.)

Swift SVN r4286
2013-03-05 02:13:49 +00:00
Doug Gregor
315451eb45 Implement parsing, AST, semantic analysis, and IRgen for dictionary literals.
Swift SVN r4193
2013-02-25 07:27:15 +00:00
Joe Groff
72703f84a6 Sema: Typecheck UnresolvedSpecializeExprs.
Use UnresolvedSpecializeExprs to set up equality constraints on the opened generic type variables of their subexpressions, and when the system is solved, resolve the expression away to its specialized base expression. Fix the solution logic for DeclRefExprs so that they obtain the type the constraint checker solved for them and not the original unbound type of the decl. This means that constructions and static member accesses of generic types now parse! This also incidentally fixes <rdar://problem/13212959>, so 'A(0)' for generic 'A<T>' now works when T can be inferred from constructor arguments.

One thing that doesn't work yet is generics as type members, as in 'A.B<C>' or 'A<B>.C<D>'. The UnresolvedDotExpr for these generates an unbound type variable, and I'm not sure how to express opening a type variable as a generic type $TO<A, B, C>.metatype constraint system in which the thing being specialized is a variable. This patch also doesn't allow explicit specialization of functions; although we could do so in theory, the constraint system that currently gets generated for functions loses the type parameters, so it would require some redesign in the constraint checker.

Swift SVN r4047
2013-02-14 19:41:26 +00:00
Joe Groff
a8b5a2ec26 AST: Add UnresolvedSpecializeExpr.
This node represents a type parameter list application in an unresolved expr context. The type checker will use these to explicitly bind type variables of generic types.

Swift SVN r4046
2013-02-14 19:41:23 +00:00
Joe Groff
b5bc022686 Incomplete support for array literal expressions.
Analyze an expression of the form [<tuple contents>] into a call to T.convertFromArrayLiteral(<tuple contents>) for some T conforming to an ArrayLiteralConvertible protocol. Because of some limitations in the constraint checker and protocol conformance checkers, it currently does an ad-hoc conformance check using member constraints. It also currently fails to typecheck for generic container types, and does not provide a default fallback to 'T[]' if unable to deduce a better type from context.

Swift SVN r3953
2013-02-05 21:23:42 +00:00
Joe Groff
e6d3c3e00c Parser: Parse 'super' expressions.
Set up AST nodes for 'super.<identifier>', 'super.constructor', and 'super[<expr>]' expressions, and implement parsing for them without any sema or backend support.

Swift SVN r3847
2013-01-23 21:24:28 +00:00
Dave Zarzycki
2f31759280 Remove SemiStmt class
We have no intention of ever supporting actual semicolon statements
(separators, statements no), nor do we ever want to because that would
mean the behavior of the program would potentially change if semicolons
were naively removed.

This patch tracks the trailing semicolon now in the decl/expr/stmt,
which will enable someone to write a good "swift indent" tool in the
future.

Swift SVN r3824
2013-01-22 00:25:26 +00:00
Doug Gregor
59ab9d1954 Split superclass-to-archetype downcasts into their own expression node.
Swift SVN r3537
2012-12-18 23:48:19 +00:00
Doug Gregor
1bc5c1b6f5 Walk the base of OverloadedMemberRefExpr as part of a traversal.
Swift SVN r3365
2012-12-05 18:13:13 +00:00
Doug Gregor
dc7dcc7fc5 Implement explicit (unchecked!) downcasting for class types.
This introduces support for the syntax

  Derived(baseObj)

to downcast from a class type to one of its subclasses. This still
needs more language design and implementation work, including:
  - This overloads the X(y) syntax again, which already means either
  "coerce y to type X, performing implicit conversions if necessary"
  or "construct a value of type X from y". It's no actually ambiguous,
  because the first case won't apply for downcasts and the second case
  is limited to value types, but it makes me wonder whether we want a
  different syntax for the first case.

  - We need this to be a checked cast, but don't have the runtime
    infrastructure to do so yet. I've left this as a FIXME.

However, the Objective-C importer is fairly useless because everything
that creates an object returns an "id", "id" maps to "NSObject", and
then the type system doesn't let you get from NSObject back to the
type you care about. So, this lets you explicitly do the cast.



Swift SVN r3279
2012-11-28 16:59:27 +00:00
John McCall
2f8f05615e Rename TypeOfExpr / TypeOfInst to MetatypeExpr / MetatypeInst.
Introduce a '.metatype' form in the syntax and do some basic
type-checking that I probably haven't done right.  Change
IR-generation for that and GetMetatypeExpr to use code that
actually honors the dynamic type of an expression.

Swift SVN r3053
2012-10-24 07:54:23 +00:00
Ted Kremenek
a5ec0af7e8 Rename 'BraceStmt::elements()' to 'getElements()' to match Swift
naming style for accessors.

Swift SVN r2742
2012-08-24 14:17:28 +00:00
Ted Kremenek
479077e354 Remove individual element setters from BraceStmt, and just use MutableArrayRef and ArrayRef to access its elements.
Swift SVN r2586
2012-08-08 05:06:33 +00:00
Eli Friedman
0bfcfbfb8a Change the type of ConstructorDecls to be of the form metatype<T> -> () -> (). Change a bunch of stuff to compensate. Get rid of ConstructorRefExpr, which is no longer used.
Swift SVN r2526
2012-08-03 03:58:44 +00:00
Eli Friedman
ea6348f446 Make NewReferenceExpr inherit from ApplyExpr; this lets us delete some redundant code.
Swift SVN r2447
2012-07-25 20:55:51 +00:00
Doug Gregor
511dbfea25 When applying an operator found in a protocol, compute the effetive
base type (e.g., the archetype type, when we're in a generic function)
used to refer to that operator as a member, e.g., given

  func min<T : Ord>(x : T, y : T) {
    if y < x { return y } else { return x }
  }

'<' is found in the Ord protocol, and is referenced as

  archetype_member_ref_expr type='(lhs : T, rhs : T) -> Bool' decl=<
    (typeof_expr type='metatype<T>'))

using a new expression kind, TypeOfExpr, that simply produces a value
of metatype type for use as the base.

This solves half of the problem with operators in protocols; the other
half of the problem involves matching up operator requirements
appropriately when checking protocol conformance.


Swift SVN r2443
2012-07-25 16:04:30 +00:00
Eli Friedman
30d1f22bfb Rewrite the representation of NewReferenceExpr to make it more friendly to generics.
Generic constructors on classes should be working with this commit.



Swift SVN r2440
2012-07-25 00:49:03 +00:00
Eli Friedman
751c463a2e Rewrite the way we represent construction of value types so that it looks
more like a call.  This should be enough to get generic constructors working.



Swift SVN r2437
2012-07-24 23:43:43 +00:00
Eli Friedman
e6917fbc51 Add support for "new" with classes with non-default constructors. <rdar://problem/11917082>.
Swift SVN r2384
2012-07-20 21:37:08 +00:00
Eli Friedman
3b16fe7d44 Fix typo.
Swift SVN r2371
2012-07-19 02:11:16 +00:00
Eli Friedman
f1f67db652 Big cleanup for how we handle computing types for functions and semantic
analysis for patterns.

Major changes:
1. We no longer try to compute the types of functions in the parser.
2. The type of a function always matches the type of the argument patterns.
3. Every FuncDecl now has a corresponding FuncExpr; that FuncExpr might not
   have a body, though.
4. We now use a new class "ExprHandle" so that both a pattern and a type
   can hold a reference to the same expression.

Hopefully this will be a more reasonable foundation for further changes to
how we compute the types of FuncDecls in generics and for the implementation
of type location information.



Swift SVN r2370
2012-07-19 02:09:04 +00:00
Eli Friedman
77751012d2 Switch over constructors so that they return a value instead of being a
method to initialize the members.  This doesn't matter so much
for structs (the generated IR is essentially equivalent except for
small structs), but on classes, we don't want to make "new X" generate
code that knows about metadata/destructors/etc for the class X.

Also, make sure classes always have a constructor.  (We haven't really
discussed the rules for implicitly declared constructors, so for now,
the rule is just "generate an implicit constructor if there is no
explicit constructor".  We'll want to revisit this when we actually
design object construction.)



Swift SVN r2361
2012-07-17 00:32:28 +00:00
Eli Friedman
5ff5b40159 Misc pieces of Sema for destructors.
Swift SVN r2350
2012-07-12 02:23:49 +00:00