Commit Graph

696 Commits

Author SHA1 Message Date
Graydon Hoare
77cad91716 Parse and print @available(swift N) / @available(swift, ...) 2016-10-12 11:20:43 -07:00
Graydon Hoare
66f2027f62 s/Version/PlatformVersion/ to availability specs, add LanguageVersion. 2016-10-12 11:20:42 -07:00
Xi Ge
e5d77911a2 [SourceKit] Indent property getters disregarding of empty bodies. rdar://28049927 (#5246)
[SourceKit] Indentation: when the indented line starts with open brace and the
line before starts with a leading declaration keywords, we never add
indentation level on the brace. rdar://28049927
2016-10-11 19:23:29 -07:00
Rintaro Ishizaki
21513b8916 [Parse] Remove unecessary parameters from parseDeclAttributeList
`InParam` was not used at all.

`StopAtTypeAttributes`
As far as I understand, this option *was* merely for improving diagnostic QoI
for declarations like:
  func foo(@typeattr Arg) {}
to fix-it to:
  func foo(_: @typeattr Arg) {}

But, this causes the very loudy diagnostics for misplaced type attributes.
For example, on:
func foo(@convention(block) x: () -> CInt) {}

test.swift:1:10: error: expected parameter name followed by ':'
test.swift:1:10: error: expected ',' separator
test.swift:1:10: error: expected ')' in parameter
test.swift:1:9: note: to match this opening '('
test.swift:1:10: error: consecutive statements on a line must be separated by ';'
test.swift:1:11: error: attribute can only be applied to types, not declarations
test.swift:1:21: error: expected declaration
test.swift:1:44: error: statement cannot begin with a closure expression
test.swift:1:44: note: explicitly discard the result of the closure by assigning to '_'
test.swift:1:44: error: braced block of statements is an unused closure
test.swift:1:6: error: expected '{' in body of function declaration
test.swift:1:44: error: expression resolves to an unused function

Now, we emit more accurate diagnostic:
test.swift:1:11: error: attribute can only be applied to types, not declarations
func foo(@convention(block) x: () -> CInt) {}
          ^

Note that This causes small regression in diagnostics for bare type parameter
like `func foo(@convention(c) () -> CInt) {}`:

Before:
test.swift:1:10: error: unnamed parameters must be written with the empty name '_'
func foo(@convention(block) () -> CInt) {}
         ^
         _:

Now:
test.swift:1:11: error: attribute can only be applied to types, not declarations
func foo(@convention(block) () -> CInt) {}
          ^
test.swift:1:29: error: unnamed parameters must be written with the empty name '_'
func foo(@convention(block) () -> CInt) {}
                            ^
                            _:
2016-10-11 02:26:13 +09:00
Rintaro Ishizaki
f772c40e75 [Parse] Eliminate Parser::canParseAttributes()
`@foo=bar` style attributes are no longer supported anyway.
So as ',' separated attribute list.

In `canParseTypeTupleBody()`, `canParseType()` can more accurately consume
type attributes.

In `isStartOfGetSetAccessor`, we can trivially inline the functionality.
2016-10-11 02:26:13 +09:00
Rintaro Ishizaki
e52e043d57 [Parse] Don't use tok::unknown as a dummy token (#5171)
Use tok::NUM_TOKENS instead. tok::unknown can easily appear in source code.

For instance `skipUntil(tok::eof)` did not work as expected, because that was
`skipUntil(tok::eof, tok::unknown)` hence does stop at error tokens such as
`0xG` (invalid hex number literal).

Revert 2abc92bbb5, since that was
accidental side-effect of 45118037cc.
Forward references are not allowed actually.
2016-10-07 14:37:11 +09:00
Rintaro Ishizaki
d75c4c4cbb [gardening][Parse] Remove 2 unused flags in Parser (#4743)
* [Parse] Remove unused GreaterThanIsOperatorRAII. NFC

Last usage was removed in 68af974227.

* [Parse] Remove unused ArgumentIsParameter flag. NFC

Last usage was removed in 4e4173f2e6
2016-09-13 21:54:03 -07:00
Doug Gregor
2552f41556 [Name lookup] Add a staging flag for ASTScope-based name lookup. 2016-09-06 09:05:11 -07:00
Jacob Bandes-Storch
d6590cd781 [QoI] improve diagnostics for operator declarations; unify parsing code 2016-09-04 22:17:29 -07:00
Doug Gregor
78b007f178 Always create a DefaultArgumentInitializer for a parameter with a default argument.
As with pattern binding initializer contexts, we were trying to
optimize away these contexts, leading to an unpredictable AST.
2016-09-02 13:51:00 -07:00
Doug Gregor
85537fd66b Murder ExprHandle in cold blood. NFC
ExprHandle is a relic from a horrible time when expressions made their
way into the type system via default arguments. It's been unnecessary
for a long time, so get rid of it.
2016-09-02 10:39:19 -07:00
Richard Wei
5358c11519 [SE-0096] [Parse] Implement type(of:) expression 2016-07-29 16:57:54 -07:00
John McCall
c8c41b385c Implement SE-0077: precedence group declarations.
What I've implemented here deviates from the current proposal text
in the following ways:

- I had to introduce a FunctionArrowPrecedence to capture the parsing
  of -> in expression contexts.

- I found it convenient to continue to model the assignment property
  explicitly.

- The comparison and casting operators have historically been
  non-associative; I have chosen to preserve that, since I don't
  think this proposal intended to change it.

- This uses the precedence group names and higherThan/lowerThan
  as agreed in discussion.
2016-07-26 14:04:57 -07:00
Doug Gregor
b40c89d4c6 [AST] Carry AST names through call expressions. 2016-07-26 11:23:57 -07:00
David Farler
4a57e647e6 Merge pull request #3762 from bitjammer/se-0081-diagnostic-and-crashes
[SE-0081] Warn on deprecated where clause inside angle brackets
2016-07-26 09:09:30 -07:00
Doug Gregor
5cce5c4d1d [Parser] Refactor parsing of calls and call-like expressions.
Rather than parsing the call arguments (or similar, e.g., subscript)
as a parenthesized expression or tuple, then later reworking that
ParenExpr/TupleExpr if a trailing closure comes along, then digging
through that ParenExpr/TupleExpr to pull out the arguments and
trailing closure... just parse the expression list and trailing
closure together, then directly form the appropriate AST node with
arguments/labels/label locations/trailing closure.

Fixes rdar://problem/19804707, which is an issue where trailing
closures weren't working with unresolved member expressions (e.g.,
".foo {... }"), and is a stepping-stone to SE-0111.
2016-07-26 08:40:11 -07:00
David Farler
7bfaeb57f1 [SE-0081] Warn on deprecated where clause inside angle brackets
and provide a fix-it to move it to the new location as referenced
in SE-0081.

Fix up a few stray places in the standard library that is still using
the old syntax.

Update any ./test files that aren't expecting the new warning/fix-it
in -verify mode.

While investigating what I thought was a new crash due to this new
diagnostic, I discovered two sources of quite a few compiler crashers
related to unterminated generic parameter lists, where the right
angle bracket source location was getting unconditionally set to
the current token, even though it wasn't actually a '>'.
2016-07-26 01:41:10 -07:00
Joe
67dccb283e [SE-0095] Code feedback changes; Any is parsed as a keyword
- Any is made into a keyword which is always resolved into a TypeExpr,
allowing the removal of the type system code to find TheAnyType before
an unconstrained lookup.
- Types called `Any` can be declared, they are looked up as any other
identifier is
- Renaming/redefining behaviour of source loc methods on
ProtocolCompositionTypeRepr. Added a createEmptyComposition static
method too.
- Code highlighting treats Any as a type
- simplifyTypeExpr also does not rely on source to get operator name.
- Any is now handled properly in canParseType() which was causing
generic param lists containing ‘Any’ to fail
- The import objc id as Any work has been relying on getting a decl for
the Any type. I fix up the clang importer to use Context.TheAnyType
(instead of getAnyDecl()->getDeclaredType()). When importing the id
typedef, we create a typealias to Any and declare it unavaliable.
2016-07-19 12:01:37 -07:00
Joe
a6dad0091b [SE-0095] Initial parsing implementation for '&' composition syntax
This commit defines the ‘Any’ keyword, implements parsing for composing
types with an infix ‘&’, and provides a fixit to convert ‘protocol<>’

- Updated tests & stdlib for new composition syntax
- Provide errors when compositions used in inheritance.
Any is treated as a contextual keyword. The name ‘Any’
is used emit the empty composition type. We have to
stop user declaring top level types spelled ‘Any’ too.
2016-07-19 12:01:02 -07:00
Chris Lattner
1b2da8c084 Remove the #setline directive, which was formerly known as #line and is now
known as #sourceLocation.  #setline was an intermediate but never endorsed state.

Upgrade the migration diagnostics for SE-0066 and SE-0049 to be errors instead of warnings.
2016-07-02 16:34:19 -07:00
Slava Pestov
5b4ee41772 Parser: Diagnose if free-standing 'where' clause is attached to a non-generic declaration
Previously we would produce an empty GenericParamList, crashing Sema.
2016-06-18 17:15:25 -07:00
Slava Pestov
7814c47b71 AST: Slightly change meaning of NominalTypeDecl::getDeclaredType()
Consider this code:

struct A<T> {
  struct B {}
  struct C<U> {}
}

Previously:

- getDeclaredType() of 'A.B' would give 'A<T>.B'
- getDeclaredTypeInContext() of 'A.B' would give 'A<T>.B'

- getDeclaredType() of 'A.C' would give 'A<T>.C'
- getDeclaredTypeInContext() of 'A.C' would give 'A<T>.C<U>'

This was causing problems for nested generics. Now, with this change,

- getDeclaredType() of 'A.B' gives 'A.B' (*)
- getDeclaredTypeInContext() of 'A.B' gives 'A<T>.B'
- getDeclaredType() of 'A.C' gives 'A.C' (*)
- getDeclaredTypeInContext() of 'A.C' gives 'A<T>.C<U>'

(Differences marked with (*)).

Also, this change makes these accessors fully lazy. Previously,
only getDeclaredTypeInContext() and getDeclaredIterfaceType()
were lazy, whereas getDeclaredType() was built from validateDecl().

Fix a few spots where the return value wasn't being checked
properly.

These functions return ErrorType if a circularity was detected via
the generic parameter list, or if the extension did not resolve.
They return Type() if the extension cannot be resolved *yet*.

This is pretty subtle, and I'll need to do another pass over
callers of these functions at some point. Many of them should be
moved over to use getSelfInContext(), getSelfOfContext() and
getSelfInterfaceType() instead.

Finally, this patch consolidates logic for diagnosting invalid
nesting of types.

The parser had some code for protocols in bad places and bad things
inside protocols, and Sema had several different bail-outs for
bad things in protocols, nested generic types, and stuff nested
inside protocol extensions.

Combine all of these into a single set of checks in Sema. Note
that we no longer give up early if we find invalid nesting.
Leaving decls unvalidated and un-type-checked only leads to
further problems. Now that all the preliminary crap has been
fixed, we can go ahead and start validating these funny nested
decls, actually fixing some crashers in the process.
2016-06-18 17:15:24 -07:00
Chris Lattner
c5bf433490 Implement parser support for SE-0081 - Move 'where' clause to end of declaration
This patch includes testsuite changes to show each of the decls supported.

Next step is to migrate the stdlib + testsuite + corelibs: I'd would *greatly* appreciate help with this.

After that is done, deprecation + migration of the old form can happen.
2016-05-30 15:28:49 -07:00
Doug Gregor
9f0cec4984 SE-0062: Implement #keyPath expression.
Implement the Objective-C #keyPath expression, which maps a sequence
of @objc property accesses to a key-path suitable for use with
Cocoa[Touch]. The implementation handles @objc properties of types
that are either @objc or can be bridged to Objective-C, including the
collections that work with key-value coding (Array/NSArray,
Dictionary/NSDictionary, Set/NSSet).

Still to come: code completion support and Fix-Its to migrate string
literal keypaths to #keyPath.

Implements the bulk of SR-1237 / rdar://problem/25710611.
2016-05-18 23:30:15 -07:00
Jordan Rose
2fa1626579 Improve diagnostic text for @available(renamed:).
We don't want to show the funny "getter:Foo.bar(self:)" syntax to
developers, so whenever possible be a little more explicit.

    'foo' has been replaced by 'X.newFoo'
    'bar(x:)' has been replaced by property 'X.bar'
    'baz(x:y:)' has been replaced by instance method 'X.baz(y:)'

(We do run up against the limitation of a string -- this diagnostic
does not do any lookup to find out if the resulting decl actually exists.)
2016-05-05 18:07:39 -07:00
Chris Lattner
14c7a3dafe implement SE-0071 - Allow (most) keywords in member references 2016-05-02 22:31:14 -07:00
Jordan Rose
d7b3b6a462 Validate the "renamed" argument to @available.
It should have the same form as the argument to NS_SWIFT_NAME
in Objective-C, except that it permits operators and (currently)
disallows instance members and properties. We do get to share the
same parsing code, at least.

This actually caught an error in the Foundation overlay!

Groundwork for SR-1008.
2016-04-28 20:21:30 -07:00
Ted Kremenek
b8bbed8c13 [WIP] Implement SE-0039 (Modernizing Playground Literals) (#2215)
* Implement the majority of parsing support for SE-0039.

* Parse old object literals names using new syntax and provide FixIt.

For example, parse "#Image(imageLiteral:...)" and provide a FixIt to
change it to "#imageLiteral(resourceName:...)".  Now we see something like:

test.swift:4:9: error: '#Image' has been renamed to '#imageLiteral
var y = #Image(imageLiteral: "image.jpg")
        ^~~~~~ ~~~~~~~~~~~~
        #imageLiteral resourceName

Handling the old syntax, and providing a FixIt for that, will be handled in a separate
commit.

Needs tests.  Will be provided in later commit once full parsing support is done.

* Add back pieces of syntax map for object literals.

* Add parsing support for old object literal syntax.

... and provide fixits to new syntax.

Full tests to come in later commit.

* Improve parsing of invalid object literals with old syntax.

* Do not include bracket in code completion results.

* Remove defunct code in SyntaxModel.

* Add tests for migration fixits.

* Add literals to code completion overload tests.

@akyrtzi told me this should be fine.

* Clean up response tests not to include full paths.

* Further adjust offsets.

* Mark initializer for _ColorLiteralConvertible in UIKit as @nonobjc.

* Put attribute in the correct place.
2016-04-25 07:19:26 -07:00
Chris Willmore
02a6be6d01 Allow parsing of function types in expr position (#2273)
Previously it was not possible to parse expressions of the form

    [Int -> Int]()

because no Expr could represent the '->' token and be converted later
into a FunctionTypeRepr. This commit introduces ArrowExpr which exists
solely to be converted to FunctionTypeRepr later by simplifyTypeExpr.

https://bugs.swift.org/browse/SR-502
2016-04-22 21:53:26 -07:00
Xi Ge
152eeaa1fe [Sema] Add a fixit for diagnosis "variable used within its own initial value".
This fixit checks if a decl with the identical name can be found in the parent type
context; if can, we add "self." to try to resolve the issue. rdar://25389852
2016-04-14 15:55:01 -07:00
Manav Gabhawala
7862f104c9 [Parser] Cleans up parsing of parameter attributes. Implements SE-0053. Fixes SR-979, SR-1020 and cleans up implementation of SE-0003. Provides better fix-its and diagnostics for misplaced 'inout' and prohibits 'var' and 'let' from parameter attributes 2016-03-29 13:55:46 -04:00
Ben Langmuir
ff895d2f5e [CodeCompletion] Fix completion in string literal interpolation at top-level
Mostly this was just returning the ParserStatus bits that we got from
parseExprList from parseExprStringLiteral. The rest was just cleaning up
places that didn't handle EOF very well, which is important here because
the code completion token is buried in the string literal, so the
primary lexer will walk past it.

rdar://problem/17101944
2016-03-14 23:13:15 -07:00
Doug Gregor
d52530970e Merge pull request #1550 from kballard/use-declname-for-scope
[Parse] Fix lookup of foo(_:bar:) expressions
2016-03-14 11:36:04 -07:00
Greg Titus
a11e911f66 Merge pull request #1610 from gregomni/typealias
[Parse/AST/Sema] Split parsing for typealias & associatedtype, allow typealias in protocols and generic constraints
2016-03-13 21:50:01 -07:00
gregomni
1e3ed8bdd0 Split parsing for typealias & associatedtype, and allow typealias in protocols.
Split up parsing of typealias and associatedtype, including dropping a
now unneeded ParseDeclOptions flag.

Then made typealias in a protocol valid, and act like you would
hope for protocol conformance purposes (i.e. as an alias possibly
involved in the types of other func/var conformances, not as a hidden
generic param in itself).

Also added support for simple type aliases in generic constraints. Aliases
to simple (non-sugared) archetype types (and also - trivially - aliases to
concrete types) can now be part of same-type constraints.

The strategy here is to add type aliases to the tree of
PotentialArchetypes, and if they are an alias to an archetype, also to
immediately find the real associated type and set it as the
representative for the PA. Thus the typealias PA node becomes just a
shortcut farther down into the tree for purposes of lookup and
generating same type requirements.

Then the typealias PA nodes need to be explicitly skipped when walking
the tree for building archetype types and other types of requirements,
in order to keep from getting extra out-of-order archetypes/witness
markers of the real associated type inserted where the typealias is
defined.

Any constraint with a typealias more complex than pointing to a single
nested associated type (e.g. `typealias T = A.B.C.D`), will now get a
specialized diagnoses.
2016-03-13 21:44:23 -07:00
Chris Lattner
4992474168 Add support for #sourceLocation in its ratified forms. Switch gyb to produce
the new form.  This keeps accepting #setline for now, but we should rip it out
at some point.
2016-03-11 22:21:42 -08:00
Kevin Ballard
502b159400 [Parse] Store DeclNames in Scope instead of Identifiers
This fixes a problem where compound names like `foo(_:bar:)` were being
resolved to variables declared with the same base name.

Fixes most of SR-880.
2016-03-04 23:42:17 -08:00
Daniel Duan
0f53348304 Merge pull request #1501 from dduan/SE-0034-pr
[Parser][SE-0034] Replace line directive #line with #setline
2016-03-01 19:44:05 -08:00
Daniel Duan
ba9809c390 [Parser][SE-0034] deprecate line directive in favor of #setline 2016-03-01 16:33:19 -08:00
Doug Gregor
3ffbe020d7 [Clang importer] Handle name mapping for "getter:" and "setter:" in swift_name.
The swift_name string format now supports "getter:" and "setter:"
prefixes to indicate that a function is the getter or setter of a
Swift-synthesized property. Start parsing these DeclNames and make
sure they're reflected in the Swift name lookup tables.

[Clang update required]
2016-03-01 15:33:21 -08:00
Doug Gregor
7265328e07 [Clang importer] Generalize name lookup tables for globals-as-members.
A swift_name attribute on a global declaration can specify a dotted
name (e.g., SomeStruct.member) to map that global into a member of the
(Swift-)named type. Handle this mapping in DeclName parsing, plumb it
through importFullName, and cope with it in the Swift name lookup
tables (tested via the dump) and importing into a Swift DeclContext
(as-yet-untested). Part of SE-0033.
2016-03-01 15:33:20 -08:00
Adrian Prantl
310b0433a9 Reapply "Serialize debug scope and location info in the SIL assembler language.""
This ireapplies commit 255c52de9f.

Original commit message:

Serialize debug scope and location info in the SIL assembler language.
At the moment it is only possible to test the effects that SIL
optimization passes have on debug information by observing the
effects of a full .swift -> LLVM IR compilation. This change enable us
to write targeted testcases for single SIL optimization passes.

The new syntax is as follows:

 sil-scope-ref ::= 'scope' [0-9]+
 sil-scope ::= 'sil_scope' [0-9]+ '{'
                 sil-loc
                 'parent' scope-parent
                 ('inlined_at' sil-scope-ref )?
               '}'
 scope-parent ::= sil-function-name ':' sil-type
 scope-parent ::= sil-scope-ref
 sil-loc ::= 'loc' string-literal ':' [0-9]+ ':' [0-9]+

Each instruction may have a debug location and a SIL scope reference
at the end.  Debug locations consist of a filename, a line number, and
a column number.  If the debug location is omitted, it defaults to the
location in the SIL source file.  SIL scopes describe the position
inside the lexical scope structure that the Swift expression a SIL
instruction was generated from had originally. SIL scopes also hold
inlining information.

<rdar://problem/22706994>
2016-02-26 13:28:57 -08:00
Adrian Prantl
255c52de9f Revert "Serialize debug scope and location info in the SIL assembler language."
Temporarily reverting while updating the validation test suite.

This reverts commit c9927f66f0.
2016-02-26 11:51:57 -08:00
Adrian Prantl
c9927f66f0 Serialize debug scope and location info in the SIL assembler language.
At the moment it is only possible to test the effects that SIL
optimization passes have on debug information by observing the
effects of a full .swift -> LLVM IR compilation. This change enable us
to write targeted testcases for single SIL optimization passes.

The new syntax is as follows:

 sil-scope-ref ::= 'scope' [0-9]+
 sil-scope ::= 'sil_scope' [0-9]+ '{'
                 sil-loc
                 'parent' scope-parent
                 ('inlined_at' sil-scope-ref )?
               '}'
 scope-parent ::= sil-function-name ':' sil-type
 scope-parent ::= sil-scope-ref
 sil-loc ::= 'loc' string-literal ':' [0-9]+ ':' [0-9]+

Each instruction may have a debug location and a SIL scope reference
at the end.  Debug locations consist of a filename, a line number, and
a column number.  If the debug location is omitted, it defaults to the
location in the SIL source file.  SIL scopes describe the position
inside the lexical scope structure that the Swift expression a SIL
instruction was generated from had originally. SIL scopes also hold
inlining information.

<rdar://problem/22706994>
2016-02-26 10:46:29 -08:00
Jordan Rose
6272941c5c Rename "build configurations" to "conditional compilation blocks".
...because "build configuration" is already the name of an Xcode feature.

- '#if' et al are "conditional compilation directives".
- The condition is a "conditional compilation expression", or just
  "condition" if it's obvious.
- The predicates are "platform conditions" (including 'swift(>=...)')
- The options set with -D are "custom conditional compilation flags".
  (Thanks, Kevin!)

I left "IfConfigDecl" as is, as well as SourceKit's various "BuildConfig"
settings because some of them are part of the SourceKit request format.
We can change these in follow-up commits, or not.

rdar://problem/19812930
2016-02-12 11:09:26 -08:00
Slava Pestov
bbbe307980 SIL: Introduce SILDefaultWitnessTable and start plumbing
This will be used to help IRGen record protocol requirements
with resilient default implementations in protocol metadata.

To enable testing before all the Sema support is in place, this
patch adds SIL parser, printer and verifier support for default
witness tables.

For now, SILGen emits empty default witness tables for protocol
declarations in resilient modules, and IRGen ignores them when
emitting protocol metadata.
2016-02-05 20:57:11 -08:00
Doug Gregor
ab31f08848 [Parser] Disambiguate between object literals and collection literals.
Now that we have expressions that start with #, the [# introducer for
object literals is no longer guaranteed to indicate an object
literal. For example:

    [#line, #column]

is an array literal and

    [#line : #column]

is a dictionary literal. Use additional lookahead in the parser to
disambiguate these cases from object literals. Fixes
rdar://problem/24533081.
2016-02-05 17:14:20 -08:00
Chris Lattner
94dd92fcb8 Fix compiler_crashers 22725 & 28236 by reworking parameter parsing error
recovery a bit.
2016-02-01 20:50:32 -08:00
David Farler
3f635d04c7 Reinstante var bindings in refutable patterns, except function parameters.
This reverts commits: b96e06da44,
                      8f2fbdc93a,
                      93b6962478,
                      64024118f4,
                      a759ca9141,
                      3434f9642b,
                      9f33429891,
                      47c043e8a6.

This commit leaves 'var' on function parameters as a warning to be
merged into Swift 2.2. For Swift 3, this will be an error, to be
converted in a follow-up.
2016-01-29 15:27:08 -08:00
Denis Vnukov
42cba88f2c Properly handle tokens split in parser inside swift::tokenize(...)
Swift parser splits tokens in few cases, but it swift::tokenize(...) does not know
about that. In order to reconstruct token stream as it was seen by the parser,
we need to collect the tokens it decided to split and use this information
in swift::tokenize(...).
2016-01-27 13:43:39 -08:00