Commit Graph

3985 Commits

Author SHA1 Message Date
Hamish Knight
07cdc2029e [Refactoring] Unwrap optional chains in async transform
Remove an optional chain of a success parameter,
as it will no longer be optional, similar to how
we remove a force unwrap.

Note that while this is a locally valid transform
within the optional chain, e.g `foo?.x` -> `foo.x`,
it may change the type of the overall chain, which
could cause errors elsewhere in the code. However
this is generally more useful to the user than
just leaving `foo` as a placeholder. Note this is
only the case when no other optionals are involved
in the chain, e.g `foo?.x?.y` -> `foo.x?.y` is
completely valid.

Resolves rdar://74014826.
2021-04-30 14:34:31 +01:00
Alex Hoppen
b2378a401e [Refactoring] Convert completion handler when converting function to async
Convert function to async currently only adds "async" to the function and runs the convert call refactoring on the body.

This was intentional, but it turns out to be somewhat confusing. Instead, run the same refactoring as the add async alternative refactoring but just replace rather than add.

Resolves rdar://77103049
2021-04-30 12:53:22 +02:00
Hamish Knight
7e4b66e071 Merge pull request #37131 from hamishknight/out-of-the-void
[Refactoring] Improve Void handling for async conversion
2021-04-30 11:27:30 +01:00
Rintaro Ishizaki
8672bacc2b Merge pull request #37144 from rintaro/sourcekit-completion-rdar77188260
[CodeCompletion] Prioritize call argument pattern
2021-04-29 19:58:21 -07:00
Hamish Knight
c1e4dc3d82 [Refactoring] Improve Void handling for async conversion
When converting a function with a completion handler
that has a Void success parameter, e.g
`(Void?, Error?) -> Void`, or more likely a
`Result<Void, Error>` parameter, make sure to omit
the `-> Void` from the resulting async function
conversion.

In addition, strip any Void bindings from an async
function call, and any explicit Void return values
from inside the async function.

Resolves rdar://75189289
2021-04-30 01:09:04 +01:00
Rintaro Ishizaki
3c2433c942 [CodeCompletion] Prioritize call argument pattern
struct Foo {
    init(_ arg1: String, arg2: Int) {}
    init(label: Int) {}
  }
  func test(strVal: String) {
    _ = Foo(<HERE>)
  }

In this case, 'strVal' was prioritized because it can use as an argument
for 'init(_:arg2:)'. However, argument labels are almost always
preferable, and if the user actually want 'strVal', they can input a few
characters to get it at the top. So we should always prioritize call
argument patterns.

rdar://77188260
2021-04-29 13:23:15 -07:00
Rintaro Ishizaki
a08e3e58a7 [Completion] Look through implicit expr when collecting possible callees
For example:
  class Base {
    init(_: Int) {}
    convenience init(_: Int) { self.init() }
  }
  class Derived: Base {
    convenience init(sub: Int) { self.init(sub) }
  }
  Derived(#^HERE^#

In this case, the call is type checked to 'Base.init(_:)' and 'Derived'
is wrapped with 'MetatypeConversionExpr' with type 'Base.Type'. We need
to look through it to get the 'TypeExpr' with 'Derived.Type'.

rdar://74233797
2021-04-28 18:47:08 -07:00
Rintaro Ishizaki
f6d49baa36 Merge pull request #37095 from rintaro/sourcekit-completion-rdar77164709
[SourceKit] Adjust result sorting in complete.open/update
2021-04-28 09:31:31 -07:00
Alex Hoppen
1bd6086cbf Merge pull request #37071 from ahoppen/pr/block-convention-to-async
[Refactoring] Support refactoring to async if callback is `@convention(block)`
2021-04-28 11:40:19 +02:00
Rintaro Ishizaki
75ff9480c2 [CodeCompletion] Boost exact case-sensitive prefix match
When there are symbols 'Label' and 'label', if a user type 'Lab',
'Label' should be prioritized.

rdar://77164709
2021-04-27 22:32:37 -07:00
Alex Hoppen
f17fe868c6 [Refactoring] Support refactoring to async if callback is @convention(block)
We already have special logic to extrac the closure for closures with capture lists, add the same kind of logic for closures that are marked `@convention(block)` etc.

Resolves rdar://75301524 [SR-14328]
2021-04-27 22:25:57 +02:00
Alex Hoppen
727c11dc4f Merge pull request #37037 from ahoppen/pr/vararg-label-completion
[CodeCompletion] Fix code suggestions for arguments in vararg followed by normal arg
2021-04-23 21:33:06 +02:00
Alex Hoppen
2392e79ec9 [CodeCompletion] Fix code suggestions for arguments in vararg followed by normal arg
For a function and call like
```swift
func test(_: Foo..., yArg: Baz) {}
test(.bar, #^COMPLETE^#)
```
the parser matches the code completion token to the `yArg` with a missing label, because this way all parameters are provided. However, because of this we don’t suggest any variables that could belong the the previous vararg list.

To fix this, if we encounter such a situation (argument without label after vararg), manually adjust the code completion token’s position in params to belong to the vararg list.

Fixes rdar://76977325 [SR-14515]
2021-04-23 17:23:57 +02:00
Alex Hoppen
16adf76b68 Merge pull request #36994 from ahoppen/pr/refactor-protocol-requirement-async
[Refactoring] Fix crash when refactoring protocol requirement to async
2021-04-22 17:02:44 +02:00
Alex Hoppen
9d62f9d4db [Refactoring] Fix crash when refactoring protocol requirement to async
When a function declaration has no body (e.g. because it’s a protocol requirement), we construct the range to replace by the `async` keyword as follows:
- Start: One character after the closing `)` (or potentially the `throws` keyword if it exists)
- End: Last token in the function declaration

Since the last token in the function declaration is the `)`, we end up with a range that has `End < Start`, which crashes when trying to print the range.

If the function has no body, we should just use the range’s start location as the end location to construct an empty range.

Fixes rdar://76677035
2021-04-22 11:56:34 +02:00
Ben Barham
9ca7663f23 [Gardening] Move functions only used in SourceKit out of lib/IDE
NFC - `getLocationInfo` and `getLocationInfoForClangNode` are both moved
and formatted with clang-format.
2021-04-21 13:22:37 +10:00
Alejandro Alonso
444c35cf8d Merge pull request #36953 from Azoy/isType-isDeclType
[NFC] Introduce isDecl and getDeclType
2021-04-20 15:33:00 -04:00
Azoy
9ed732f0ab Introduce isDecl and getDeclType
fix enum logic issue

fix tests

guard against null types
2021-04-20 02:22:16 -04:00
Ben Langmuir
fa476b0a8d [completion] Make NotRecommendedReason an enum class 2021-04-19 13:22:13 -07:00
Ben Langmuir
be7b5a7179 [completion] Clarify and simplify not-recommended state
Combine IsNotRecommended with NotRecommendedReason and improve the names
of the existing cases to more clearly identify the cases they apply to.
Now all not-recommended completions are required to have a reason.
2021-04-19 09:43:28 -07:00
Alex Hoppen
0bc679c6e9 Merge pull request #36927 from ahoppen/pr/fast-completion-bug
[CodeCompletion] Reset diagnostics when reusing an ASTContext for completion
2021-04-15 19:14:32 +02:00
Alex Hoppen
6085e1dca4 [CodeCompletion] Reset diagnostics when reusing an ASTContext for completion
The diagnosticc engine is keeping track of state which might modify parsing/typechecking behaviour. In the added test case the `fatalErrorOccurred` flag was during the first completion. The flag was still `true` for the second completion, causing parsing/typechecking to behave slightly differently. Because of this, the ExprRewriter failed when applying a constraint system solution, not properly cleaning up its `ExprStack`.

This PR tackles both issues:
1) Reset the `hadError` flags in the diagnostics engine
2) Clean up the `ExprRewriter`’s `ExprStack` when rewriting a target fails.

Either of these changes fixes the crash in the test case but I think both could manifest through different code paths in different scenarios.

Fixes rdar://76051976 [SR-14430]
2021-04-15 13:07:27 +02:00
Alex Hoppen
f539d3340b Merge pull request #36774 from ahoppen/pr/complete-generic-constructor
[CodeComplete] Complete argument labels in generic initializer
2021-04-13 18:52:47 +02:00
Ben Barham
299df93a7f Merge pull request #36807 from bnbarham/use-original-locs
Replace uses of presumed locations where they do not make sense
2021-04-13 08:48:23 +10:00
Alex Hoppen
f96548820d [CodeComplete] Complete argument labels in generic initializer
The actual fix is to perform qualified lookup on a TypeExpr in `collectPossibleCalleesForApply`.

This changes the behaviour of some test cases in `complete_multiple_trailingclosure.swift`, which now provide argument labels. To make the choices suggested less verbose, I refined the parameter matching to only match trailing closures to parameters of function types.

In `INIT_FALLBACK_1` we technically shouldn't be suggesting `arg3` based on the matched argument types (the closure returns `Int` and the constructor with `arg3` requires the closure to return `String`), but AFAICT we aren't doing type-checking at this stage, so there's no way to rule it out.
2021-04-12 10:10:01 +02:00
Ben Barham
20f45ec284 Replace uses of presumed locations where they do not make sense
Various uses of `getPresumedLineAndColumnForLoc` were likely added when
that function was the very misleading name `getLineAndColumn`. Change
these to use `getLineAndColumnForBuffer` instead where appropriate, ie.
we want the underlying file rather than the location to display to the
user.

There were also some cases where the buffer identifier had been swapped
to use the display name instead, under the assumption that the presumed
location was needed. Updated those as well.

SingleRawComment: Lines are only used when merging comments, where the
original location is fine to use.

Index: Doesn't store the file set in #sourceLocation, so using the
presumed line would end up pointing to a location that makes no sense.

Editor functionality: Formatting and refactoring are on the current
file. Using the presumed location would result in incorrect
replacements.
2021-04-10 09:49:31 +10:00
Alex Hoppen
7e536ff365 [CodeComplete] Complete argument labels after vararg
Currently, if the code completion token is after a label that refers to a vararg, it is part of that VarargExpansionExpr, so we don’t suggest the subsequent parameter’s label.

Add special handling to detect this situation and suggest the parameter label.

Fixes rdar://76355192
2021-04-08 19:33:30 +02:00
Alex Hoppen
fd8e34913a Merge pull request #36551 from ahoppen/pr/internal-labels-in-closures
[CodeComplete] Default parameter names of completed closure to internal names
2021-04-06 15:30:26 +02:00
Alex Hoppen
865e80f9c4 [CodeComplete] Default parameter names of completed closure to internal names
If have a function that takes a trailing closure as follows
```
func sort(callback: (_ left: Int, _ right: Int) -> Bool) {}
```
completing a call to `sort` and expanding the trailing closure results in
```
sort { <#Int#>, <#Int#> in
  <#code#>
}
```

We should be doing a better job here and defaulting the trailing closure's to the internal names specified in the function signature. I.e. the final result should be
```
sort { left, right in
  <#code#>
}
```

This commit does exactly that.

Firstly, it keeps track of the closure's internal names (as specified in the declaration of `sort`) in the closure's type through a new `InternalLabel` property in `AnyFunctionType::Param`. Once the type containing the parameter gets canonicalized, the internal label is dropped.

Secondly, it adds a new option to `ASTPrinter` to always try and print parameter labels. With this option set to true, it will always print external paramter labels and, if they are present, print the internal parameter label as `_ <internalLabel>`.

Finally, we can use this new printing mode to print the trailing closure’s type as
```
<#T##callback: (Int, Int) -> Bool##(_ left: Int, _ right: Int) -> Bool#>
```

This is already correctly expanded by code-expand to the desired result. I also added a test case for that behaviour.
2021-04-01 19:14:19 +02:00
Alex Hoppen
47b012d469 Merge pull request #36629 from ahoppen/pr/visit-attributes-in-order
[SemaAnnotator] Fix bug causing custom attributes to be walked out of order
2021-04-01 18:22:01 +02:00
Alex Hoppen
c3bfc541ca Merge pull request #36628 from ahoppen/pr/balanced-pre-post
[IDE] Ensure every walkToPre call is matched with a walkToPost call in SemaAnnotator
2021-04-01 18:21:24 +02:00
Alex Hoppen
16baf61601 [RangeInfo] Acknowledge that SemaAnnotator walks the tree in source order *excluding* attributes
`SemaAnnotator` walks the tree in source order with respect to the source ranges *excluding* attributes, but `RangeResolver` considers attributes part of their declaration. Thus they disagree on what “walking in source order means”. `SemaAnnotator` will visit the attributes *before* the decl they are on, while `RangeResolver` as currently implemented expects them *as part of* the decl they are on.

Thus, for the purpose of `RangeResolver`, we need to assume that nodes are visited in arbitrary order and we might encounter enclosing nodes after their children.

Thus, when we find a new node, remove all nodes that it encloses from `ContainedASTNodes`.

Fixes rdar://64140713 [SR-12958]
2021-03-31 13:32:02 +02:00
Ben Barham
0b3164203b Merge pull request #36547 from bnbarham/include-init
[SourceKit/CursorInfo] Add constructor to call results
2021-03-31 16:40:02 +10:00
Rintaro Ishizaki
8c2e54bbde Merge pull request #36634 from rintaro/ide-completion-rdar75963052
[CodeCompletion] Stop suggesting initializer calls on unresolved member
2021-03-30 09:48:24 -07:00
Alex Hoppen
4faa3973ac Merge pull request #36607 from ahoppen/pr/suggest-self-in-where-clause
[CodeComplete] In where clauses, suggest Self and the current type
2021-03-30 13:17:45 +02:00
Alex Hoppen
981b663851 [IDE] Ensure every walkToPre call is matched with a walkToPost call in SemaAnnotator
We had some unbalanced calls of `walkTo*Pre` and `walkTo*Post` in `SemaAnnotator`.

The main fix was to set `Cancelled` to `true` if traversal is being stopped in `walkToExprPre`.

While I was at it, I also
- Added some more checks, ensuring that no more `walkTo*` calls are issued after `Cancelled` has been set to `true`.
- Added some comments, describing the intended traversal behaviour.
- Inverted the return value of the `ReportParamList` lambda to be in line with the return value of the enclosing `walkToDeclPre`
- Moved `walkToExprPost` to be place right after `walkToExprPre`

Resolves rdar://64139829 [SR-12957]
2021-03-30 12:35:29 +02:00
Ben Barham
3ea9bed415 [SourceKit/CursorInfo] Add constructor to call results
Cursor info for a constructor would previously give the cursor info for
the containing type only. It now also adds cursor info for the
constructor itself in a "secondary_symbols" field.

Refactor `passCursorInfoForDecl` to use a single allocator rather than
keeping track of positions in a buffer and assigning everything at the
end of the function.

Refactor the various available refactoring gathering functions to take a
SmallVectorImpl and to not copy strings where they don't need to.

Resolves rdar://75385556
2021-03-30 13:23:59 +10:00
Rintaro Ishizaki
4df17c5bd2 [CodeCompletion] Stop suggesting initializer calls on unresolved member
For example, for

  class C {
    class D: C {
        init() {}
    }
  }
  let _: C = .#^HERE^#

We used to suggest 'D()' (not just 'D') because it was invalid without
initialization. However, after SE-0287, it can be valid. For example, if
'D' has:

  extension C.D {
    static var staticC: C { ... }
  }

Users can write:

  let _: C = .D.staticC

So we should not suggest constructor calls. Also, this is consistent with
normal type name completion. Users still can get initializer completions
by adding '(' after the type name.

Although initialization call completion with type names was convenient
in some cases, it's too annoying when we have unrelated member types
like:

  enum MyEnum {
    typealias Content = Int
    case value(Content)
  }

We don't want `.Content(bitPattern)` etc for implicit member completion
for 'MyEnum' context type.

rdar://75963052
2021-03-29 15:37:13 -07:00
Doug Gregor
826b59b64a Merge pull request #36606 from DougGregor/remove-actor-independent-unsafe-isolation
[Concurrency] Remove actorIndependent(unsafe) isolation.
2021-03-26 12:30:10 -07:00
Alex Hoppen
943d7ee621 [CodeComplete] In where clauses, suggest Self and the current type
Fixes rdar://70058225
2021-03-26 17:43:35 +01:00
Doug Gregor
9d8fde8c18 [Concurrency] Remove actorIndependent(unsafe) isolation.
Don't treat `actorIndependent(unsafe)` as its own kind of isolation.
It was only really used as a bring-up hack to break the isolation model,
but shouldn't be in the user model of the language and causes
complications to the implementation.
2021-03-26 08:27:36 -07:00
Alex Hoppen
433d7564a4 [CodeComplete] Match argument labels when completing function arguments
Previously, we always assumed that the position in the arguments would match the position in the parameter, which isn’t true in case of defaulted arguments. Try matching parameters based on argument labels to give better completion results.

Fixes rdar://60346573
2021-03-25 20:54:07 +01:00
Alex Hoppen
cbd0206fd3 Merge pull request #36549 from ahoppen/pr/complete-self-dot-init
[CodeComplete] Complete parameter labels in self.init call
2021-03-25 16:29:35 +01:00
Rintaro Ishizaki
3434463368 [CodeCompletion] Factor out actor isolation analysis 2021-03-24 15:53:37 -07:00
Rintaro Ishizaki
b2174da15b [CodeCompletion] Update for actor isolation
For cross actor references:
* Annotate with 'async'
* "Not recommended" if there're non-'Sendable' arguments or return types

rdar://72200120
2021-03-24 15:52:44 -07:00
Alex Hoppen
11df457563 [CodeComplete] Complete parameter labels in self.init call
The `init` of `self.init` needs to be looked up on the Metatype of `self`, not on the type of `self` itself. We were already doing a similar special-casing for `super.init`, which I extened to also cover `self.init`.

Resolves rdar://36521732
2021-03-23 09:27:58 +01:00
Ben Barham
8948a034c8 Merge pull request #36508 from bnbarham/static-dynamic-flag
[SourceKit/CursorInfo] Mark dynamic calls
2021-03-23 15:27:37 +10:00
Ben Barham
19f23130d0 [SourceKit/CursorInfo] Mark dynamic calls
Adds two new fields to the cursor info response:
  1. is_dynamic: whether a call is dynamic
  2. receivers: receivers of the call (USRs)

Users of the CursorInfo request can use "is_dynamic" to decide whether
to lookup overrides or not, and then the "receivers" as the starting
point of the lookup.

Resolves rdar://75385900
2021-03-20 13:57:01 +10:00
Ben Barham
b889b0777d [IDE] Refactor some call related functions out of Index.cpp
The cursor info request also needs to output whether a call is "dynamic"
or not, move the functions related to this out of Index.cpp and into
IDE/Utils.cpp.

Also cleanup the `TrailingExpr` handling in `CursorInfoResolver` - it
only needs the first expression.
2021-03-20 13:57:01 +10:00
Rintaro Ishizaki
c991347160 [IDE] Explicitly specify 'SerializedOK=false' to 'getRawComment()'
This ensures that we don't try getRawComment() from serialized locations

rdar://problem/75010520
2021-03-18 17:30:36 -07:00