Commit Graph

2410 Commits

Author SHA1 Message Date
Anthony Latsis
24c19d4ad4 Sema: Enable covariant erasure for dependent member types 2022-02-02 02:10:05 +03:00
Anthony Latsis
b3ee4b0718 AST, Sema: Use the opened archetype's generic signature to determine existential member availability 2022-02-02 02:09:59 +03:00
Pavel Yaskevich
48ffeddbc7 [CSApply] Result coercion check should always use resolved type
`shouldCoerceToContextualType` used `solution.getType(ASTNode)`
which returns a type that has type variables in it. To properly
check whether result type needs a coercion it has to be resolved
first which is done via `solution.getResultType(ASTNode)`.

Resolves: rdar://88285682
2022-01-31 14:42:27 -08:00
Slava Pestov
e7e536705e AST: Introduce ParametrizedProtocolType 2022-01-26 00:11:38 -05:00
Holly Borla
76e6156857 [Sema] Construct OpenedArchetypeType with a canonical existential type.
Opened archetypes can be created in the constraint system, and the
existential type it wraps can contain type variables. This can happen
when the existential type is inferred through a typealias inside a
generic type, and a member reference whose base is the opened existential
gets bound before binding the generic arguments of the parent type.

However, simplifying opened archetypes to replace type variables is
not yet supported, which leads to type variables escaping the constraint
system. We can support cases where the underlying existential type doesn't
depend on the type variables by canonicalizing it when opening the
existential. Cases where the underlying type requires resolved generic
arguments are still unsupported for now.
2022-01-19 22:53:52 -08:00
Doug Gregor
452eccab83 Remove NestedArchetypeType.
Nested archetypes are represented by their base archetype kinds (primary,
opened, or opaque type) with an interface type that is a nested type,
as represented by a DependentMemberType. This provides a more uniform
representation of archetypes throughout the frontend.
2022-01-14 21:28:21 -08:00
Holly Borla
d971d489d6 [Type System] With explicit existential types, make sure existential
metatypes always wrap the constraint type directly, and the instance
type of an existential metatype is an existential type.
2022-01-13 19:30:44 -08:00
Evan Wilde
89af8c9d24 Removing unused ctx variable
Cleaning up build warning for unused ctx variable in CSApply.cpp.
2022-01-11 09:16:09 -08:00
Doug Gregor
7a37ad3105 Ensure that we set opaque type substitutions on local variables.
We were never setting these opaque type substitutions, but code
generation was silently failing. Now we assert, so move the code into
the proper common location so we always set opaque type substitutions
on properties.

Fixes rdar://86800325.
2022-01-10 15:32:42 -08:00
Pavel Yaskevich
9f7d3fccad Merge pull request #40708 from xedin/disable-multi-stmt-inference-inside-result-builder-bodies
[ConstraintSystem] SE-0326: Temporarily prevent multi-statement closure inference in result builder contexts
2022-01-06 01:04:22 -08:00
Doug Gregor
b97ef02d85 Opaque opaque types and compute substitutions in the constraint system
Opaque opaque types and record them within the "opened types" of the
constraint system, then use that information to compute the set of
substitutions needed for the opaque type declaration using the normal
mechanism of the constraint solver. Record these substitutions within
the underlying-to-opaque conversion.

Use the recorded substitutions in the underlying-to-opaque conversion
to set the underlying substitutions for the opaque type declaration
itself, rather than reconstructing the substitutions in an ad hoc manner
that does not account for structural opaque result types.
2021-12-26 20:33:58 -08:00
Pavel Yaskevich
bbdbb47b25 [CSApply] Switch delayed closure processing to use participatesInInference
Instead of checking the frontend flag directly, let's use dedicated
method on a constraint system to determine whether closure did
participate in inference or not.
2021-12-25 17:08:58 -08:00
Robert Widmann
d44d8ec043 Allow Converting Pack Types to Tuples
Insert an implicit conversion from pack types to tuples with equivalent parallel structure. That means

1) The tuple must have the same arity
2) The tuple may not have any argument labels
3) The tuple may not have any variadic or inout components
4) The tuple must have the same element types as the pack
2021-12-16 08:51:38 -08:00
Robert Widmann
0471e2c58e Implement Type Sequence Parameter Opening
The heart of this patchset: An inference scheme for variadic generic functions and associated pack expansions.

A traditional variadic function looks like

func foo<T>(_ xs: T...) {}

Along with the corresponding function type

<T>(T [variadic]) -> Void

which the constraint system only has to resolve one two for. Hence it opens <T> as a type variable and uses each argument to the function to try to solve for <T>. This approach cannot work for variadic generics as each argument would try to bind to the same <T> and the constraint system would lose coherency in the one case we need it: when the arguments all have different types.

Instead, notice when we encounter expansion types:

func print<T...>(_ xs: T...)
print("Macs say Hello in", 42, "different languages")

We open this type as

print : ($t0...) -> ($t0...)

Now for the brand new stuff: We need to create and bind a pack to $t0, which will trigger the expansion we need for CSApply to see a coherent view of the world. This means we need to examine the argument list and construct the pack type <$t1, $t2, $t3, ...> - one type variable per argument - and bind it to $t0. There's also the catch that each argument that references the opened type $t0 needs to have the same parallel structure, including its arity. The algorithm is thus:

For input type F<... ($t0...), ..., ($tn..) ...> and an apply site F(a0, ..., an) we walk the type `F` and record an entry in a mapping for each opened variadic generic parameter. Now, for each argument ai in (a0, ..., an), we create a fresh type variable corresponding to the argument ai, and record an additional entry in the parameter pack type elements corresponding to that argument.

Concretely, suppose we have

func print2<T..., U...>(first: T..., second: U...) {}
print2(first: "", 42, (), second: [42])

We open print2 as

print2 : ($t0..., $t1...) -> Void

And construct a mapping

  $t0 => <$t2, $t3, $t4> // eventually <String, Int, Void>
  $t1 => <$t5> // eventually [Int]

We then yield the entries of this map back to the solver, which constructs bind constraints where each => exists in the diagram above. The pack type thus is immediately substituted into the corresponding pack expansion type which produces a fully-expanded pack type of the correct arity that the solver can actually use to make forward progress.

Applying the solution is as simple as pulling out the pack type and coercing arguments element-wise into a pack expression.
2021-12-16 01:16:45 -08:00
Robert Widmann
8ac8633f9d [NFC] Hide VarargExpansionExpr's Constructor 2021-12-16 01:16:45 -08:00
Holly Borla
69be7b17fc Merge pull request #40282 from hborla/existential-any
[SE-0335] Introduce existential `any`
2021-12-10 08:56:03 -08:00
Holly Borla
445a856652 [Type System] Introduce a dedicated type to represent existential types.
The new type, called ExistentialType, is not yet used in type resolution.
Later, existential types written with `any` will resolve to this type, and
bare protocol names will resolve to this type depending on context.
2021-12-09 23:14:50 -08:00
Richard Wei
05363cd55a Regex literal runtime plumbing.
- Frontend: Implicitly import `_StringProcessing` when frontend flag `-enable-experimental-string-processing` is set.
- Type checker: Set a regex literal expression's type as `_StringProcessing.Regex<(Substring, DynamicCaptures)>`. `(Substring, DynamicCaptures)` is a temporary `Match` type that will help get us to an end-to-end working system. This will be replaced by actual type inference based a regex's pattern in a follow-up patch (soon).
- SILGen: Lower a regex literal expression to a call to `_StringProcessing.Regex.init(_regexString:)`.
- String processing runtime: Add `Regex`, `DynamicCaptures` (matching actual APIs in apple/swift-experimental-string-processing), and `Regex(_regexString:)`.

Upcoming:
- Build `_MatchingEngine` and `_StringProcessing` modules with sources from apple/swift-experimental-string-processing.
- Replace `DynamicCaptures` with inferred capture types.
2021-12-09 16:05:34 -08:00
Hamish Knight
37f16520e6 Prototype regex literal AST and emission
With `-enable-experimental-string-processing`,
start lexing `'` delimiters as regex literals (this
is just a placeholder delimiter for now). The
contents of which gets passed to the libswift
library, which can return an error string to be
emitted, or null for success.

The libswift side isn't yet hooked up to the Swift
regex parser, so for now just emit a dummy
diagnostic for regexes starting with quantifiers.

If successful, build an AST node which will be
emitted as an implicit call to an
`init(_regexString:)` initializer of an in-scope
`Regex` decl (which will eventually be a known
stdlib decl).
2021-12-06 21:16:14 +00:00
Pavel Yaskevich
0e6e058e7c [TypeChecker] Fix constraint solver to respect LeaveClosureBodyUnchecked flag 2021-12-03 10:54:07 -08:00
swift-ci
1b6ec37b06 Merge pull request #40363 from zoecarver/fix-mangler-leaks 2021-12-01 21:04:39 -08:00
zoecarver
3bb9d43ead [nfc] Fix two leaks where clang::ManglerContext was not cleaned up. 2021-12-01 17:13:24 -08:00
Pavel Yaskevich
bc54bc6bb7 Revert "[TypeChecker] SE-0326: Enable multi-statement closure inference by default" 2021-11-29 17:26:08 -08:00
Robert Widmann
1faf7edbd6 Merge pull request #40193 from CodaFi/sequential-access-patterns
Model Sequence Archetypes
2021-11-17 13:19:31 -08:00
Pavel Yaskevich
63f355fde0 Merge pull request #39989 from xedin/more-diag-improvements-for-multi-stmt-closures
[TypeChecker] SE-0326: Enable multi-statement closure inference by default
2021-11-17 10:14:58 -08:00
Robert Widmann
e7e11df927 Model Sequence Archetypes 2021-11-16 11:38:57 -08:00
Hamish Knight
551604a456 Merge pull request #40183 from hamishknight/the-path-less-traveled 2021-11-16 14:14:53 +00:00
Pavel Yaskevich
83033198c3 [TypeChecker] Fix constraint solver to respect LeaveClosureBodyUnchecked flag 2021-11-15 16:42:05 -08:00
Hamish Knight
76c6254779 [AST] Refactor KeyPathExpr constructors
Now that the CSApply just uses components, we can
better split up the key path constructors to either
accept a set of resolved components, or a parsed
root or path.
2021-11-15 12:25:18 +00:00
Hamish Knight
d6ac93efb1 [CS] Don't set parsed paths for dynamic member key paths
The logic here could form AST loops due to passing
in `anchor` for the key path's parsed path.

However setting a parsed path here seems to be a
holdover from the CSDiag days, so set the path to
`nullptr` and rip out and the rest of the synthesis
and SanitizeExpr logic for it.

rdar://85236369
2021-11-15 12:25:17 +00:00
Hamish Knight
15098e22bd [AST] Rename resolveComponents -> setComponents
The naming here has bothered me for a little while
now, it just sets the components, it doesn't
resolve anything.
2021-11-15 12:25:17 +00:00
Pavel Yaskevich
fc0f05f416 [TypeChecker] Implement distributed thunk identification in expr rewritter
This logic cannot live in `ActorIsolationChecker` because
all of the relevant information is only accessible through
constraint system while applying solutions.
2021-11-12 21:15:59 -08:00
Pavel Yaskevich
115af99031 [CSApply] Mark call to distributed thunks as implicitly throwing
Use newly added `isDistributedThunk` check to determine whether
the given call is to a remote distributed actor and if so mark
it as implicitly throwing.

Resolves: rdar://83610106
2021-11-12 12:41:30 -08:00
Pavel Yaskevich
0b4ec1c31e [ConstraintSystem] Add accessor to check whether target represents async let init 2021-11-12 12:41:29 -08:00
Robert Widmann
658de80ca8 Merge pull request #39627 from CodaFi/the-replacements
Suggest Replacement Types for Invalid Placeholders
2021-11-10 16:23:29 -08:00
Pavel Yaskevich
0c70f5650f Merge pull request #39592 from Jumhyn/contextual-placeholder-followup
Remove default argument from getContextualType
2021-11-08 10:00:36 -08:00
Robert Widmann
1fe2e4b3e7 Relax Restrictions on Placeholder Types Appearing in Interface Types
These restrictions are meant to keep placeholder types from escaping TypeCheckType. But there's really no harm in that happening as long as we diagnose it on the way out in the places it's banned. (We also need to make sure we're only diagnosing things in primaries, but that's a minor issue). The end result is that we lose information because a lot of the AST that has placeholders in it becomes filled with error types instead.

Lift the restriction on placeholders appearing in the interface type, teach the mangler to treat them as unresolved types, and teach serialization to treat them as error types.
2021-11-03 10:29:15 -07:00
Doug Gregor
3945ce0b1b Remove now-unused "unsafe sendable" and "unsafe main actor" closure bits. 2021-10-19 23:01:07 -07:00
Doug Gregor
1b8f562852 Adjust the referenced function type for @_unsafeSendable and @_unsafeMainActor.
When referencing a function that contains parameters with the hidden
`@_unsafeSendable` or `@_unsafeMainActor` attributes, adjust the
function type to make the types of those parameters `@Sendable` or
`@MainActor`, respectively, based on both the context the expression:

* `@Sendable` will be applied when we are in a context with strict
concurrency checking.
* `@MainActor` will be applied when we are in a context with strict
concurrency checking *or* the function is being directly applied so
that an argument is provided in the immediate expression.

The second part of the rule of `@MainActor` reflects the fact that
making the parameter `@MainActor` doesn't break existing code (because
there is a conversion to add a global actor to a function value), but
it does enable such code to synchronously use a `@MainActor`-qualified
API.

The main effect of this change is that, in a strict concurrency
context, the type of referencing an unapplied function involving
`@_unsafeSendable` or `@_unsafeMainActor` in a strict context will
make those parameters `@Sendable` or `@MainActor`, which ensures that
these constraints properly work with non-closure arguments. The former
solution only applied to closure literals, which left some holes in
Sendable checking.

Fixes rdar://77753021.
2021-10-19 22:50:17 -07:00
Hamish Knight
287fa8e8de [CS] Refactor IUO handling
The current IUO design always forms a disjunction
at the overload reference, for both:

- An IUO property `T!`, forming `$T := T? or T`
- An IUO-returning function `() -> T!`, forming `$T := () -> T? or () -> T`

This is simple in concept, however it's suboptimal
for the latter case of IUO-returning functions for
a couple of reasons:

- The arguments cannot be matched independently of
  the disjunction
- There's some awkwardness when it comes e.g wrapping
  the overload type in an outer layer of optionality
  such as `(() -> T!)?`:
  - The binding logic has to "adjust" the correct
    reference type after forming the disjunction.
  - The applicable fn solving logic needs a special
    case to handle such functions.
- The CSApply logic needs various hacks such as
  ImplicitlyUnwrappedFunctionConversionExpr to
  make up for the fact that there's no function
  conversion for IUO functions, we can only force
  unwrap the function result.
  - This lead to various crashes in cases where
    we we'd fail to detect the expr and peephole
    the force unwrap.
  - This also lead to crashes where the solver
    would have a different view of the world than
    CSApply, as the former would consider an
    unwrapped IUO function to be of type `() -> T`
    whereas CSApply would correctly see the overload
    as being of type `() -> T?`.

To remedy these issues, IUO-returning functions no
longer have their disjunction formed at the overload
reference. Instead, a disjunction is formed when
matching result types for the applicable fn
constraint, using the callee locator to determine
if there's an IUO return to consider. CSApply then
consults the callee locator when finishing up
applies, and inserts the force unwraps as needed,
eliminating ImplicitlyUnwrappedFunctionConversionExpr.

This means that now all IUO disjunctions are of the
form `$T := T? or T`. This will hopefully allow a
further refactoring away from using disjunctions
and instead using type variable binding logic to
apply the correct unwrapping.

Fixes SR-10492.
2021-10-12 14:14:33 +01:00
Pavel Yaskevich
87f41a9b21 [CSClosure] Check multi-statement closure attrs only in if inference is enabled 2021-10-08 12:12:44 -07:00
Pavel Yaskevich
90876134f2 [CSApply] Set types for for all delayed closures 2021-10-08 10:08:03 -07:00
Pavel Yaskevich
8867a8d407 [CSApply] Delay solution application to multi-statement closure bodies
Let's delay solution application to multi-statement closure bodies,
because declarations found in the body of such closures may depend
on its `ExtInfo` flags e.g. no-escape is set based on parameter if
closure is used in a call.
2021-10-08 10:08:03 -07:00
Pavel Yaskevich
d5e9a39f65 [CSApply] Mark pattern target as fully verified 2021-10-08 10:08:03 -07:00
Pavel Yaskevich
e3aa37700e [ConstraintSystem] Allow default initialized patterns
Add support for pattern bindings with default initializable patterns
e.g. `let x: Int?`.
2021-10-08 10:08:03 -07:00
Pavel Yaskevich
99a9828a03 [ConstraintSystem] Add a new contextual purpose - CTP_CaseStmt 2021-10-08 10:08:02 -07:00
Pavel Yaskevich
7197fac8f5 [ConstraintSystem] Add a new contextual purpose - CTP_ForEachSequence
A contextual purpose for a sequence expression associated with
`for-in` statement, that decays into a `ConformsTo` constraint
to a `Sequence` or `AsyncSequence` protocol.

Note that CTP_ForEachSequence is almost identical to CTP_ForEachStmt
but the meaning of latter is overloaded, so to avoid breaking solution
targets I have decided to add a new purpose for now.
2021-10-08 10:08:02 -07:00
swift-ci
b69eac9630 Merge pull request #39535 from guitard0g/tparam-not-used-in-fsig 2021-10-06 18:06:29 -07:00
Pavel Yaskevich
1c0a306c75 Merge pull request #37956 from xedin/implicit-swift-to-c-ptr-conversions
[TypeChecker] Implement limited set of conversions between Swift and C pointers
2021-10-06 14:35:22 -07:00
Josh Learn
f433ac2d58 Allow importing templated functions when template args do not appear
in the function signature by adding explicit metatype parameters to
the function signature.
2021-10-06 13:35:12 -07:00