808 Commits

Author SHA1 Message Date
Luciano Almeida
90c5dfa9ed [Parse] Track whether an let _: pattern is an async let pattern 2022-04-17 14:06:39 -03:00
Alex Hoppen
bfc68f48e4 [Parser] When recovering from expression parsing don't stop at '{'
When recovering from a parser error in an expression, we resumed parsing at a '{'. I assume this was because we wanted to continue inside e.g. an if-body if parsing the condition failed, but it's actually causing more issue because when parsing e.g.

```swift
expr + has - error +

functionTakesClosure {
}
```

we continue parsing at the `{` of the trailing closure, which is a completely garbage location to continue parsing.

The motivating example for this change was (in a result builder)
```swift
Text("\(island.#^COMPLETE^#)")
takeTrailingClosure {}
```

Here `Text(…)` has an error (because it contains a code completion token) and thus we skip `takeTrailingClosure`, effectively parsing
```swift
Text(….) {}
```

which the type checker wasn’t very happy with and thus refused to provide code completion. With this change, we completely drop `takeTrailingClosure {}`. The type checker is a lot happier with that.
2022-04-07 09:19:22 +02:00
Rintaro Ishizaki
bcc003bd2d [CodeCompletion] Update for SE-0345 shorthand optional binding
Suggest visible optional values after 'if let'.

rdar://90399603
2022-04-05 09:56:14 -07:00
Doug Gregor
a6bcd80043 Merge pull request #40694 from calda/cal--if-let-shorthand
[SE-0345] Support `if let foo {` optional binding conditions
2022-03-31 10:49:45 -07:00
Cal Stephens
cc85edff22 Clean up implementation, add more tests 2022-03-23 17:43:03 -07:00
Cal Stephens
14076df392 Fix test failures 2022-03-16 16:08:26 -07:00
Alex Hoppen
82cb46c8b0 [CodeCompletion] Complete code completion tokens after if-statement as top-level
Instead of setting the code completion position when parsing the if-statement, which doesn’t create a `CodeCompletionExpr`, parse it as a new top-level expression.

As far as test-cases are concerned, this removes the “RareKeyword” flair from top-level completions in the modified test case. This makes sense IMO.
2022-03-14 14:40:11 +01:00
Cal Stephens
ac7529f5bd Improve diagnostic in cases like 'if let foo.bar' 2022-03-13 12:20:01 -07:00
Cal Stephens
b9c2370b1b Implement support for 'if let foo {' syntax 2022-01-04 09:36:20 -08:00
Rintaro Ishizaki
7c92a8e555 [SourceKit] Add a request to generate object files in SourceKit
Add 'request.compile'
2021-12-21 14:35:38 -08:00
Alex Hoppen
b888dc0e40 [Parser] Don't modify the current token kind when cutting off parsing
Previously, when we reached the maximum nesting level, we changed the current token’s kind to an EOF token. A lot of places in the parser are not set up to expect this token change. The intended workaround was to check whether pushing a structure marker failed (which would change the token kind) and bail out parsing if this happened. This was fragile and caused assertion failures in assert builds.

Instead of changing the current token’s kind, and failing to push the structure marker, let the lexer know that it should cut off lexing, essentially making the input buffer stop at the current position. The parser will continue to consume its current token (`Parser.Tok`) and the next token that’s already lexed in the lexer (`Lexer.NextToken`) before reaching the emulated EOF token. Thus two more tokens are parsed than before, but that shouldn’t make much of a difference.
2021-11-09 12:28:10 +01:00
Hamish Knight
e3e9ef90da [Parse] Properly reject labeled yield
Instead of asserting, emit a diagnostic with a
fix-it to remove the label.

SR-15066
rdar://82132821
2021-09-30 11:00:29 +01:00
Hamish Knight
a5775482ee [Parser] Adopt ArgumentList
Split up the expr list parsing members such that
there are separate entry points for tuple and
argument list parsing, and start using the argument
list parsing member for call and subscripts.
2021-09-01 18:40:24 +01:00
Hamish Knight
c70f280e4a [AST] Add CallExpr::createImplicitEmpty
Add a convenience constructor for an implicit
nullary call. This will become more useful when
the argument parameter starts taking an
ArgumentList.
2021-07-28 23:14:43 +01:00
Bruno Rocha
1fe3857735 [SE-0290] Add #unavailable 2021-07-02 13:35:11 +02:00
Rintaro Ishizaki
aa182ac8e0 [Parse] Don't skip '}' when recovering from 'default' outside 'switch'
That caused assertion failures in code completion.

rdar://78781163
2021-06-23 08:44:32 -07:00
Rintaro Ishizaki
b348bf60e1 [CodeCompletion] Complete pattern introducer for 'for'
After 'for', suggest 'try', 'await', 'var' and 'case'.

rdar://76355581
2021-05-06 18:13:43 -07:00
Alex Hoppen
931f3394d7 [Parse] Create SwitchStmt nodes for switch statements with errors
At the moment, if there is an error in the `switch` statement expression or if the `{` is missing, we return `nullptr` from `parseStmtSwitch`, but we consume tokens while trying to parse the `switch` statement. This causes the AST to not contain any nodes for the tokens that were consumed while trying to parse the `switch` statement.

While this doesn’t cause any issues during compilation (compiling fails anyway so not having the `switch` statement in the AST is not a problem) this causes issues when trying to complete inside an expression that was consumed while trying to parse the `switch` statement but doesn’t have a representation in the AST. The solver-based completion approach can’t find the expression that contains the completion token (because it’s not part of the AST) and thus return empty results.

To fix this, make sure we are always creating a `SwitchStmt` when consuming tokens for it.

Previously, one could always assume that a `SwitchStmt` had a valid `LBraceLoc` and `RBraceLoc`. This is no longer the case because of the recovery. In order to form the `SwitchStmt`’s `SourceRange`, I needed to add a `EndLoc` property to `SwitchStmt` that keeps track of the last token in the `SwitchStmt`. Theoretically we should be able to compute this location by traversing the right brace, case stmts, subject expression, … in reverse order until we find something that’s not missing. But if the `SubjectExpr` is an `ErrorExpr`, representing a missing expression, it might have a source range that points to one after the last token in the statement (this is due to the way the `ErrorExpr` is being constructed), therefore returning an invalid range. So overall I thought it was easier and safer to add another property.

Fixes rdar://76688441 [SR-14490]
2021-04-15 18:37:25 +02:00
Doug Gregor
540d2b03b1 [SE-0298: Async/Await: Sequences] Enable by default.
One still needs to import the _Concurrency library to use it.
2021-02-12 13:55:24 -08:00
Doug Gregor
238290cdc4 [SE-0296] Enable async/await by default.
Always parse `async` and `await`, allowing the definition and use of
asynchronous functions without the "experimental concurrency" flag.

Note that, at present, use of asynchronous functions requires one to
explicitly import or link against the `_Concurrency` library. We'll
sort this out in a follow-up change.

Tracked by rdar://73455330.
2021-02-05 09:51:46 -08:00
Philippe Hausler
6e05240426 AsyncSequence and protocol conformance rethrows (#35224)
* Initial draft of async sequences

* Adjust AsyncSequence associated type requirements

* Add a draft implementation of AsyncSequence and associated functionality

* Correct merge damage and rename from GeneratorProtocol to AsyncIteratorProtocol

* Add AsyncSequence types to the cmake lists

* Add cancellation support

* [DRAFT] Implementation of protocol conformance rethrowing

* Account for ASTVerifier passes to ensure throwing and by conformance rethrowing verifies appropriately

* Remove commented out code

* OtherConstructorDeclRefExpr can also be a source of a rethrowing kind function

* Re-order the checkApply logic to account for existing throwing calculations better

* Extract rethrowing calculation into smaller functions

* Allow for closures and protocol conformances to contribute to throwing

* Add unit tests for conformance based rethrowing

* Restrict rethrowing requirements to only protocols marked with @rethrows

* Correct logic for gating of `@rethrows` and adjust the determinates to be based upon throws and not rethrows spelling

* Attempt to unify the async sequence features together

* Reorder try await to latest syntax

* revert back to the inout diagnosis

* House mutations in local scope

* Revert "House mutations in local scope"

This reverts commit d91f1b25b59fff8e4be107c808895ff3f293b394.

* Adjust for inout diagnostics and fall back to original mutation strategy

* Convert async flag to source locations and add initial try support to for await in syntax

* Fix case typo of MinMax.swift

* Adjust rethrowing tests to account for changes associated with @rethrows

* Allow parsing and diagnostics associated with try applied to for await in syntax

* Correct the code-completion for @rethrows

* Additional corrections for the code-completion for @rethrows this time for the last in the list

* Handle throwing cases of iteration of async sequences

* restore building XCTest

* First wave of feedback fixes

* Rework constraints checking for async sequence for-try-await-in checking

* Allow testing of for-await-in parsing and silgen testing and add unit tests for both

* Remove async sequence operators for now

* Back out cancellation of AsyncIteratorProtocols

* Restructure protocol conformance throws checking and cache results

* remove some stray whitespaces

* Correct some merge damage

* Ensure the throwing determinate for applying for-await-in always has a valid value and adjust the for-await-in silgen test to reflect the cancel changes

* Squelch the python linter for line length
2021-01-25 18:48:50 -08:00
Anthony Latsis
47ce1529f0 Parse: Only diagnose dollar-prefixed identifiers that are Swift declarations 2020-11-19 20:30:53 +03:00
Slava Pestov
5808d9beb9 Parse: Remove parse-time name lookup 2020-11-16 22:39:44 -05:00
Alexis Laferrière
fa6f1b6b96 Merge pull request #33439 from xymus/expand-avail
[Sema] Define availability specification macros with a frontend flag
2020-10-08 09:25:32 -07:00
Slava Pestov
da1c5c99a9 Parse: Fix repeat/while error recovery path
We were creating an ErrorExpr whose source range overlaps with
the following statement, which is now flagged by ASTScope.
2020-10-06 15:39:10 -04:00
Alexis Laferrière
c6fc53e844 [Sema] Define availability via compiler flag
Introduce availability macros defined by a frontend flag.
This feature makes it possible to set the availability
versions at the moment of compilation instead of having
it hard coded in the sources. It can be used by projects
with a need to change the availability depending on the
compilation context while using the same sources.

The availability macro is defined with the `-define-availability` flag:

swift MyLib.swift -define-availability "_iOS8Aligned:macOS 10.10, iOS 8.0" ..

The macro can be used in code instead of a platform name and version:
@available(_iOS8Aligned, *)
public func foo() {}

rdar://problem/65612624
2020-10-06 11:25:20 -07:00
Slava Pestov
d4cc35a938 AST: Remove VarDecl::hasNonPatternBindingInit() 2020-09-18 16:11:06 -04:00
Slava Pestov
d7f4b1a1bd AST: Capture list bindings now point back to their parent CaptureListExpr
We'll need this to get the right 'selfDC' when name lookup
finds a 'self' declaration in a capture list, eg

class C {
  func bar() {}
  func foo() {
    _ = { [self] in bar() }
  }
}
2020-09-18 02:59:15 -04:00
Nathan Hawes
bb773232a8 [Parse][CodeCompletion] Stop code completion within a closure causing parser recovery after the closure.
For example, the completion below would trigger error recovery within the
closure, which we recover from by skipping to the first inner closure's right
brace. The fact that we recovered though, was not recorded. The closure is
treated as still being an error, triggering another recovery after it that
skips over the 'Thing' token, giving a lone closure expression, rather than a
call.

CreateThings {
    Thing { point in
      print("hello")
      point.#^HERE^#
    }
    Thing { _ in }
}

This isn't an issue for code completion when the outer closure is a regular
closure, but when it's a function builder, invalid elements result in no types
being applied (no valid solutions) and we end up with no completion results.

The fix here is removing the error status from the parser result after the
initial parser recovery.
2020-09-10 21:59:09 -07:00
Nathan Hawes
00994f1147 [Parse] Stop early exiting when parsing catch statements and ObjCSelector expressions that contain code completions. 2020-08-28 17:09:37 -07:00
Nathan Hawes
c4f05052da [Parse] Don't drop throws containing a code completion expression. 2020-08-28 17:09:37 -07:00
Anthony Latsis
efa8f86193 [NFC] FuncDecl: Strip factory constructors out of TypeLocs 2020-08-19 00:09:10 +03:00
Anthony Latsis
b26310ee97 TypeLoc: Offload TypeLoc off the ASTWalker 2020-08-04 18:13:28 +03:00
Chris Lattner
8bde04cc14 [Concurrency] Implement parsing and semantic analysis of await operator
Similar to `try`, await expressions have no specific semantics of their
own except to indicate that the subexpression contains calls to `async`
functions, which are suspension points. In this design, there can be
multiple such calls within the subexpression of a given `await`.

Note that we currently use the keyword `__await` because `await` in
this position introduces grammatical ambiguities. We'll wait until
later to sort out the specific grammar we want and evaluate
source-compatibility tradeoffs. It's possible that this kind of prefix
operator isn't what we want anyway.
2020-07-29 22:08:09 -07:00
Doug Gregor
f6e9f352f0 [Concurrency] Add async to the Swift type system.
Add `async` to the type system. `async` can be written as part of a
function type or function declaration, following the parameter list, e.g.,

  func doSomeWork() async { ... }

`async` functions are distinct from non-`async` functions and there
are no conversions amongst them. At present, `async` functions do not
*do* anything, but this commit fully supports them as a distinct kind
of function throughout:

* Parsing of `async`
* AST representation of `async` in declarations and types
* Syntactic type representation of `async`
* (De-/re-)mangling of function types involving 'async'
* Runtime type representation and reconstruction of function types
involving `async`.
* Dynamic casting restrictions for `async` function types
* (De-)serialization of `async` function types
* Disabling overriding, witness matching, and conversions with
differing `async`
2020-07-27 18:18:03 -07:00
Rintaro Ishizaki
28dacefd86 [Parse] Fix excessive skipping of '}'
* Don't skip r-brace in paren or square brackets
* Don't skip '}' when finding '{' on the same line

rdar://problem/65891507
2020-07-21 11:10:17 -07:00
Michael Gottesman
092edd6621 [ast] Rename VarPattern -> BindingPattern.
VarPattern is today used to implement both 'let' and 'var' pattern bindings, so
today is already misleading. The reason why the name Var was chosen was done b/c
it is meant to represent a pattern that performs 'variable binding'. Given that
I am going to add a new 'inout' pattern binding to this, it makes sense to
give it now a better fitting name before I make things more confusing.
2020-07-16 18:56:01 -07:00
Nathan Hawes
9bcb54910e [AST] Prefer the 'macOS' spelling over 'OSX' when printing the platform kind.
This affects module interfaces, interface generation in sourcekitd, and
diagnostics. Also fixes a fixit that was assuming the 'OSX' spelling when
computing the source range to replace.

Resolves rdar://problem/64667960
2020-07-08 13:51:25 -07:00
Rintaro Ishizaki
3ec250f701 [CodeCompletion] Wrap base expression with CodeCompletionExpr
For example for:

  funcName(base.<HERE>)

Wrap 'base' with 'CodeCompletionExpr' so that type checker can check
'base' independently without preventing the overload choice of 'funcName'.

This increases the chance of successful type checking.

rdar://problem/63965160
2020-06-05 15:51:07 -07:00
Rintaro Ishizaki
f107a15c63 [CodeCompletion] Skip to '=' after completion in 'if'/'guard' pattern
So that the parser can parse the subject expresion which provides the
expected type of the pattern.

rdar://problem/56802036
2020-05-29 13:56:30 -07:00
Owen Voorhees
dac96989a4 Fix comparisons between presumed and buffer line numbers 2020-05-26 08:02:33 -07:00
Owen Voorhees
45bc578ae5 [SourceManager] Rename line and column APIs for clarity 2020-05-21 12:54:07 -05:00
Robert Widmann
31242bc3da Remove The Parser Hack For If-Let
The parser used to rewrite

if let x: T

into

if let x: T?

This transformation is correct at face value, but relied on being able
to construct TypeReprs with bogus source locations. Instead of having
the parser kick semantic analysis into shape, let's perform this
reinterpretation when we resolve if-let patterns in statement
conditions.
2020-05-13 12:34:24 -07:00
John McCall
a518e759d9 WIP for a different syntax for multiple trailing closures
that allows arbitrary `label: {}` suffixes after an initial
unlabeled closure.

Type-checking is not yet correct, as well as code-completion
and other kinds of tooling.
2020-05-06 01:56:40 -04:00
Pavel Yaskevich
d06126da3b [Parser] Add support for multiple trailing closures syntax
Accept trailing closures in following form:

```swift
foo {
  <label-1>: { ... }
  <label-2>: { ... }
  ...
  <label-N>: { ... }
}
```

Consider each labeled block to be a regular argument to a call or subscript,
so the result of parser looks like this:

```swift
foo(<label-1>: { ... }, ..., <label-N>: { ... })
```

Note that in this example parens surrounding parameter list are implicit
and for the cases when they are given by the user e.g.

```swift
foo(bar) {
  <label-1>: { ... }
  ...
}
```

location of `)` is changed to a location of `}` to make sure that call
"covers" all of the transformed arguments and parser result would look
like this:

```swift
foo(bar,
   <label-1>: { ... }
)
```

Resolves: rdar://problem/59203764
2020-05-06 01:56:40 -04:00
Pavel Yaskevich
45ac1bcf17 [Parser] Adjust parseExprList to return multiple trailing closures
Also extend returned object from simplify being an expression to
`TrailingClosure` which has a label, label's source location and
associated closure expression.
2020-05-06 01:56:40 -04:00
Pavel Yaskevich
5cea9b9849 [AST] Add support for multiple trailing closures to the parser/expressions 2020-05-06 01:56:40 -04:00
Robert Widmann
7161ed01f8 Work Around IDE Structure Markers
Structure analysis trusts what should be implicit pattern nodes have the
right source location information in them. Preserve that behavior for
now.
2020-05-01 16:30:45 -07:00
Robert Widmann
0342855e50 [NFC] Debride Pattern.h of Implicit Tri-State
Remove all of this in favor of explicit constructors to preserve the one-liners, or distribute the setImplicit() calls to the callsites if necessary.
2020-04-30 22:03:55 -07:00
Rintaro Ishizaki
0f1cffd2d2 [CodeCompletion] Completion for control trasfer target
Completion after 'break' and 'continue'

rdar://problem/57016218
2020-04-17 14:18:33 -07:00