Commit Graph

844 Commits

Author SHA1 Message Date
Doug Gregor
5d0d8d97ae [Constraint solver] Capture/roll back type mappings generated while solving.
When we perform constraint generation while solving, capture the
type mappings we generate as part of the solver scope and solutions,
rolling them back and replaying them as necessary. Otherwise, we’ll
end up with uses of stale type variables, expression/parameter/type-loc
types set twice, etc.

Fixes rdar://problem/50390449 and rdar://problem/50150314.
2019-06-11 17:34:45 -07:00
Doug Gregor
a4301cc95b [Type checker] Transform multi-statement closures via function builders.
When calling a function whose parameter specifies a function builder
with a multi-statement closure argument, transform the closure into
a single expression via the function builder. Should the result
type checker, replace the closure body with the single expression.
2019-06-11 17:34:44 -07:00
Slava Pestov
c84aad8bf1 Sema: TypeChecker::conformsToProtocol() is static 2019-06-11 02:47:32 -07:00
Saleem Abdulrasool
731c31f9a5 MSVC: litter the code with llvm_unreachable (NFC)
Add `llvm_unreachable` to mark covered switches which MSVC does not
analyze correctly and believes that there exists a path through the
function without a return value.
2019-06-01 19:02:46 -07:00
Hamish Knight
8aa7401ba5 [Sema] Add getDeclOrNull to OverloadChoice
This helps clean up a bunch of call sites.
2019-05-16 12:07:41 +01:00
Doug Gregor
5aea1315cd Add @_disfavoredOverload attribute to affect overload resolution.
Introduce an attribute @_disfavoredOverload that can be used to state
that a particular declaration should be avoided if there is a
successful type-check for a non-@_disfavoredOverload. It's a way to
nudge overload resolution away from particular solutions.
2019-05-14 23:07:26 -07:00
Gwen Mittertreiner
e51b72b3e0 Reduce the Stack Size of ConstraintSystem
The ConstraintSystem class is on the order of 1000s of bytes in size on
the stacka nd is causing issues with dispatch's 64k stack limit.

This changes most Small data types which store data on the stack to non
small heap based data types.
2019-05-13 11:40:43 -07:00
Nate Chandler
f9400be21b Create opaque type constraint for single expr return. [49581931]
Previously, an OpaqueUnderlyingType constraint was created only if the
contextual type purpose was CTP_ReturnStmt.  Now that there is a
distinct CTP for implicit, single-expression returns, an
OpaqueUnderlyingType constraint needs to be created if that is the CTP.
2019-04-25 08:52:46 -07:00
Nate Chandler
b2ad56223f Eliminated conversion from uninhabited. 2019-04-24 10:09:17 -07:00
Pavel Yaskevich
ca6cf0c022 [ConstraintSystem] Use special locator for expr representing return of single expr function 2019-04-24 10:06:44 -07:00
Nate Chandler
0143ce25c2 Implicitly convert single exprs from uninhabited.
When type-checking a return statement's result, pass a new
ContextualTypePurpose when that return statement appears in a function
with a single expression.  When solving the corresponding constraint
system, the conversion constraint will have a new ConstraintKind.  When
matching types, check whether the constraint kind is this new kind,
meaning that the constraint is between a function's single expression
and the function's result.  If it is, allow a conversion from
an uninhabited type (the expression's type) to anything (the function's
result type) by adding an uninhabited upcast restriction to the vector
of conversions.  Finally, at coercion time, upon encountering this
restriction, call coerceUninhabited, replacing the original expression
with an UninhabitedUpcastExpr.  Finally, at SILGen time, treat this
UninhabitedUpcastExpr as a ForcedCheckedCastExpr.

Eliminates the bare ConstraintSystem usage from
typeCheckFunctionBodyUntil, ensuring that the same code path is followed
for all function bodies.
2019-04-24 10:04:17 -07:00
Brent Royal-Gordon
814d50c7e6 Merge pull request #24163 from brentdax/line-line-line-line
Add -debug-constraints-on-line flag
2019-04-22 16:54:00 -07:00
Brent Royal-Gordon
79cee8daad Add -debug-constraints-on-line flag 2019-04-22 13:59:50 -07:00
Joe Groff
a8c2b50bd8 Merge pull request #22072 from jckarter/opaque-type-runtime
Opaque types with resilience
2019-04-18 14:52:31 -07:00
Joe Groff
f008019bda Sema: Infer the underlying type for opaque return types from function bodies. 2019-04-17 14:43:32 -07:00
Brent Royal-Gordon
817a44bb95 [ConstraintSolver] Centralize dumping an expr
There are two places where we can dump an expr with types from the constraint solver. There should only be one.
2019-04-17 14:32:16 -07:00
Slava Pestov
eed84abda9 Sema: Add TVO_CanBindToNoEscape
We have a systemic class of issues where noescape types end up bound to
type variables in places that should not. The existing diagnostic for
this is ad-hoc and duplicated in several places but it doesn't actually
address the root cause of the problem.

For now, I've changed all call sites of createTypeVariable() to set the
new flag. I plan on removing enough occurrences of the flag to replicate
the old diagnostics. Then we can continue to refine this over time.
2019-04-16 23:01:33 -04:00
Pavel Yaskevich
2e8d163655 [ConstraintSystem] Special case keypath dynamic member lookup in disjunction filtering
Since filtering currently runs as part of the `applicable function`
constraint processing, "keypath dynamic member lookup" choice can't
be attempted in-place because that would also try to operate on that
constraint, so instead let's keep the disjunction, but disable all
unviable choices.

Resolves: rdar://problem/49533404
2019-04-03 12:23:23 -07:00
Pavel Yaskevich
d4bbcc1953 [TypeChecker] Add subscript support keypath dynamic member lookup 2019-04-01 12:40:39 -07:00
Pavel Yaskevich
9eed0135fa [CSSolver] Don't generate implicit argument for keypath dynamic lookup
Implicit argument expression was necessary to generate keypath
constraint which is used to validate a choice picked for the member.
But since read-only check has been factored out it's now possible
to validate choice directly in combination with new 'keypath dynamic lookup'
locator associated with member type variable which represents result
of the dynamic lookup.
2019-04-01 12:40:39 -07:00
Pavel Yaskevich
cde23eccc8 [ConstraintSystem] Implement keypath dynamic member lookup
Implement keypath based dynamic member lookup which augments
functionality of existing @dynamicMemberLookup attribute.

Two new subscript overloads are accepted:

```
subscript(dynamicMember member: KeyPath<T, ...>) -> ...
subscript(dynamicmember member: WritableKeyPath<T, ...>) -> ...
```

Example:

```swift
struct Point {
  let x: Int
  var y: Int
}

@dynamicMemberLookup struct Lens<T> {
  var obj: T

  init(_ obj: T) {
    self.obj = obj
  }

  subscript<U>(dynamicMember member: KeyPath<T, U>) -> Lens<U> {
    get { return Lens<U>(obj[keyPath: member]) }
  }

  subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> {
    get { return Lens<U>(obj[keyPath: member]) }
    set { obj[keyPath: member] = newValue.obj }
  }
}

var lens = Lens(Point(x: 0, y: 0))

_ = lens.x // converted into `lens[dynamicMember: KeyPath<Point, Int>`
_ = lens.y = Lens(10) // converted into `lens[dynamicMember: WritableKeyPath<Point, Int>]`
```
2019-04-01 12:40:39 -07:00
Pavel Yaskevich
8b5396bbac [CSSolver] Attempt disabled disjunction choices only if they have a fix
This draws a distinction between disabled choices with and without
fixes - former is disabled because it's unrelated, latter because
it only makes sense to attempt it during "salvage" mode while trying
to produce diagnostics.
2019-03-14 13:18:42 -07:00
Doug Gregor
15ac48cd4b Improve a comment regarding an constraint-favoring hack. 2019-03-05 21:59:51 -08:00
Doug Gregor
1d6cb4f28f [Constraint solver] Remove unused ConstraintSystem::getUnboundBindOverloads() 2019-03-05 21:40:48 -08:00
Doug Gregor
b83bb70bac [Constraint solver] Look through optional binding for overload sets.
When we’re trying to find the overload set corresponding to a particular
type variable, look through “optional object of” constraints that represent
the use of ? binding or ! forcing. This allows us to find overload sets
when referring to, e.g., @objc optional protocol requirements.
2019-03-05 21:40:48 -08:00
Doug Gregor
fd50d945ce [Constraint system] Move SIMD operator partitioning into disjunction partitioning
Continuing along my path to move application-independent partitioning
rules into the common disjunction partitioning code.
2019-03-05 15:01:46 -08:00
Doug Gregor
b993c6e076 [Constraint solver] Move tryOptimizeGenericDisjunction() into partitioning
This narrow favoring rule makes more sense as part of disjunction
partitioning, because it is not dependent on the use site at all and
should only kick in when other options fail.
2019-03-05 15:01:46 -08:00
Doug Gregor
d2c7c8d5ee [Constraint solver] Enable favoring of disjunction constraints during solving
Allow constraints to be favored during solving, and unwound after exiting
that particular solver scope. We're not using this yet.
2019-03-05 10:30:51 -08:00
Doug Gregor
0f31416d96 [Constraint solver] Always partition disjunctions when solving.
The disjunction partitioning logic was only used for the experimental
designated-types feature, but is generally useful. Unify the code
paths so we always do the partitioning, with only the designated-types
part being enabled/disabled by the flag.
2019-03-04 19:49:58 -08:00
Doug Gregor
233cf6ffa6 [Constraint solver] Address feedback from Pavel and Slava. 2019-03-01 20:54:48 -08:00
Doug Gregor
bdc961d8c6 [Constraint solver] Do argument label matching during apply simplification.
When simplifying a function application constraint, check the argument
labels for that application against the disjunction containing the overload
set, disabling any overloads with mis-matching labels. This is staging for
several different directions:

* Eliminating the argument label matching from performMemberLookup, where it
does not belong
* More aggressively filtering the overload set when we have some concrete
information about argument types
* Identifying favored constraints when we have some concrete information
about argument types

At present, the only easily-visible effect of this change is that
we now properly handle argument label matching for non-member functions.
2019-02-28 23:53:08 -08:00
Doug Gregor
5f99d91ea8 [Constraint solver] Compute common apply result type in the solver.
Constraint generation for function application expressions contains a simple
hack to try to find the common result type for an overload set containing
callable things. Instead, perform this “common result type” computation
when simplifying an applicable function constraint, so it is more
widely applicable.
2019-02-27 23:30:03 -08:00
Pavel Yaskevich
0b29d9d4e6 [ConstraintSystem] Decouple designated types feature from Swift version
`selectApplyDisjunction` only makes sense in conjunction with
designated types feature because it's going to prioritize disjunctions
with arguments which are known to conform to literal protocols.

Prioritization like that is harmful without designated types feature
because it doesn't always lead to better constraint system splits,
and could prioritize bigger disjunctions which harms chances to
short-circuit solving.

Resolves: rdar://problem/47492691
2019-01-31 11:48:35 -08:00
Pavel Yaskevich
e604261805 [ConstraintSystem] Track AST depth information directly
Instead of storing information about expression depths in the
solver state (which gets recomputed for salvage) let's track
it directly in constraint system, which also gives solver
access to it when needed e.g. for fixes.
2019-01-23 18:44:53 -08:00
Pavel Yaskevich
e26fc1efff [ConstraintSystem] Skip literal protocols without default types from minimalization
After collecting possible conformances and types for each argument,
`ArgumentInfoCollector` attempts literal protocol minimalization
to reduce the set of possible types argument could assume. Let's
exclude literal protocols without default types like
`ExpressibleByNilLiteral` from consideration by that algorithm.

Resolves: rdar://problem/47266563
2019-01-16 00:35:17 -08:00
Pavel Yaskevich
60fb2bf94e [CSFix] Try to fix missing member by defining it based on use
If lookup couldn't find anything matching given name, let's try to
fake its presence based on how member is being used. This is going
to help (potentially) type-check whole expression and diagnose the
problem precisely.
2019-01-09 14:35:27 -08:00
Pavel Yaskevich
35202ab5b0 [TypeChecker] Always emit a fallback error if type-check failed without producing one
Sometimes constraint solver fails without producing any diagnostics,
it could happen during different phases e.g. pre-check, constraint
generation, or even while attempting to apply solution. Such behavior
leads to crashes down the line in AST Verifier or SILGen which are
hard to diagnose.

Let's guard against that by tracking if solver produced any diagnostics
upon its failure and if no errors were or are scheduled to be produced,
let's produce a fallback fatal error pointing at affected expression.

Resolves: rdar://problem/38885760
2019-01-07 10:42:00 -08:00
Pavel Yaskevich
637692ccf8 [ConstraintSystem] NFC: Define {activate, deactivate}Constraint to make that logic reusable 2018-12-18 10:24:11 -08:00
Mark Lacey
10ef7347a7 [ConstraintSystem] Better handling of operators with multiple designated types.
For operators with multiple designated types, we attempt to decide the
best order for exploring the types. We were doing this by checking
for matching types. Extend this to also consider conforming types.

Fixes: rdar://problem/46687985
2018-12-14 13:24:23 -08:00
Mark Lacey
e713cbd516 [ConstraintSystem] With designated types enabled, use fewer partitions.
In 119864a0f5 I moved the consideration
of top-level operators sooner when the designated types feature is
enabled, and that fixed some source compatibility issues that show up
in our test suite, but also introduced a new one.

For maximum source compatibility we'll just split the partitions up
into the operators from designated types, followed by operators that
are not deprecated or disabled, followed by the deprecated ones, and
finally the disabled ones.
2018-12-13 15:18:20 -08:00
Mark Lacey
119864a0f5 [ConstraintSystem] Attempt global operators earlier.
When -Xfrontend -solver-enable-operator-designated-types is enabled,
attempt operators defined outside of types before attempting operators
defined within (non-designated) types.

This helps fix some source compatability problems that arise from
attempting some of the operators defined for Optional (e.g. we
would sometimes typecheck successfully with the operator for Optional
and then inject values into Optionals and skip attempting
globally defined operators that also match).

The old behavior resulted in failures in SourceKit and SIL Optimizer
tests when enabling designated types by default in our test suite.
2018-12-11 20:48:09 -08:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08:00
Mark Lacey
4d76d308c9 [ConstraintSystem] Move checkTypeOfBinding into CSBindings.cpp.
This is the only place that it's actually used from.
2018-11-29 21:00:32 -08:00
Mark Lacey
a1be08230f [ConstraintSystem] Enable disjunction ordering change when use of designated types are enabled.
We try to work more-or-less bottom up in the expression when we
attempt apply disjunctions first. This is very helpful to get good
results with designated types enabled in the solver. Rather than
forcing tests to specify both `-swift-version 5` (which also enables
this bottom-up behavior) and enabling designated types, allow them to
just enable the later to get the behavior.

We'll eventually have to revisit this when we decide the specific
conditions that we'll enable the use of designated types under.
2018-11-16 22:01:04 -08:00
Mark Lacey
d7cf830842 [ConstraintSystem] Add Array as a designated type for + and +=.
Also add overloads for these operators to an extension of Array.

This allows us to typecheck array concatenation quickly with
designated type support enabled and the remaining type checker hacks
disabled.
2018-11-15 21:42:33 -08:00
Dan Zheng
2a4e1b83fd Implement @dynamicCallable. (#20305)
* Implement dynamically callable types (`@dynamicCallable`).

- Implement dynamically callable types as proposed in SE-0216.
  - Dynamic calls are resolved based on call-site syntax.
  - Use the `withArguments:` method if it's defined and there are no
    keyword arguments.
  - Otherwise, use the `withKeywordArguments:` method.
- Support multiple `dynamicallyCall` methods.
  - This enables two scenarios:
    - Overloaded `dynamicallyCall` methods on a single
      `@dynamicCallable` type.
    - Multiple `dynamicallyCall` methods from a `@dynamicCallable`
      superclass or from `@dynamicCallable` protocols.
  - Add `DynamicCallableApplicableFunction` constraint. This, used with
    an overload set, is necessary to support multiple `dynamicallyCall`
    methods.
2018-11-09 09:49:14 -08:00
Slava Pestov
564695d9bf AST: Remove DeclContext::isExtensionContext()
It's identical in every way to isa<ExtensionDecl>(), so
make code less confusing by only having one way of doing
that check.
2018-11-07 17:34:56 -05:00
Mark Lacey
ffcbe70e90 [ConstraintSystem] Fix crash due to not all literal protocols having default types. 2018-11-07 13:04:59 -08:00
Jordan Rose
dc3ff6c22b Merge pull request #19985 from vinivendra/ast-dump-cleanup
Cleans up calls to print/dump for the AST Dumper
2018-10-24 15:22:41 -07:00
Greg Titus
d20fdf5f82 Merge pull request #19920 from gregomni/8757
[Sema][QoI] Call out missing conformances in protocol witness candidates.
2018-10-22 16:39:51 -07:00