Commit Graph

53 Commits

Author SHA1 Message Date
Slava Pestov
41df661160 AST: Use a builtin conformance for unconditional Copyable/Escapable
This generalizes what we were already doing for classes.
2024-03-07 15:07:47 -05:00
Slava Pestov
10a2ddb95e RequirementMachine: Fix MaxConcreteNesting check to take initial rules into account
Fixes rdar://123357717.
2024-03-06 21:42:49 -05:00
Slava Pestov
06b1aee360 Evaluator: Cache circular evaluation to avoid redundant diagnostics
Previously, if a request R evaluated itself N times, we would emit N
"circular reference" diagnostics. These add no value, so instead let's
cache the user-provided default value on the first circular evaluation.

This changes things slightly so that instead of returning an
llvm::Expected<Request::OutputType>, various evaluator methods take
a callback which can produce the default value.

The existing evaluateOrDefault() interface is unchanged, and a new
evaluateOrFatal() entry point replaces
llvm::cantFail(ctx.evaluator(...)).

Direct callers of the evaluator's operator() were updated to pass in
the callback. The benefit of the callback over evaluateOrDefault() is
that if the default value is expensive to constuct, like a dummy
generic signature, we will only construct it in the case where a
cycle actually happened, otherwise we just delete the callback.

(cherry picked from commit b8fcf1c709efa6cd28e1217bd0efe876f7c0d2b7)
2024-02-09 16:02:24 -08:00
Kavon Farvardin
9f3743dec0 NCGenerics: mark hanging tests as unsupported 2024-02-04 19:14:53 -08:00
Nishith Shah
8e2e625543 [Diagnostics] Use imperative msg for protocol conformance & switch-case fixits
This commit changes fixit messages from a question/suggestion to an
imperative message for protocol conformances and switch-case. Addresses
https://github.com/apple/swift/issues/67510.
2023-08-13 22:34:26 -07:00
Slava Pestov
0254c0ee7c RequirementMachine: Fix handling of unavailable Sendable conformances in concretizeNestedTypesFromConcreteParent()
We can't just ignore unavailable conformances because the
generic signature we're computing might itself be attached
to an unavailable declaration.

Until we get a proper fix, only drop unavailable conformances
to Sendable here.

Fixes rdar://problem/94305457.
2022-06-10 17:46:40 -04:00
Doug Gregor
c9c50b4ae0 [Requirement machine] Ignore unavailable conformances on superclass constraints.
When determining whether a superclass conforms to a particular protocol,
skip unavailable conformances. This way, we don't minimize away a
constraint that might only apply to subclasses of the specified
superclass.

Fixes rdar://91853658.
2022-05-27 13:09:15 -07:00
Slava Pestov
dac8d666ee Stop passing -requirement-machine-{abstract,inferred,protocol}-signatures flags in tests
These flags are now no-ops.
2022-05-10 12:56:17 -04:00
Slava Pestov
b4b873332f Update -requirement-machine-* flags in various tests
- Don't pass 'verify' since it's now the default
- Update tests where diagnostics changed in a correct way to pass 'on' instead
- Delete compiler_scale/explicit_requirements_perf.swift since it's not testing anything with the requirement machine
2022-03-31 15:57:36 -04:00
Slava Pestov
df49e112e3 RequirementMachine: Skip 'verify' check if completion failed
We obviously don't have a valid generic signature in this case.
2022-03-14 12:33:18 -04:00
Slava Pestov
6c714f4087 Sema: Try to avoid calling getGenericSignature() when performing structural resolution 2022-02-11 08:15:50 -05:00
Slava Pestov
f33eb17b75 GSB: Remove unsound cycle-breaking hack 2022-01-25 21:28:52 -05:00
Slava Pestov
4a019f0662 Sema: Improved recovery from circular generic signature construction
Returning a null GenericSignature is not the right way to break a cycle,
because then callers have to be careful to handle the case of a null
GenericSignature together with a non-null GenericParamList, for example
in applyGenericArguments().

An even worse problem can occur when a GenericSignatureRequest for a
nested generic declaration requests the signature of the parent context,
which hits a cycle. In this case, we would build a signature where
the first generic parameter did not have depth 0.

This makes the requirement machine upset, so this patch implements a new
strategy to break such cycles. Instead of returning a null
GenericSignature, we build a signature with the correct generic
parameters, but no requirements. The generic parameters can be computed
just by traversing GenericParamLists, which does not trigger more
GenericSignatureRequests, so this should be safe.
2021-09-04 00:13:03 -04:00
Slava Pestov
68957078c5 GSB: Set HadAnyError in two more places
If we don't set this flag, we can end up making an invalid GSB into
the canonical builder for some signature. This was caught by
requirement machine cross-checking on the compiler_crashers suite.
2021-07-12 23:52:49 -04:00
Pavel Yaskevich
ac8dfcf89b [CSGen] Replace getInterfaceType() -> mapTypeIntoContext() for VarDecl with getType
In `ConstraintGenerator::visitDeclRefExpr` instead of using
`getInterfaceType()` for unknown type and later mapping it into
context, let's use `getType()` which does that interally, that
allows to detect presence of error types in resulting type and
abort constraint generation.
2020-06-11 17:03:28 -07:00
Slava Pestov
653fa07260 GSB: Fix maybeResolveEquivalenceClass() with member type of superclass-constrained type
Name lookup might find an associated type whose protocol is not in our
conforms-to list, if we have a superclass constraint and the superclass
conforms to the associated type's protocol.

We used to return an unresolved type in this case, which would result in
the constraint getting delayed forever and dropped.

While playing wack-a-mole with regressing crashers, I had to do some
refactoring to get all the tests to pass. Unfortuanately these refactorings
don't lend themselves well to being peeled off into their own commits:

- maybeAddSameTypeRequirementForNestedType() was almost identical to
  concretizeNestedTypeFromConcreteParent(), except for superclasses
  instead of concrete same-type constraints. I merged them together.

- We used to drop same-type constraints where the subject type was an
  ErrorType, because maybeResolveEquivalenceClass() would return an
  unresolved type in this case.

  This violated some invariants around nested types of ArchetypeTypes,
  because now it was possible for a nested type of a concrete type to
  be non-concrete, if the type witness in the conformance was missing
  due to an error.

  Fix this by removing the ErrorType hack, and adjusting a couple of
  other places to handle ErrorTypes in order to avoid regressing with
  invalid code.

Fixes <rdar://problem/45216921>, <https://bugs.swift.org/browse/SR-8945>,
<https://bugs.swift.org/browse/SR-12744>.
2020-05-19 20:28:51 -04:00
Robert Widmann
5dc060ee57 Define ResolveTypeRequest 2020-04-30 16:10:25 -07:00
Robert Widmann
4f6951c42f Change a cycle condition
Not having the generic signature is the real culprit here.
2019-09-18 11:24:03 -07:00
Pavel Yaskevich
a1643d94f7 [Diagnostics] NFC: Update all of the improved test-cases 2019-09-13 22:35:52 -07:00
Pavel Yaskevich
253abad789 [Diagnostics] Port remaining contextual failures (expect associated with nil)
Remove the rest of the obsolete code from `diagnoseContextualConversionError`
and port diagnostic about string indexing to new diagnostic framework.
2019-08-13 14:33:38 -07:00
Slava Pestov
2d4b25960d Sema: Type variables for opened generic parameters store the generic parameter type and not an archetype
There's no need to instantiate archetypes in the generic environment
of the declaration being opened.

A couple of diagnostics changed. They were already misleading, and the
new diagnostics, while different, are not any more misleading than
before.
2018-09-27 20:49:23 -07:00
Doug Gregor
e67d78d919 Update test case for better recursion detection. 2018-08-20 23:59:30 -07:00
Doug Gregor
8d11ce1028 Minor test case update due to cycle detection. 2018-08-14 02:19:21 -07:00
Slava Pestov
3701f745c4 Migrate various Sema tests to Swift 4 2018-06-25 01:02:20 -07:00
Slava Pestov
5d2752f7d2 Run tests with -swift-version 4 by default
Some test now fail, so add an explicit -swift-version 3.
2018-06-19 23:24:19 -07:00
Doug Gregor
684a484d81 SR-5753: Don't warn about constraints redundant with inferred constraints. 2017-09-26 17:22:43 -07:00
Pavel Yaskevich
242006706e [QoI] Improve diagnostics of unsatisfied generic requirements
Fixes a problem related to presence of InOutType in function parameters
which diagnostics related to generic parameter requirements didn't handle
correctly, and improves diagnostics for unsatisfied generic requirements
in operator applications, which we didn't attempt to diagnose at all.

Resolves: rdar://problem/33477726
2017-07-27 15:06:12 -07:00
Doug Gregor
cf5424b617 [GSB] Move the Recursive(Concrete|Superclass)Type bits into EquivalenceClass.
Recursive concrete and superclass constraints are detected
per-equivalence-class; record them that way.

Use that information to drop recursive concrete and superclass
constraints from the resulting signature, which frees the canonical
generic signature builder from having to worry about such recursive
constraints. This eliminates the invalid-code crashes introduced in
the prior commit that disabled finalization for the canonical GSBs, as
well as fixing one other random crash-on-invalid.
2017-05-15 22:05:07 -07:00
Doug Gregor
8a4451dda9 [GSB] Infer requirements from concrete types in requirements.
When a requirement mentions a concrete type, that type might utter
other types (e.g., Set<T>) that infer requirements (here, T:
Hashable). Perform requirement inference for such types.

Part of rdar://problem/31520386.
2017-04-14 17:19:01 -07:00
Slava Pestov
ab74f6b143 AST: Simplify name lookup a little 2017-04-03 23:14:17 -07:00
Huon Wilson
e6dff39a2b [TypeCheck] Explicitly diagnose associatedtype AT = AT.
This warning used to be a consequence of some other warnings, but
changes to how validation work mean this is no longer true.
2017-02-24 19:21:33 -08:00
Doug Gregor
faf659d16b [Archetype builder] Make sure the archetype builder is always "finalized".
ArchetypeBuilder::finalize() is needed to tie up any loose ends before
requesting a generic signature or generic environment. Make sure it
gets called consistently.
2017-02-05 21:23:44 -08:00
Slava Pestov
4ed17f0f63 AST: Add a new 'isBeingValidated' flag to replace a couple of other flags
Previously, validateDecl() would check if the declaration had an
interface type and use that as an indication not to proceed.

However for functions we can only set an interface type after
checking the generic signature, so a recursive call to validateDecl()
on a function would "steal" the outer call and complete validation.

For generic types, this meant we could have a declaration with a
valid interface type but no generic signature.

Both cases were problematic, so narrow workarounds were put in
place with additional new flags. This made the code harder to
reason about.

This patch consolidates the flags and establishes new invariants:

- If validateDecl() returns and the declaration has no interface
  type and the isBeingValidated() flag is not set, it means one
  of the parent contexts is being validated by an outer recursive
  call.

- If validateDecl() returns and the declaration has the
  isBeingValidated() flag set, it may or may not have an interface
  type. In this case, the declaration itself is being validated
  by an outer recursive call.

- If validateDecl() returns and the declaration has an interface
  type and the isBeingValidated() flag is not set, it means the
  declaration and all of its parent contexts are fully validated
  and ready for use.

In general, we still want name lookup to find things that have an
interface type but are not in a valid generic context, so for this
reason nominal types and associated types get an interface type as
early as possible.

Most other code only wants to see fully formed decls, so a new
hasValidSignature() method returns true iff the interface type is
set and the isBeingValidated() flag is not set.

For example, while resolving a type, we can resolve an unqualified
reference to a nominal type without a valid signature. However, when
applying generic parameters, the hasValidSignature() flag is used
to ensure we error out instead of crashing if the generic signature
has not yet been formed.
2016-12-19 01:38:23 -08:00
Slava Pestov
e063e8297c Sema: Some fixes for the ITC
- In functions called from resolveType(), consistently
  use a Type() return value to indicate 'unsatisfied
  dependency', and ErrorType to indicate failure.

- Plumb the unsatisfiedDependency callback through the
  resolution of the arguments of BoundGenericTypes, and
  also pass down the options.

- Before doing a conformance check on the argument of a
  BoundGenericType, kick off a TypeCheckSuperclass request
  if the type in question is a class. This ensures we don't
  recurse through NominalTypeDecl::prepareConformanceTable(),
  which wants to see a class with a valid superclass.

- The ResolveTypeOfDecl request was assuming that
  the request was satisfied after calling validateDecl().
  This is not the case when the ITC is invoked from a
  recursive call to validateDecl(), hack this up by returning
  *true* from isResolveTypeDeclSatisfied(); otherwise we
  assert in satisfy(), and we can't make forward progress
  in this case anyway.

- Fix a bug in cycle breaking; it seems if we don't invoke
  the cycle break callback on all pending requests, we end
  up looping forever in an outer call to satisfy().

- Remove unused TR_GlobalTypeAlias option.
2016-12-09 17:36:49 -08:00
Doug Gregor
00a7981e05 [Type checker] Eliminate one "pass" in generic environment validation.
We no longer need a separate "pass" that creates an archetype builder
that inherits context archetypes, because we no longer ever inherit
context archetypes.
2016-12-07 14:27:49 -08:00
Slava Pestov
6f49557530 Sema: Gut finalizeGenericParamList()
This function did three things:

- In debug builds, record an association between the newly-created
  context archetypes and the current DeclContext.

- Set the accessibility of the GenericTypeParamDecls as appropriate.

- Re-check the types written in the GenericParamList.

The last step was not needed, because we no longer serialize
GenericParamLists, or care if the RequirementRepr contains valid
types at all. The other two have been moved elsewhere.
2016-12-04 00:03:12 -08:00
Slava Pestov
1a991da16d AST: Assign interface types to ParamDecls
First, ensure all ParamDecls that are synthesized from scratch are given
both a contextual type and an interface type.

For ParamDecls written in source, add a new recordParamType() method to
GenericTypeResolver. This calls setType() or setInterfaceType() as
appropriate.

Interestingly enough a handful of diagnostics in the test suite have
improved. I'm not sure why, but I'll take it.

The ParamDecl::createUnboundSelf() method is now only used in the parser,
and no longer sets the type of the self parameter to the unbound generic
type. This was wrong anyway, since the type was always being overwritten.
This allows us to remove DeclContext::getSelfTypeOfContext().

Also, ensure that FuncDecl::getBodyResultTypeLoc() always has an interface
type for synthesized declarations, eliminating a mapTypeOutOfContext()
call when computing the function interface type in configureInterfaceType().

Finally, clean up the logic for resolving the DynamicSelfType. We now
get the interface or contextual type of 'Self' via the resolver, instead
of always getting the contextual type and patching it up inside
configureInterfaceType().
2016-12-04 00:02:21 -08:00
Slava Pestov
2ff9994313 Sema: Improve circularity checks
The previous patches regressed a test where we used to diagnose
(poorly) a circular associated type, like so:

  associatedtype e: e

With the error "inheritance from non-protocol, non-class type 'e'".

This error went away, because we end up not setting the interface
type of the associated type early enough. Instead, we return an
ErrorType from resolveTypeInContext() and diagnose nothing.

With this patch, emit a diagnostic at the point where the ErrorType
first appears.

Also, remove the isRecursive() bit from AssociatedTypeDecl, and
remove isBeingTypeChecked() which duplicates a bit with the same
name in Decl.
2016-12-01 13:00:19 -08:00
David Farler
b7d17b25ba Rename -parse flag to -typecheck
A parse-only option is needed for parse performance tracking and the
current option also includes semantic analysis.
2016-11-28 10:50:55 -08:00
Slava Pestov
8bf32c5280 AST: Better checks for same-type constraints making generic parameters concrete
The old logic missed some cases where this could come up.
2016-10-04 20:01:39 -04:00
Slava Pestov
9771ec84dd Sema: Improve checking of associated type superclass constraints
When checking a conformance of a concrete type to a protocol, we
effectively checked the associated types twice -- once when
deriving them, and another time at the end, where we performed
a substitution of the protocol 'Self' type to the concrete type.

The latter checked superclass constraints, while the former did not.

However, this trick no longer works with minimized generic
signatures, because <P : Self> no longer has redundant requirements
for the associated types of 'P'.

Instead, check superclass constraints at the same time as checking
conformances.
2016-09-06 11:51:14 -07:00
Robert Widmann
4f465224ea Polish off uses of dynamicType in tests 2016-07-29 16:59:14 -07:00
David Farler
7bfaeb57f1 [SE-0081] Warn on deprecated where clause inside angle brackets
and provide a fix-it to move it to the new location as referenced
in SE-0081.

Fix up a few stray places in the standard library that is still using
the old syntax.

Update any ./test files that aren't expecting the new warning/fix-it
in -verify mode.

While investigating what I thought was a new crash due to this new
diagnostic, I discovered two sources of quite a few compiler crashers
related to unterminated generic parameter lists, where the right
angle bracket source location was getting unconditionally set to
the current token, even though it wasn't actually a '>'.
2016-07-26 01:41:10 -07:00
Slava Pestov
528a4a547c Sema: Clean up some code duplication when validating generic type signatures
Every call to validateGenericTypeSignature() had the same
boilerplate following; move the common logic into that
function.

As one might expect, each callsite had slight variants on
the same underlying logic -- this makes them consistent.

Also, this slightly widens the scope during which
GenericTypeDecl::isValidatingGenericSignature() returns
true.

Interesting, that change introduces a diagnostic in an
existing testcase where previously there was none:

protocol P {
  associatedtype T
}

struct S<A: P where A.T == S<A>> {}

While it looks like this generic signature was built
correctly, in fact I think we weren't computing
conformances for the substitution of 'A' in 'S<A>'.

After trying small variations on the above testcase,
I quickly ran into SILGen crashes, which the diagnostic
now prevents. A few interesting cases still crash.
See test/decl/protocol/req/recursion.swift for the
gory details.
2016-06-18 17:05:27 -07:00
Doug Gregor
38c1de69e4 Reinstate "[SR-511][Parse] Add 'associatedtype' keyword and fixit"
This reverts commit ce7b2bcf09, tweaking
a few validation tests appropriately (1 crasher fixed, two -verify
tests that needed updating).
2016-01-14 00:21:48 -08:00
Erik Eckstein
ce7b2bcf09 Revert "[SR-511][Parse] Add 'associatedtype' keyword and fixit"
This reverts commit 2b2e9dc80e.

It broke some compiler crasher tests
2016-01-13 20:42:58 -08:00
gregomni
2b2e9dc80e [SR-511][Parse] Add 'associatedtype' keyword and fixit
Adds an associatedtype keyword to the parser tokens, and accepts either
typealias or associatedtype to create an AssociatedTypeDecl, warning
that the former is deprecated. The ASTPrinter now emits associatedtype
for AssociatedTypeDecls.

Separated AssociatedType from TypeAlias as two different kinds of
CodeCompletionDeclKinds. This part probably doesn’t turn out to be
absolutely necessary currently, but it is nice cleanup from formerly
specifically glomming the two together.

And then many, many changes to tests. The actual new tests for the fixits
is at the end of Generics/associated_types.swift.
2016-01-13 17:54:31 -08:00
Slava Pestov
c258f991f6 Sema: Nuke NominalTypeDecl::markInvalidGenericSignature()
This would just set the NominalTypeDecl's declared type to
ErrorType, which caused problems elsewhere.

Instead, generalize the logic used for AbstractFunctionDecl.
This correctly wires up the GenericTypeParamDecl's archetypes even
if the signature didn't validate, fixing crashes if the generic
parameters of the type are referenced.
2015-12-14 13:29:55 -08:00
Robert Widmann
11cce3bcdc Diagnose circular type aliases in protocol declarations 2015-12-05 16:05:15 -05:00
Doug Gregor
6af6048c0c AST printing: take more care to only escape 'Self' when needed.
Cleans up AST printing somewhat as well as providing slightly better
type-to-declaration mappings for annotated AST printing and indexing.

Swift SVN r32420
2015-10-03 05:13:52 +00:00