Commit Graph

315 Commits

Author SHA1 Message Date
Slava Pestov
3994c4679f Sema: Use getParameterType() instead of getOldType() in CSRanking.cpp
One last usage of getOldType() remains here, but it's actually
meaningful since we want to handle InOutType there, so it will
take more work to eliminate.
2021-04-08 21:26:42 -04:00
Pavel Yaskevich
dc6cf0330f [CSRanking] NFC: Fix bad merge artifact 2021-03-17 00:18:17 -07:00
Pavel Yaskevich
afa07a6cf2 [CSRanking] Add ImplicitValueConversion to getScoreKindName 2021-03-17 00:18:16 -07:00
Pavel Yaskevich
7ab93250ba [ConstraintSystem] Add a new score kind to model implicit value conversions 2021-03-17 00:18:07 -07:00
Doug Gregor
9ccf206feb [Concurrency] Tune overloading to to allow sync overloads in async contexts.
The existing overloading rules strongly prefer async functions within
async contexts, and synchronous functions in synchronous contexts.
However, when there are other differences in the
signature, particularly parameters of function type that differ in
async vs. synchronous, the overloading rule would force the use of the
synchronous function even in cases where the synchronous function
would be better. An example:

    func f(_: (Int) -> Int) { }
    func f(_: (Int) async -> Int) async { }

    func g(_ x: Int) -> Int { -x }

    func h() async {
      f(g) // currently selects async f, want to select synchronous f
    }

Effect the semantics change by splitting the "sync/async mismatch"
score in the constraint system into an "async in sync mismatch" score
that is mostly disqualifying (because the call will always fail) and a
less-important score for "sync used in an async context", which also
includes conversion from a synchronous function to an asynchronous
one. This way, only synchronous functions are still considered within
a synchronous context, but we get more natural overloading behavior
within an asynchronous context. The end result is intended to be
equivalent to what one would get with reasync:

  func f(_: (Int) async -> Int) async { ... }

Addresses rdar://74289867.
2021-03-02 23:14:08 -08:00
Nathan Hawes
8a660bb360 [CodeCompletion][CSRanking] Still allow some filtering of soltions when solving for code completion to improve performance
We were previously completely skipping the "best" solution filtering the solver
does to make sure we didn't miss any non-best but still viable solutions, as
the completions generated from them can make them become the best solution. E.g:

struct Foo { let onFoo = 10 }

func foo(_ x: Int) -> Int { return 1 }
func foo<T>(_ x: T) -> Foo { return Foo() }

foo(3).<here> // the "best" solution is the one with the more-specialized foo(x: Int) overload

In the example above we shouldn't remove the solution for foo(x: T) even though
there is a single "best" solution (`foo(x: Int)`) as picking a completion
result generated from it (`onFoo`) would make the foo(x: T) overload the best
and only viable solution.

Completely skipping this filtering as we were previously doing is overkill
though and adversely affects performance. E.g. it makes sense to filter out
and stop exploring solutions with overload choices for foo that required fixes
for missing arguments if there is another solution with an overload choice that
didn't require any fixes.

This patch restores best solution filtering during code completion and instead updates
the compareSolutions function it compare solutions based purely on their fixed score.

Resolves rdar://problem/73282163
2021-02-26 13:14:49 +10:00
Luciano Almeida
ef86e9edbe [ConstraintSystem] Adding new score kind SK_FunctionToAutoClosureConversion to increase impact of a function to autoclosure 2021-02-23 07:21:58 -03:00
Frederick Kellison-Linn
a53b1e4f3f [Sema] Always look through optionals for unresolved member lookup 2020-12-04 12:11:10 -05:00
Nathan Hawes
ca7fb37aba [CodeCompletion][Sema][Parse] Migrate unresolved member completion to the solver-based completion implementation
Following on from updating regular member completion, this hooks up unresolved
member completion (i.e. .<complete here>) to the typeCheckForCodeCompletion API
to generate completions from all solutions the constraint solver produces (even
those requiring fixes), rather than relying on a single solution being applied
to the AST (if any). This lets us produce unresolved member completions even
when the contextual type is ambiguous or involves errors.

Whenever typeCheckExpression is called on an expression containing a code
completion expression and a CompletionCallback has been set, each solution
formed is passed to the callback so the type of the completion expression can
be extracted and used to lookup up the members to return.
2020-11-13 15:37:14 -08:00
Pavel Yaskevich
461eafff54 [ConstraintSystem] NFC: Move ConstraintSystem.h to include/swift/Sema 2020-10-08 10:45:47 -07:00
Pavel Yaskevich
f94be56468 [Sema] Decouple ConstraintSystem and TypeChecker headers 2020-10-06 13:18:49 -07:00
Doug Gregor
b5759c9fd9 [Concurrency] Allow overload 'async' with non-async and disambiguate uses.
Allow an 'async' function to overload a non-'async' one, e.g.,

    func performOperation(_: String) throws -> String { ... }
    func performOperation(_: String) async throws -> String { ... }

Extend the scoring system in the type checker to penalize cases where
code in an asynchronous context (e.g., an `async` function or closure)
references an asychronous declaration or vice-versa, so that
asynchronous code prefers the 'async' functions and synchronous code
prefers the non-'async' functions. This allows the above overloading
to be a legitimate approach to introducing asynchronous functionality
to existing (blocking) APIs and letting code migrate over.
2020-09-08 16:51:10 -07:00
Slava Pestov
45fc0bc4db Sema: Replace some calls to getDeclaredType() with getDeclaredInterfaceType() 2020-07-31 13:39:02 -04:00
Doug Gregor
25d40125e9 [Trailing closures] Bias toward the backward scan for ambiguities.
This approach, suggested by Xiaodi Wu, provides better source
compatibility for existing Swift code, by breaking ties in favor of the
existing Swift semantics. Each time the backward-scan rule is needed
(and differs from the forward-scan result), we will produce a warning
+ Fix-It to prepare for Swift 6 where the backward rule can be
removed.
2020-07-24 08:47:51 -07:00
Doug Gregor
17669d7d5d [Trailing closures] Attempt both forward and backward scans.
To better preserve source compatibility, teach the constraint
solver to try both the new forward scanning rule as well as the
backward scanning rule when matching a single, unlabeled trailing
closure. In the extreme case, where the unlabeled trailing closure
matches different parameters with the different rules, and yet both
produce a potential match, introduce a disjunction to explore both
possibilities.

Prefer solutions that involve forward scans to those that involve
backward scans, so we only use the backward scan as a fallback.
2020-07-24 08:11:25 -07:00
Robert Widmann
afe8f2b63f Drop TypeCheckerDebugConsumer 2020-05-18 22:49:55 -07:00
Robert Widmann
2bca013457 Move "isDebugMode" into ConstraintSystem
This eliminates the final source of mutation of the TypeCheckerFlags on the ASTContext.
2020-05-13 09:13:44 -07:00
Pavel Yaskevich
326b371e10 [ConstraintSystem] Switch auxiliary functions to use ASTNode instead of TypedNode 2020-04-29 17:03:45 -07:00
Slava Pestov
742bd98402 Sema: Remove ConformanceCheckOptions::SkipConditionalRequirements
All callers can trivially be refactored to use ModuleDecl::lookupConformance()
instead. Since this was the last flag in ConformanceCheckOptions, we can remove
that, too.
2020-04-25 00:14:24 -04:00
Pavel Yaskevich
4b1aa29149 [ConstraintSystem] NFC: Adjust all uses of locator anchors to work with TypedNode 2020-04-23 01:13:13 -07:00
Robert Widmann
48a5432cb7 [NFC] Remove ConformanceCheckFlags::InExpression
The last read of this bit was removed when the legacy referenced name tracker was deleted in the last commit.
2020-04-20 10:22:58 -07:00
Robert Widmann
987cd55f50 [NFC] Drop llvm::Expected from Evaluation Points
A request is intended to be a pure function of its inputs. That function could, in theory, fail. In practice, there were basically no requests taking advantage of this ability - the few that were using it to explicitly detect cycles can just return reasonable defaults instead of forwarding the error on up the stack.

This is because cycles are checked by *the Evaluator*, and are unwound by the Evaluator.

Therefore, restore the idea that the evaluate functions are themselves pure, but keep the idea that *evaluation* of those requests may fail. This model enables the best of both worlds: we not only keep the evaluator flexible enough to handle future use cases like cancellation and diagnostic invalidation, but also request-based dependencies using the values computed at the evaluation points. These aforementioned use cases would use the llvm::Expected interface and the regular evaluation-point interface respectively.
2020-03-26 23:08:02 -07:00
Pavel Yaskevich
da2023c9a0 [ConstraintSystem] Score solutions based on number of holes
Introduce `SK_Hole` which is used to count a number of "holes" in
a given solution. It is used to distinguish solutions with fewer holes.

Also it makes it possible to check whether a solution has holes but
no fixes, which is an issue and such solution shouldn't be applied
to AST.
2020-03-24 16:51:44 -07:00
Hamish Knight
c74a7512f7 [CS] NFC: Remove OverloadChoiceKind::BaseType
This doesn't appear to be used any more.
2020-03-22 22:51:58 -07:00
Hamish Knight
39d988da9c [CS] Remove ReturnAllDiscoveredSolutions flag
This is now no longer used.
2020-03-02 14:50:16 -08:00
Pavel Yaskevich
288a7765fc [CSRanking] Detect cases where overload choices are incomparable
If constraint system is underconstrained e.g. because there are
editor placeholders, it's possible to end up with multiple solutions
where each ambiguous declaration is going to have its own overload kind:

```swift
func foo(_: Int) -> [Int] { ... }
func foo(_: Double) -> (result: String, count: Int) { ... }

_ = foo(<#arg#>).count
```

In this case solver would produce 2 solutions: one where `count`
is a property reference on `[Int]` and another one is tuple access
for a `count:` element.

Resolves: rdar://problem/49712598
2020-02-19 13:41:26 -08:00
Pavel Yaskevich
ad52afa4bb [ConstraintSystem] Add pair-wise differentiation of key path dynamic member overloads
Single type of keypath dynamic member lookup could refer to different
member overlaods, we have to do a pair-wise comparison in such cases
otherwise ranking would miss some viable information e.g.
`_ = arr[0..<3]` could refer to subscript through writable or read-only
key path and each of them could also pick overload which returns `Slice<T>`
or `ArraySlice<T>` (assuming that `arr` is something like `Box<[Int]>`).
2020-01-14 00:09:33 -08:00
Pavel Yaskevich
c3153e020d [CSRanking] Account for that fact that some bindings can be type holes 2020-01-14 00:09:33 -08:00
Pavel Yaskevich
22e12e86a8 [ConstraintSystem] Switch to pair-wise type binding differentiation for ranking
Instead of trying to hold a "global" set of type variable differences
let's use pair-wise comparison instead because in presence of generic
overloads such would be more precise.

If there are N solutions for a single generic overload we currently
relied on "local" comparison to detect the difference, but it's not
always possible to split the system to do one. Which means higher
level comparisons have to account for "local" (per overload choice)
differences as well otherwise ranking would loose precision.
2020-01-14 00:09:33 -08:00
Dan Zheng
1486d6b346 NFC: Add GenericSignature::getCanonicalSignature. (#29105)
Motivation: `GenericSignatureImpl::getCanonicalSignature` crashes for
`GenericSignature` with underlying `nullptr`. This led to verbose workarounds
when computing `CanGenericSignature` from `GenericSignature`.

Solution: `GenericSignature::getCanonicalSignature` is a wrapper around
`GenericSignatureImpl::getCanonicalSignature` that returns the canonical
signature, or `nullptr` if the underlying pointer is `nullptr`.

Rewrite all verbose workarounds using `GenericSignature::getCanonicalSignature`.
2020-01-12 12:17:41 -08:00
Robert Widmann
f4d333d066 Sink a bunch of semantic options into TypeCheckerOptions
Sink
- DebugConstraintSolver
- DebugConstraintSolverAttempt
- DebugConstraintSolverOnLines
- DebugGenericSignatures
- DebugForbidTypecheckPrefix
- SolverMemoryThreshold
- SolverBindingThreshold
- SolverShrinkUnsolvedThreshold
- SolverDisableShrink
- EnableOperatorDesignatedTypes
- DisableConstraintSolverPerformanceHacks
- SolverEnableOperatorDesignatedTypes
2019-11-12 22:39:49 -08:00
Doug Gregor
99555dc951 [Constraint system] Add ConstraintSystem::getExprDepth() and use it for cleanup.
Rather than passing around or create depth maps at a few places in the
constraint solver, introduce getExprDepth() and use it consistently.
2019-11-12 15:42:17 -08:00
Robert Widmann
b7d94e4b84 Drop TypeChecker out of some Code Completion utilities 2019-11-10 13:32:13 -08:00
Robert Widmann
7bad9aacc3 Drop the TypeChecker out of ConstraintSystem 2019-11-10 13:26:47 -08:00
Robert Widmann
1123b1f897 Move constraint satisfiability utilities 2019-11-10 13:12:50 -08:00
Robert Widmann
41ab235797 [CS] Remove some TypeChecker uses 2019-11-07 12:41:37 -08:00
Robert Widmann
2b08d1b834 [NFC] ASTContext::getLazyResolver -> ASTContext::getLegacyGlobalTypeChecker 2019-11-05 14:44:41 -08:00
Hamish Knight
e7fe2a7a48 Prevent non-ephemeral fix from affecting overload resolution
This commit changes the behaviour of the error for
passing a temporary pointer conversion to an
@_nonEphemeral parameter such that it doesn't
affect overload resolution. This is done by recording
the fix with an impact of zero, meaning that we don't
touch the solution's score.

In addition, this change means we no longer need
to perform the ranking hack where we favour
array-to-pointer, as the disjunction short-circuiting
will continue to happen even with the fix recorded.
2019-11-03 08:42:26 -08:00
Robert Widmann
3753a96d7c Add CompareDeclSpecializationRequest 2019-10-30 15:10:34 -07:00
Robert Widmann
abc6db13b1 Provide AST Context Getters To Protocol Inference 2019-10-30 12:55:42 -07:00
Robert Widmann
972e755e9b Give ConstraintSystem's outlet to the ASTContext
Make it less tempting to ask for the type checker embedded into
ConstraintSystem by using the accessor to the ASTContext.
2019-10-30 12:55:42 -07:00
Robert Widmann
4f84c2a628 Use the default constructor to clean up some APIs
Use ProtocolConformanceRef::forInvalid() in implementations only as a semantic signal.  In one place, use the default constructor to drop the final use of Optional<ProtocolConformanceRef>.
2019-10-29 16:56:22 -07:00
Robert Widmann
b849e51768 Use operator bool to claw back some readability 2019-10-29 16:56:21 -07:00
Robert Widmann
3e1a61f425 [NFC] Fold The Tri-State In Optional<ProtocolConformanceRef>
ProtocolConformanceRef already has an invalid state.  Drop all of the
uses of Optional<ProtocolConformanceRef> and just use
ProtocolConformanceRef::forInvalid() to represent it.  Mechanically
translate all of the callers and callsites to use this new
representation.
2019-10-29 16:55:56 -07:00
Robert Widmann
5a8d0744c3 [NFC] Adopt TypeBase-isms for GenericSignature
Structurally prevent a number of common anti-patterns involving generic
signatures by separating the interface into GenericSignature and the
implementation into GenericSignatureBase.  In particular, this allows
the comparison operators to be deleted which forces callers to
canonicalize the signature or ask to compare pointers explicitly.
2019-09-30 14:04:36 -07:00
Pavel Yaskevich
868afc6fc9 [CSRanking] Always rank key path dynamic member choices lower than non-dynamic ones
This only comes into play when all other choices are coming from
constrained extensions, because there is no way to determine upfront
whether any are going to match it's better to be safe and add
key path dynamic member choice to the set too.

Resolves: [SR-11465](https://bugs.swift.org/browse/SR-11465)
Resolves: rdar://problem/55314724
2019-09-12 14:03:57 -07:00
Slava Pestov
19d283d9dc AST: Replace ImplicitlyUnwrappedOptionalAttr with Decl::{is,set}ImplicitlyUnwrappedOptional() 2019-08-15 18:41:41 -04:00
gregomni
a2cd53d802 Handle simplification of optional-chaining key path literals, distinguish function type and keypath BGT type without explicit disjunctions. 2019-08-06 07:52:56 -07:00
Brent Royal-Gordon
6f4b0e5771 [ConstraintSolver] Favor keypaths over functions
Necessary to keep SE-0249 from failing tests.
2019-08-06 07:52:56 -07:00
Hamish Knight
a3ead02902 Merge remote-tracking branch 'upstream/master' into a-couple-of-tangents 2019-06-13 14:46:55 +01:00