Commit Graph

108 Commits

Author SHA1 Message Date
Arnold Schwaighofer
13ff5abdb8 Introduce @specialized attribute
Implements SE-0460 -- the non-underscored version of @specialized.

It allows to specify "internal" (not abi affecting) specializations.

rdar://150033316
2025-05-23 13:12:47 -07:00
Anthony Latsis
b6be6da277 ASTGen: Translate associated type declarations
Plus tweak `DefaultDefinitionTypeRequest` caching to support querying the
cached type when dumping. This fixes a crash where type computation is
triggered in the dumper before import resolution in `-dump-parse` mode.
2023-09-12 20:37:50 +03:00
Slava Pestov
6982b90c6e Serialization: Round-trip primary associated type list 2022-04-16 22:36:29 -04:00
Slava Pestov
7ee83a0c22 Serialization: Round-trip the RequirementMachine's ProtocolTypeAlias records 2022-02-13 00:24:23 -05:00
Nuri Amari
3762ca1fa7 Attach Lazy ClangImporter Diagnostics as Notes
Clang importer diagnostics that are produced as a result of a reference
in Swift code are attached to as notes to the Sema produced diagnostic
that indicates the declaration is unavailable.

Ex: Notes about why a C function import failed are attached to
the error explaining that the symbol could not be found in scope.
2022-01-29 14:32:42 -05:00
Nuri Amari
130f2de7fd Improve ClangImporter failure diagnostics
This patch introduces new diagnostics to the ClangImporter to help
explain why certain C, Objective-C or C++ declarations fail to import
into Swift. This patch includes new diagnostics for the following entities:

- C functions
- C struct fields
- Macros
- Objective-C properties
- Objective-C methods

In particular, notes are attached to indicate when any of the above
entities fail to import as a result of refering an incomplete (only
forward declared) type.

The new diangostics are hidden behind two new flags, -enable-experimental-clang-importer-diagnostics
and -enable-experimental-eager-clang-module-diagnostics. The first flag emits diagnostics lazily,
while the second eagerly imports all declarations visible from loaded Clang modules. The first
flag is intended for day to day swiftc use, the second for module linting or debugging the importer.
2022-01-02 12:43:59 -05:00
Slava Pestov
4e1c2b2e47 Serialization: Serialize the list of associated types in a protocol
This allows ProtocolDecl::getAssociatedTypeMembers() on a serialized
ProtocolDecl to avoid deserializing the full member list.
2021-07-31 00:25:22 -04:00
Arnold Schwaighofer
b994bf3191 Add support for _specialize(exported: true, ...)
This attribute allows to define a pre-specialized entry point of a
generic function in a library.

The following definition provides a pre-specialized entry point for
`genericFunc(_:)` for the parameter type `Int` that clients of the
library can call.

```
@_specialize(exported: true, where T == Int)
public func genericFunc<T>(_ t: T) { ... }
```

Pre-specializations of internal `@inlinable` functions are allowed.

```
@usableFromInline
internal struct GenericThing<T> {
  @_specialize(exported: true, where T == Int)
  @inlinable
  internal func genericMethod(_ t: T) {
  }
}
```

There is syntax to pre-specialize a method from a different module.

```
import ModuleDefiningGenericFunc

@_specialize(exported: true, target: genericFunc(_:), where T == Double)
func prespecialize_genericFunc(_ t: T) { fatalError("dont call") }

```

Specially marked extensions allow for pre-specialization of internal
methods accross module boundries (respecting `@inlinable` and
`@usableFromInline`).

```
import ModuleDefiningGenericThing
public struct Something {}

@_specializeExtension
extension GenericThing {
  @_specialize(exported: true, target: genericMethod(_:), where T == Something)
  func prespecialize_genericMethod(_ t: T) { fatalError("dont call") }
}
```

rdar://64993425
2020-10-12 09:19:29 -07:00
Robert Widmann
8f065e7a61 Delete TypeChecker::validateType
Inline it into its final user: swift::performTypeLocChecking
2020-06-10 19:33:58 -07:00
Dan Zheng
83f6714334 [AutoDiff] Start fixing SR-12526.
Start fixing SR-12526: `@derivative` attribute cross-module deserialization
crash. Remove original `AbstractFunctionDecl *` from `DerivativeAttr` and store
`DeclID` instead, mimicking `DynamicReplacementAttr`.
2020-04-06 06:37:23 -07:00
Robert Widmann
27b211c1f9 Lazy-load the eraser of @_typeEraser where possible
Type erasure requires a circular construction by its very nature:

@_typeEraser(AnyProto)
protocol Proto { /**/ }
public struct AnyProto : Proto {}

If we eagerly resolve AnyProto, the chain of resolution steps that
deserialization must make goes a little something like this:

Lookup(Proto)
    -> Deserialize(@_typeEraser(AnyProto))
    -> Lookup(AnyProto)
    -> DeserializeInheritedStuff(AnyProto)
    -> Lookup(Proto)

This cycle could be broken if the order of incremental inputs was
such that we had already cached the lookup of Proto.

Resolve this cycle in any case by suspending the deserialization of the
type eraser until the point it's demanded by adding
ResolveTypeEraserTypeRequest.

rdar://61270195
2020-04-03 14:52:21 -07:00
Slava Pestov
0b502d8c84 AST: loadNamedMembers() never fails
This allows us to simplify lookupDirect() a fair bit as well.
2020-02-12 18:32:46 -05:00
Robert Widmann
ac08fceacc Add loadDynamicallyReplacedFunctionDecl
To support lazy resolution of the cross-referenced function in a serialized @_dynamicReplacement(for: ...) attribute, add a utility to the LazyMemberLoader and plumb it through.  This is a more general utility than the current resolver, which relies on the type checker to strip the attribute off of VarDecls and fan it back out onto accessors, which means serialization has only ever seen AbstractFunctionDecls.
2019-12-03 15:28:19 -08:00
Robert Widmann
56a713f179 Remove LazyResolver! 2019-11-05 14:43:12 -08:00
Robert Widmann
01d272073a Requestify Witness Resolution
Witness matching is a source of a lot of ad-hoc cycles, and mixes the
logic that performs resolution, caching, validation, and cycle detection into one
place.  To make matters worse, some checkers kick off other checks in
order to cache work for further declarations, and access an internal
cache on their subject conformance for many requirements at once, or
sometimes just one requirement.

None of this fits into the request evaluator's central view of the
caching.  This is further evidenced by the fact that if you attempt to
move the caching step into the evaluator, it overcaches the same
witness and trips asserts.

As a start, define requests for the resolution steps, and flush some
hacks around forcing witness resolution. The caching logic is mostly
untouched (the requests don't actually cache anything), but some cycle
breaking is now handled in the evaluator itself.  Once witness matching
has been refactored to cache with the evaluator, all of these hacks can
go away.

My urge to destroy the LazyResolver outweighs the compromises here.
2019-11-05 13:28:07 -08:00
Robert Widmann
d4906ac10b Rationalize Implicit Member Synthesis Somewhat
Codable's deep magic currently forces conformance checks in the middle
of name lookup in order to inject CodingKeys into lookup results.  This
is compounded by the fact that this lookup fixup is occuring
incrementally, meaning depending on order of requirements being looked
up, Decl::getMembers() will give you a different answer.

Compounding this, NameLookup relied on the LazyResolver to formalize
this layering violation, and relied on implicit laziness to guard
against re-entrancy.

The approach is multi-pronged:
1) Shift the layering violation into the request evaluator
2) Spell out the kinds of resolution we support explicitly (make them
easier to find and kill)
3) Remove the LazyResolver entrypoint this was relying on
4) Split off the property wrappers part into its own utility
2019-11-05 09:10:13 -08:00
Robert Widmann
a29bfb4434 Fold resolveImplicitConstructors into resolveImplicitMember 2019-11-01 18:11:24 -07:00
Robert Widmann
464aab67ec Define InterfaceTypeRequest
The moment you've all been waiting for...

Define InterfaceTypeRequest and use it to, well, compute the interface
type.  This naturally widens the few cycles that we pick up with the
request evaluator.

There is still a lot of work to get done here, mostly around scaling
back all of the ad-hoc circularity checks around the interface type
computation.  It would also be great to improve the circularity
diagnostics.
2019-10-17 16:01:56 -07:00
Robert Widmann
ae60618f3b Remove resolveExtension and validateExtension
Push the relevant work this was doing down into the callers.  Most of them didn't want to validate the entire extension and force its generic parameters, they just wanted to validate the nominal type.

We must eagerly validate the generic signature of extensions, though.  This avoids a class of cycles where non-generic members of an extension with a generic signaure will call through to getGenericSignatureOfContext and force the generic signature anyways.  When this calls through to protocol witness matching, the signature can be recursively computed.
2019-09-20 22:22:49 -07:00
Slava Pestov
d395eb18ae AST: Remove LazyResolver::resolveProtocolEnvironment() 2019-09-20 17:59:56 -04:00
Slava Pestov
0405ab5ffc AST: GenericContexts store a GenericSignature instead of a GenericEnvironment
This eliminates the entire 'lazy generic environment' concept;
essentially, all generic environments are now lazy, and since
each signature has exactly one environment, their construction
no longer needs to be co-ordinated with deserialization.
2019-09-06 17:16:04 -04:00
Doug Gregor
11969847c4 Simplify lazy parsing of nominal and extension members.
Lazy parsing for the members of nominal types and extensions depends
only on information already present in
`IterableDeclContext`. Eliminate the use of PersistentParserState as
an intermediary and have the member-parsing request construct a new
`Parser` instance itself to handle parsing. Make this possible even
for ill-formed nominal types/extensions to simplify the code path.

Eliminate `LazyMemberParser` and all of its uses, because it was only
present for lazy member parsing, which no longer needs it.
2019-08-30 08:29:43 -07:00
Doug Gregor
d8f7c9e72c [Parser] Introduce a request for parsing type and extension members.
Ensure that lazy parsing of the members of nominal type definitions
and extensions is handled through a request. Most of the effort here
is in establishing a new request zone for parser requests.
2019-08-28 21:39:56 -07:00
Jordan Rose
cce8d2fde0 [Serialization] Deserialize protocol requirement signatures lazily
Always good to do less work, and it's a stepping stone towards
recovering from trying to deserialize a protocol with missing
requirements.
2019-06-27 14:52:47 -07:00
Slava Pestov
c9ea70efd0 Sema: Remove TypeChecker::markConformanceUsed() 2019-05-28 22:08:38 -04:00
Slava Pestov
18f216c581 Sema: Fix re-entrant call to ensureRequirementsAreSatisfied() when resolving associated conformances
ConformanceChecker::ensureRequirementsAreSatisfied() modifies the
conformance as it resolves each one of its associated conformances,
so a re-entrant call can end up corrupting state by adding too
many elements to the buffer, or adding elements at the wrong
offsets.

If TypeChecker::checkConformanceRequirements() was called before
ConformanceChecker::resolveTypeWitnesses(), we could re-entrantly call
ConformanceChecker::ensureRequirementsAreSatisfied():

TypeChecker::checkConformanceRequirements()
=> ConformanceChecker::ensureRequirementsAreSatisfied()
   => Type::subst(), etc
      => ConformanceChecker::resolveTypeWitnesses()
         => ConformanceChecker::ensureRequirementsAreSatisfied()

The code in SubstitutionMap::lookupConformance() worked around
this by checking the failure condition and calling
resolveTypeWitness() first, before calling getAssociatedConformance().

Instead, remove this and call resolveTypeWitness() from inside
NormalProtocolConformance::getAssociatedConformance().
2019-05-28 22:08:31 -04:00
Slava Pestov
fa12d85739 AST: Clean up associated type default representation a bit 2019-04-26 21:47:02 -04:00
Doug Gregor
6fd878c2b3 [Sema] Lazily fill in signature conformances as needed.
If the type checker doesn't prepopulate signature conformances, fill
them in when we first need them. This is a stopgap solution until we
can move these queries over to the request-evaluator.

Fixes rdar://problem/34584596, as well as a regression introduced by
the use of mangled names for associated conformances in witness tables.
2018-11-12 09:42:51 -08:00
Slava Pestov
7eed6c482b AST: Remove LazyResolver::bindExtension() 2018-09-19 09:47:36 -07:00
Xi Ge
a7a06d7ce3 FrontendTool: parse all delayed member decls when we're dumping parse tree or verifying parse diagnostics. 2018-09-12 19:40:28 -07:00
Xi Ge
033732b1e5 ASTVerifier: avoid verifying IterableDeclContext if it has unparsed members. 2018-09-12 14:11:41 -07:00
Xi Ge
24b0eac9a4 Parser: parse members in extension decls incrementally. 2018-09-05 17:00:39 -07:00
Doug Gregor
94951f431d [Lazy resolver] Remove resolveTrailingWhereClause().
This is completely subsumed by the “requirement” request.
Also remove some dead declarations in TypeChecker. NFC.
2018-08-23 09:28:33 -07:00
Doug Gregor
3499bf9d3a [Type checker] Eliminate the TypeChecker parameter from CompleteGenericTypeResolver. 2018-08-20 10:33:23 -07:00
Doug Gregor
064652693b Remove LazyResolver::resolveExtensionForConformanceConstruction().
This is no longer used. NFC
2018-08-13 19:03:35 -07:00
Doug Gregor
b70466dc63 [Type Checker] Add a request kind for computing 'ValueDecl::isObjC()'.
Still a WIP
2018-07-18 14:50:39 -07:00
Doug Gregor
8f23915334 [Type Checker] Introduce a request for “overridden declarations”.
Introduce a new request kind to capture the computation of the set of
overridden declarations of a given declaration, eliminating the
stateful “setOverriddenDecls()” calls from the type checker.
2018-07-18 14:50:38 -07:00
Slava Pestov
19de53f6cf Sema: Remove dead code from access level computation rework 2018-07-06 23:50:36 -07:00
Doug Gregor
5c6c2367c9 [Evaluator] Use the evaluator directly from AST entry points.
Rather than call through the LazyResolver (when available) to satisfy
queries that may require type checking, call into the evaluator
directly: it will make use of the type checker (via the lazy resolver)
when necessary. This change should allow us to use the
request-evaluator’s cache for state rather than mutable AST state,
as well as the ability to see requests that were evaluated after
type checking.
2018-06-29 16:11:29 -07:00
Slava Pestov
5f4f55caf8 AST: Add superclass field to ProtocolDecl 2018-06-28 15:19:20 -07:00
Doug Gregor
ebd774bcd1 [Sema] Eliminate the last use of the IterativeTypeChecker.
Implement TypeChecker::resolveInheritedProtocols() in terms of
"getInheritedType()" queries, instead.

[Sema] Put back resolveInheritedProtocols().

We're still depending on it to update state in some cases.
2018-06-14 15:29:57 -07:00
Doug Gregor
2b2e143f59 [Request-Evaluator] Introduce a request for getting an "inherited type". 2018-06-14 15:29:57 -07:00
Doug Gregor
99e540f588 [Evaluator] Add an “enum raw type” request and use it consistently.
Similar to get “superclass of class” request, introduce an “enum raw type”
request that is accessed via EnumDecl::getRawType().
2018-06-14 15:29:57 -07:00
Doug Gregor
ef337bb8ba [Evaluator] Use the request-evaluator for the superclass of a class.
Wire up the request-evaluator with an instance in ASTContext, and
introduce two request kinds: one to retrieve the superclass of a class
declaration, and one to compute the type of an entry in the
inheritance clause.

Teach ClassDecl::getSuperclass() to go through the request-evaluator,
centralizing the logic to compute and extract the superclass
type.

Fixes the crasher from rdar://problem/26498438.
2018-06-14 15:28:36 -07:00
Doug Gregor
bc0445d1f7 Narrow a few LazyResolver::resolveDeclSignature() calls to what they really need.
Specifically, introduce entrypoints for "resolve overridden decl" and "is @objc". These can
be computed cheaply in many more cases.
2018-06-04 18:15:39 -07:00
Doug Gregor
ef020c74aa Eliminate all vestiges of Substitution and SubstitutionList.
Introduced during the bring-up of the generics system in July, 2012,
Substitution (and SubstitutionList) has been completely superseded by
SubstitutionMap. R.I.P.
2018-05-11 21:43:40 -07:00
Huon Wilson
a23808f5d2 [AST] Introduce 'resolveExtensionForConformanceConstruction' for lazier conformance searching.
We need to be able to find which conformances need to be
declared/constructed without forcing extensions to be completely
validated. This is important for both SR-6569 and
rdar://problem/36499373. The former due to the source-level recursion,
and the latter because implied conformances weren't always
constructed (but are needed for good diagnostics).

They weren't always constructed because:

1. ConformanceLookupTable's updateLookupTable on an early stage (before
   implied conformances are found) triggers extension
   validation *before* constructing any conformances, but *after*
   updating the stage state
2. extension validation validates the conditional requirements
3. validating the conditional requirements requires setting up generic
   signatures
4. setting up generic signatures forces the types conformances and so
   ends up in updateLookupTable on the same nominal again, skipping over
   the earlier stages that are complete/in progress
5. we expand the conformances that are implied by all the conformances we
   know about... But we don't know any, because we haven't finished the
   first updateLookupTable.

This breaks the loop at step 2: we instead do the minimal work needed to
know what conformances an extension (might) declare, which is connect
the extension to a type, and then resolve the inherited TypeReprs to
Types.
2018-04-04 10:34:33 +10:00
Slava Pestov
46d416361e Sema: Remove TypoCorrectionResolver
With the previous changes, validating a property while
type checking its initializer is no longer a fatal error.

This means we don't have to do anything special when
validating typo correction candidates, so we can get rid
of the TypoCorrectionResolver. This means there is now
only one subclass of LazyResolver, the TypeChecker itself.
2018-04-03 14:39:30 -07:00
Doug Gregor
8c05278ef3 [Clang importer] Lazily load all named members with a matching base name.
When loading the named members for a given name, we want to load all
of the members with that base name... not only the ones that match the
full name, because the lookup table is indexed by base name and
filtering too early drops candidates.

Fixes rdar://problem/36085994.
2017-12-15 23:54:36 -08:00
Slava Pestov
422000a2f2 Sema: Remove isProtocolExtensionUsable()
It doesn't do anything that isExtensionApplied() doesn't do.
2017-12-12 21:12:46 -08:00