Commit Graph

3985 Commits

Author SHA1 Message Date
Hamish Knight
7302792506 [IDE] Use method result type for getTypeOfMember call
Previously we were defaulting to the method's
interface type, which could lead to calling `subst`
with a GenericFunctionType. Instead, pass the
result type only, as that's all we want anyway.

rdar://77259607
2021-07-20 14:11:30 +01:00
Rintaro Ishizaki
5559d9406f [CodeCompletion] NFC: rename CallParameter* to CallArgument*
Since these chunks are for call sites, the correct term is "argument".
2021-07-19 16:30:12 -07:00
swift-ci
bfeb8e4de7 Merge remote-tracking branch 'origin/main' into rebranch 2021-07-19 10:34:31 -07:00
Hamish Knight
63c6f987de Merge pull request #38447 from hamishknight/fewer-substitutions-for-you 2021-07-19 18:14:09 +01:00
Hamish Knight
f90befe441 [CodeCompletion] Use substGenericArgs in getTypeOfMember
For a GenericFunctionType, use `substGenericArgs`
instead of `subst`, as the latter would form a bad
generic signature if there were UnresolvedTypes
present in the base type, causing the GSB to blow
up when attempting to canonicalize it.

rdar://80635105
2021-07-19 11:26:07 +01:00
swift-ci
9c09c7fb37 Merge remote-tracking branch 'origin/main' into rebranch 2021-07-16 17:54:28 -07:00
Rintaro Ishizaki
18dc9c1c27 [CodeCompletion] Remove CodeComletionString::getName()
`CodeCompletioString::getName()` was used only as the sorting keys in
`CodeCompletionContext::sortCompletionResults()` which is effectively
deprecated. There's no reason to check them in `swift-ide-test`. Instead,
check `printCodeCompletionResultFilterName()` that is actually used for
filtering.
2021-07-16 13:24:19 -07:00
swift-ci
8fade629bd Merge remote-tracking branch 'origin/main' into rebranch 2021-07-13 10:13:24 -07:00
Alex Hoppen
ebfb3a5f5e Merge pull request #38331 from ahoppen/pr/rename-captured-variables-once
[Refactoring] Only rename variables in capture lists once
2021-07-13 19:11:20 +02:00
swift-ci
1201a5c4ba Merge remote-tracking branch 'origin/main' into rebranch 2021-07-13 09:14:51 -07:00
Slava Pestov
77565ff849 IDE: Remove bogus use of getCanonicalTypeInContext()
The GenericSig might come from a protocol extension.

The original types in the Requirement come from this generic signature.

However, the Requirement can then be substituted with the base type's
concrete substitutions, and if the base type is a conforming nominal
type, we now have a Requirement whose types are written in terms of
the conforming nominal type's generic signature.

Therefore, the call to getCanonicalTypeInContext() might not produce
correct results, since there's no guarantee the protocol extension's
GenericSignature has the same requirements as the conforming type's.

This used to just silently produce incorrect results, but now asserts
when the RequirementMachine is enabled.

To fix this I replaced these calls with plain old getCanonicalType()
that does not take a GenericSignature.

If we find a case that is now broken as a result of this change, we'll
need to re-introduce some bookkeeping here to keep track of *which*
GenericSignature generates the types in the substituted Requirement.
2021-07-12 23:08:31 -04:00
swift-ci
a3ebc9a069 Merge remote-tracking branch 'origin/main' into rebranch 2021-07-12 10:51:07 -07:00
Doug Gregor
06bbc70b3e Module printing and serialization support for @unchecked Sendable 2021-07-11 12:29:54 -07:00
Alex Hoppen
a535203096 [Refactoring] Only rename variables in capture lists once
Inside capture lists like `{ [test] in }`, `test` refers to both the newly declared, captured variable and the referenced variable it is initialized from. We currently try to rename it twice, yielding invalid, confusing results. Make sure to only record this situation once.

Fixes rdar://78522816 [SR-14661]
2021-07-09 11:38:37 +02:00
swift-ci
3c890a3ee6 Merge remote-tracking branch 'origin/main' into rebranch 2021-07-07 15:52:59 -07:00
Alex Hoppen
ca26a1a3fe Merge pull request #38227 from ahoppen/pr/ambiguous-completion-handler-calls
[Async Refactoring] Split ambiguous (error + success) completion handler calls into success and error case
2021-07-08 00:41:56 +02:00
swift-ci
8eed427d64 Merge remote-tracking branch 'origin/main' into rebranch 2021-07-07 06:34:04 -07:00
QuietMisdreavus
0cc6ce962a Merge pull request #38070 from apple/QuietMisdreavus/spi-comments
include comments on SPI symbols when they're in symbol graphs
2021-07-07 07:30:04 -06:00
Alex Hoppen
cd31fa0f73 [Async Refactoring] Improve fatalError message to unwrap result arguments in continuation
In the previous `fatalError` message `Expected non-nil result 'result' for nil error`, it wasn’t exactly clear wht the `error` referred to. In some cases, when the error was ignored, there wasn’t even an `error` variable in the refactored code.

The new `Expected non-nil result '...' in the non-error case` is a little more generic and also fits if an error is ignored.
2021-07-07 12:05:37 +02:00
Alex Hoppen
edc1393291 [Async Refactoring] Rename 'success param/argument' to 'result' in fatalError messages
The 'success param/argument' is a terminology we use internally in the refactoring and not one we want to present to the user. Just name it 'result' instead.
2021-07-07 11:54:11 +02:00
Alex Hoppen
06219cdfa2 [Async Refactoring] Remove assertions for nil result values in async wrapper
Since we aren’t checking that all result arguments are `nil` if there was an `error` in all the other refactorings, also remove the assertions in the async wrapper.
2021-07-07 11:54:11 +02:00
Alex Hoppen
6cbbb7cb1f [Async Refactoring] Split ambiguous (error + success) completion handler calls into success and error case
Previously, when a completion handler call had arguments for both the success and error parameters, we were always interpreting it as an error call. In case the error argument was an `Optional`, this could cause us to generate code that didn't compile, because we `throw`ed the `Error?` or passed it to `continuation.resume(throwing)`, both of which didn't work.

We now generate an `if let` statement that checks if the error is `nil`. If it is, the error is thrown. Otherwise, we interpret the call as a success call and return the result.

- Example 1 (convert to continuation)
-- Base Code
```swift
func test(completionHandler: (Int?, Error?) -> Void) {
  withoutAsyncAlternativeThrowing { (theValue, theError) in
    completionHandler(theValue, theError)
  }
}
```
-- Old Refactoring Result
```swift
func test() async throws -> Int {
  return try await withCheckedThrowingContinuation { continuation in
    withoutAsyncAlternativeThrowing { (theValue, theError) in
      continuation.resume(throwing: theError) // error: Argument type 'Error?' does not conform to expected type 'Error'
    }
  }
}
-- New Refactoring Result
```swift
func testThrowingContinuationRelayingErrorAndResult() async throws -> Int {
  return try await withCheckedThrowingContinuation { continuation in
    withoutAsyncAlternativeThrowing { (theValue, theError) in
      if let error = theError {
        continuation.resume(throwing: error)
      } else {
        guard let theValue = theValue else {
          fatalError("Expected non-nil success argument 'theValue' for nil error")
        }
        continuation.resume(returning: theValue)
      }
    }
  }
}
```

- Example 2 (convert to async/await)
-- Base Code
```swift
func test(completion: (String?, Error?) -> Void) {
  simpleErr() { (res, err) in
    completion(res, err)
  }
}
```
-- Old Refactoring Result
```swift
func test() async throws -> String {
  let res = try await simpleErr()
  throw <#err#>
}
```
-- New Refactoring Result
```swift
func test() async throws -> String {
  let res = try await simpleErr()
  return res
}
```
2021-07-07 11:54:11 +02:00
swift-ci
e0e2634b84 Merge remote-tracking branch 'origin/main' into rebranch 2021-07-06 09:35:07 -07:00
Alex Hoppen
03d3887bba [Async Refactoring] Convert data structure storing continuation resume args to std::vector
The `std::vector` keeps its elements alive. Currently, we might be accessing uninitalized memory if the call of `callArgs(CE)` (which owns its elements in case there is a single element) goes out of scope before `Args`.
2021-07-06 18:08:12 +02:00
Alex Hoppen
c3e9676cb1 Merge pull request #38261 from ahoppen/pr/check-semantics-expr-for-completion-handler-call
[Async Refactoring] Get semantics providing expr to decide if call is to completion handler
2021-07-06 10:53:56 +02:00
Alex Hoppen
ec8957972a [Async Refactoring] Get semantics providing expr to decide if call is to completion handler
Resolves rdar://78011350
2021-07-05 17:41:39 +02:00
Alex Hoppen
3dcb08a369 [Async Refactoring] Cosmetic Improvements to "Add Async Wrapper" Refactoring
Two mostly-cosmetic change to the "Add Async Wrapper" refactoring
- Rename the continuation from `cont` to `continuation` and error from `err` to `error` to better match Swifts naming guidelines
- Add assertions that all result parameters are `nil` if an error is passed to the completion handler.

Resolves rdar://80172152
2021-07-05 13:34:27 +02:00
Evan Wilde
2c04be2724 llvm::StringRef compare_lower -> compare_insensitive
The `compare_lower` API was replaced with `compare_insensitive` in llvm
commit 2e4a2b8430aca6f7aef8100a5ff81ca0328d03f9.

git clang-format ran.

(cherry picked from commit aca2de95ee)
2021-07-02 10:55:17 -07:00
Evan Wilde
42ff140171 llvm::StringRef equals_lower -> equals_insensitive
The `equals_lower` API was replaced with `equals_insensitive` in llvm
commit 2e4a2b8430aca6f7aef8100a5ff81ca0328d03f9 and
3eed57e7ef7da5eda765ccc19fd26fb8dfcd8d41.

Ran git clang-format.

(cherry picked from commit e21e70a6bf)
2021-07-02 10:55:17 -07:00
Alex Hoppen
54fcc90841 [Async Refactoring] Wrap code in a continuation if conversion doesn't yield reasonable results
If we are requested to convert a function to async, but the call in the function’s body that eventually calls the completion handler doesn’t have an async alternative, we are currently copying the call as-is, replacing any calls to the completion handler by placeholders.

For example,
```swift
func testDispatch(completionHandler: @escaping (Int) -> Void) {
  DispatchQueue.global.async {
     completionHandler(longSyncFunc())
  }
}
```
becomes
```swift
func testDispatch() async -> Int  {
  DispatchQueue.global.async {
     <#completionHandler#>(longSyncFunc())
  }
}
```

and

```swift
func testUrlSession(completionHandler: @escaping (Data) -> Void) {
  let task = URLSession.shared.dataTask(with: request) { data, response, error in
    completion(data!)
  }
  task.resume()
}
```
becomes
```swift
func testUrlSession() async -> Data {
  let task = URLSession.shared.dataTask(with: request) { data, response, error in
    <#completion#>(data!)
  }
  task.resume()
}
```

Both of these are better modelled using continuations. Thus, if we find an expression that contains a call to the completion handler and can’t be hoisted to an await statement, we are wrapping the rest of the current scope in a `withChecked(Throwing)Continuation`, producing the following results:

```swift
func testDispatch() async -> Int {
  return await withCheckedContinuation { (continuation: CheckedContinuation<Int, Never>) in
    DispatchQueue.global.async {
      continuation.resume(returning: syncComputation())
    }
  }
}
```

and

```swift
func testDataTask() async -> Int?
  return await withCheckedContinuation { (continuation: CheckedContinuation<Data, Never>) in
    let task = URLSession.shared.dataTask { data, response, error in
      continuation.resume(returning: data!)
    }
    task.resume()
  }
}
```

I think both are much closer to what the developer is actually expecting.

Resolves rdar://79304583
2021-07-02 15:48:41 +02:00
Alex Hoppen
d0472e1b21 [Async Refactoring] Code style improvements 2021-07-01 15:57:42 +02:00
Alex Hoppen
7a68a1d834 Merge pull request #38191 from ahoppen/pr/implict-return-async-refactoring
[Async Refactoring] Add `return` keyword if wrapping `ReturnStmt` is implicit
2021-07-01 15:40:00 +02:00
Alex Hoppen
f7c7599a8c [Async Refactoring] Add return keyword if wrapping ReturnStmt is implicit
Previously, in the following case we were failing to add a `return` keyword inside `withImplicitReturn`.
```
func withImplicitReturn(completionHandler: (String) -> Void) {
  simple {
    completionHandler($0)
  }
}
```

This is because the call of `completionHandler($0)` is wrapped by an implicit `ReturnStmt` and thus we assumed that there was already a `return` keyword present.

Fix this issue by checking if the wrapping `ReturnStmt` is implicit and if it is, add the `return` keyword.

Fixes rdar://80009760
2021-07-01 10:21:46 +02:00
Doug Gregor
80b6fbde88 Merge pull request #38186 from DougGregor/actors-and-global-actors
Semantic tweaks to (global) actors to bring them in line with the accepted proposals
2021-06-30 19:02:12 -07:00
Victoria Mitchell
85fabb23ed include comments on SPI symbols when they're in symbol graphs 2021-06-30 16:13:08 -06:00
Alex Hoppen
39e92db1b1 Merge pull request #38049 from ahoppen/pr/keypath-completion
[CodeCompletion] Migrate key path completion to be solver based
2021-06-30 22:03:44 +02:00
Doug Gregor
9ec20776c9 [SE-0306] Make actors semantically "final".
Treat actors as being semantically `final` throughout the type checker.
This allows, for example, a non-`required` initializer to satisfy a
protocol requirement.

We're leaving the ABI open for actor inheritance should we need it.

Addresses rdar://78269551.
2021-06-30 10:59:49 -07:00
Alex Hoppen
3ea37693a5 Merge pull request #38085 from fwcd/fix-wildcard-name-range
[IDE] Fix name range of wildcard declarations
2021-06-29 15:03:27 +02:00
Hamish Knight
0d4eb978da [Async Refactoring] Add missing null type check
Don't crash if we have a boolean condition without
a type, as that may occur in invalid code.

rdar://79864182
2021-06-28 16:03:54 +01:00
Alex Hoppen
d64b8ecea6 [CodeCompletion] Migrate key path completion to be solver based
This commit essentially consistes of the following steps:
- Add a new code completion key path component that represents the code completion token inside a key path. Previously, the key path would have an invalid component at the end if it contained a code completion token.
- When type checking the key path, model the code completion token’s result type by a new type variable that is unrelated to the previous components (because the code completion token might resolve to anything).
- Since the code completion token is now properly modelled in the constraint system, we can use the solver based code completion implementation and inspect any solution determined by the constraint solver. The base type for code completion is now the result type of the key path component that preceeds the code completion component.

This resolves bugs where code completion was not working correctly if the key path’s type had a generic base or result type. It’s also nice to have moved another completion type over to the solver-based implementation.

Resolves rdar://78779234 [SR-14685] and rdar://78779335 [SR-14703]
2021-06-25 23:19:35 +02:00
Alex Hoppen
ffbbbaffca Merge pull request #38052 from ahoppen/pr/use-closure-label-for-async-return-type
[Refactoring] Use internal completion handler labels for async function's return type
2021-06-25 12:57:00 +02:00
Fredrik Wieczerkowski
b2fb9e4494 Fix name range of wildcard names in walkToDeclPre 2021-06-24 22:01:32 +02:00
Alex Hoppen
ba910cc786 Merge pull request #37867 from fwcd/sourcekit-var-types
[SourceKit] Add `CollectVariableType` request
2021-06-24 08:50:45 +02:00
Alex Hoppen
d944b8bd49 [Refactoring] Use internal completion handler labels for async function's return type
If a completion handler specifies internal parameter labels, we can use those to label the elements of the tuple returned by the async alternative.

For example
```swift
func foo(completion: (_ first: String, _ second: String) -> Void) { }
```
gets refactored to
```swift
func foo() async -> (first: String, second: String) { }
```

Resolves rdar://77268040
2021-06-24 08:00:28 +02:00
Alex Hoppen
872ecb01e8 Merge pull request #37711 from ahoppen/pr/global-actor-completion
[CodeComplete] Mark results as not recommended if global actor context doesn't match
2021-06-23 18:49:03 +02:00
Alex Hoppen
ada9c9ad4e Merge pull request #38000 from ahoppen/pr/enum-unresolved-dot-arg-label
[IDE] Complete enum argument labels in unresolved member completions
2021-06-23 14:32:27 +02:00
Rintaro Ishizaki
013333b0d7 [CodeCompletion] Allow unresolved types in Callee analysis
struct Generic<T> {
    init(destination: T, isActive: Bool) {  }
  }

  invalid {
    Generic(destination: true, #^COMPLETE^#)
  }

In this case, since `invalid { ... }` cannot be type checked.
`ExprContextAnalysis` tries to type check `Generic` alone which resolves
to bound `Generic` type with an unresolved type. Previously, we used to
give up the analysis when seeing unresolved type. That caused mis callee
analyis.

rdar://79092374
2021-06-22 17:31:44 -07:00
Fredrik Wieczerkowski
b904d0fc0c Address stylistic suggestions in VariableTypeCollector
Rename VariableTypeCollector::getTypeOffsets to ::getTypeOffset and only
return the start offset, since the end offset is no longer needed (the
string is null-terminated).

Also improve variable naming slightly.
2021-06-22 15:14:27 +02:00
Fredrik Wieczerkowski
1a844efe5e Ignore error types in VariableTypeCollector
Also add a test to verify that error types get ignored (as intended).
2021-06-22 15:02:43 +02:00
Fredrik Wieczerkowski
7a73c99510 Migrate VariableTypeCollector to SourceRange
- Add SourceRange::contains and SourceRange::overlaps
- Use SourceRange in VariableTypeCollector
2021-06-21 19:33:52 +02:00