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().
After recent changes, this asserts on all decls that are not VarDecls,
so we can just enforce that statically now. Interestingly, this turns
up some dead code which would have asserted immediately if called.
Also, replace AnyFunctionRef::getType() with
AnyFunctionRef::getInterfaceType(), since the old
AnyFunctionRef::getType() would just assert when called on
a Decl.
Previously, getInterfaceType() would return getType() if no
interface type was set. Instead, always set an interface type
explicitly.
Eventually we want to remove getType() altogether, and this
brings us one step closer to this goal.
Note that ParamDecls are excempt from this treatment, because
they don't have a proper interface type yet. Cleaning this up
requires more effort.
My recent refactoring of witnesses in Sema and the AST disabled a
test for property behaviors, because they were no longer handling
substitutions correctly. Introduce a type checker entrypoint to record
information about a known witness, using the normal witness-matching
logic rather than trying to synthesize the correct answer (and getting
it wrong).
Note that I had to manually introduce some type witnesses to get the
property behavior tests passing, because the property-behavior code is
(intentionally) not introducing implicit typealiases for the type
witnesses it synthesized. The old witness-synthesizing code worked
around this issue, but the new code does not. A different fix is in
the works (i.e., better handling of type witnesses in the constraint
solver), so we'll take this temporary regression in an experimental
feature.
Reimplement the witness matching logic used for generic requirements
so that it properly models the expectations required of the witness,
then captures the results in the AST. The new approach has a number of
advantages over the existing hacks:
* The constraint solver no longer requires hacks to try to tangle
together the innermost archetypes from the requirement with the
outer archetypes of the context of the protocol
conformance. Instead, we create a synthetic set of archetypes that
describes the requirement as it should be matched against
witnesses. This eliminates the infamous 'SelfTypeVar' hack.
* The type checker no longer records substitutions involving a weird
mix of archetypes from different contexts (see above), so it's
actually plausible to reason about the substitutions of a witness. A
new `Witness` class contains the declaration, substitutions, and all
other information required to interpret the witness.
* SILGen now uses the substitution information for witnesses when
building witness thunks, rather than computing all of it from
scratch. ``substSelfTypeIntoProtocolRequirementType()` is now gone
(absorbed into the type checker, and improved from there), and the
witness-thunk emission code is simpler. A few other bits of SILGen
got simpler because the substitutions can now be trusted.
* Witness matching and thunk generation involving generic requirements
and nested generics now works, based on some work @slavapestov was
already doing in this area.
* The AST verifier can now verify the archetypes that occur in witness substitutions.
* Although it's not in this commit, the `Witness` structure is
suitable for complete (de-)serialization, unlike the weird mix of
archetypes previously present.
Fixes rdar://problem/24079818 and cleans up an area that's been messy
and poorly understood for a very, very long time.
Targeted fix for SR-2673: if a potential protocol witness is
@NSManaged, add accessors the NSManaged way, not the stored property
way.
There's probably more weirdness around here, so I'll clone the bug to
go through maybeAddAccessorsToVariable a lot more often. (Lazy
properties could easily be broken in the same way.)
While the use of a local property from within its own accessors is a
bit dubious, Swift 3 only warned on it, so model the existing lookup
behavior in the scope map.
SILType substitutions are still done with the old form, and until
BoundGenericTypes hold conformances, we still have to pass around
a ModuleDecl in a few places we really shouldn't, but one step
at a time.
Lazy property initializers can refer to 'self' either directly or
implicitly (via references to instance members). Model this in
ASTScope-based unqualified name lookup.
Note that the modeling of 'self' with the current name lookup
mechanism is broken, so when ASTScope-based unqualified name lookup is
enabled, it fixes SR-2203, rdar://problem/16954496, and the many dupes
of the latter.
This patch is rather large, since it was hard to make this change
incrementally, but most of the changes are mechanical.
Now that we have a lighter-weight data structure in the AST for mapping
interface types to archetypes and vice versa, use that in SIL instead of
a GenericParamList.
This means that when serializing a SILFunction body, we no longer need to
serialize references to archetypes from other modules.
Several methods used for forming substitutions can now be moved from
GenericParamList to GenericEnvironment.
Also, GenericParamList::cloneWithOuterParameters() and
GenericParamList::getEmpty() can now go away, since they were only used
when SILGen-ing witness thunks.
Finally, when printing generic parameters with identical names, the
SIL printer used to number them from highest depth to lowest, by
walking generic parameter lists starting with the innermost one.
Now, ambiguous generic parameters are numbered from lowest depth
to highest, by walking the generic signature, which means test
output in one of the SILGen tests has changed.
A GenericEnvironment stores the mapping between GenericTypeParamTypes
and context archetypes (or eventually, concrete types, once we allow
extensions to constrain a generic parameter to a concrete type).
The goals here are two-fold:
- Eliminate the GenericTypeParamDecl::getArchetype() method, and
always use mapTypeIntoContext() instead
- Replace SILFunction::ContextGenericParams with a GenericEnvironment
This patch adds the new data type as well as serializer and AST
verifier support. but nothing else uses it yet.
Note that GenericSignature::get() now asserts if there are no
generic parameters, instead of returning null. This requires a
few tweaks here and there.
This is the first, and most trivial, usage of the new
GenericSignature::getSubstitutions() method.
Note that getForwardingSubstitutions() now takes a
GenericSignature, which is slightly awkward.
However, this is in line with our goal of 'hollowing out'
GenericParamList by removing knowledge of the finalized
generic requirements.
Also, there is now a new getForwardingSubstitutionMap()
function, which returns an interface type substitution
mapping. This is used in the new getForwardingSubstitutions()
implementation, and all also be used elsewhere later.
Finally, in the SILFunction we now cache the forwarding
substitutions, instead of re-computing them every time.
I doubt this makes a big difference in performance, but
it's a simple enhancement and every little bit helps.
Factor out the trailing storage of call arguments, since we'll need it
for a few different kinds of expression nodes. Use it for both
CallExpr (which already had this storage, albeit with a specialized
implementation) and now SubscriptExpr.
Yet another step on the way to SE-0111, capture the argument labels
(and their locations) directly in CallExpr, rather than depending on
them being part of the tuple argument.
More detail: some members are intended to have the same the access as
their containing types. This doesn't fly for SE-0025 'private', which
would limit the members to only being accessed from lexically within
the type decl, instead anywhere the type itself can be seen. Instead,
follow the rule for user-written members---internal by default---and
then raise the access level to 'public' if necessary. This affects:
- enum cases
- deinitializers
- protocol requirements
- generic parameters
- implicit initializers
- inherited initializers
- derived conformance members
- synthesized typealiases for associated types
Introduce several new factory methods to create CallExprs, and hide
the constructor. The primary reason for this refactor is to start
moving clients over to the factory method that takes the call
arguments separately from the argument labels. Internally, it
repackages those arguments into a TupleExpr or ParenExpr (as
appropriate) so the result ASTs are the same. However, this will make
it easier for us to tease out the arguments themselves in the
implementation of SE-0111.
Start chipping away at cross-file type checker performance issues by
avoiding type checking of lazy property accessor bodies when the type in
question is defined in a different file and the lazy property is a typed
pattern.
We still type check these in the file they are defined in when we go to
type check the types defined within that file.
Resolves rdar://problem/26894118.
Previously getInterfaceType() would punt to getType() if no
interface type was set. This patch changes getInterfaceType()
to assert if no interface type is set, and updates various
places to set the interface type explicitly.
This brings us a step closer to removing PolymorphicFunctionType.
The code in recordTypeWitness() seemed to be completely bogus;
it already receives a type written in terms of the archetypes
of the adoptee's context, so mapTypeOutOfContext() did nothing
here, because it was using the wrong substitutions.
The logic for synthesizing designated initializers was also
slightly wrong if the class was nested inside a generic
function.
Finally, interface and contextual types of a derived rawValue
were flipped around.
Before we would construct types containing a mix of interface and
contextual types, and then map them in and out. Straighten this out.
Note that I've also had to start untangling the issue where
synthesized ParamDecls do not have an interface type.
In C++ we can't have nice things. The macro name 'defer' collided with
use of 'defer' in the Tokens.def file and we were already doing horrible
workarounds in a couple of places to allow them to be included into the
same file. So use a less awesome but more robust name (thanks to Joe for
suggesting SWIFT_DEFER).
Incidentally, sort a bunch of #inlcudes.
Consider this code:
struct A<T> {
struct B {}
struct C<U> {}
}
Previously:
- getDeclaredType() of 'A.B' would give 'A<T>.B'
- getDeclaredTypeInContext() of 'A.B' would give 'A<T>.B'
- getDeclaredType() of 'A.C' would give 'A<T>.C'
- getDeclaredTypeInContext() of 'A.C' would give 'A<T>.C<U>'
This was causing problems for nested generics. Now, with this change,
- getDeclaredType() of 'A.B' gives 'A.B' (*)
- getDeclaredTypeInContext() of 'A.B' gives 'A<T>.B'
- getDeclaredType() of 'A.C' gives 'A.C' (*)
- getDeclaredTypeInContext() of 'A.C' gives 'A<T>.C<U>'
(Differences marked with (*)).
Also, this change makes these accessors fully lazy. Previously,
only getDeclaredTypeInContext() and getDeclaredIterfaceType()
were lazy, whereas getDeclaredType() was built from validateDecl().
Fix a few spots where the return value wasn't being checked
properly.
These functions return ErrorType if a circularity was detected via
the generic parameter list, or if the extension did not resolve.
They return Type() if the extension cannot be resolved *yet*.
This is pretty subtle, and I'll need to do another pass over
callers of these functions at some point. Many of them should be
moved over to use getSelfInContext(), getSelfOfContext() and
getSelfInterfaceType() instead.
Finally, this patch consolidates logic for diagnosting invalid
nesting of types.
The parser had some code for protocols in bad places and bad things
inside protocols, and Sema had several different bail-outs for
bad things in protocols, nested generic types, and stuff nested
inside protocol extensions.
Combine all of these into a single set of checks in Sema. Note
that we no longer give up early if we find invalid nesting.
Leaving decls unvalidated and un-type-checked only leads to
further problems. Now that all the preliminary crap has been
fixed, we can go ahead and start validating these funny nested
decls, actually fixing some crashers in the process.
There was a weird corner case with nested generic functions that
would fail in the SIL verifier with some nonsense about archetypes
out of context.
Fix this the "right" way, by re-working Sema function declaration
validation to assign generic signatures in a more principled way.
Previously, nested functions did not get an interface type unless
they themselves had generic parameters.
This was inconsistent with methods nested inside generic types,
which did get an interface type even if they themselves did not
have a generic parameter list.
There's some spill-over in SILGen from this change. Mostly it
makes things more consistent and fixes some corner cases.
If the base class is in a different module and defines an internal
initializer, or it is in a different file and defines a private
initializer, the subclass cannot access this initializer.
Fix this by insisting on synthesizing initializers even if they
override an internal or private initializer in the base class.
In this case, synthesize them as a stub instead of a chaining
initializer. They cannot be called, and they cannot reference
the superclass initializer, so a stub is appropriate here.
Also in SILGen, emit vtable entries for stub initializers unless
they are overriding an Objective-C initializer.
Lookup can occasionally produce a call to a superclass constructor here that is not in our immediate superclass and we would trust it was completely valid. Instead, reject the notion of creating such a constructor entirely unless its decl can prove it is actually in our superclass.
Whenever we have a call, retrieve the argument labels from the
argument structurally and associate them with the callee. We were
previously doing this as a separate AST walk (which was unnecessary),
so fold that into constraint generation for a CallExpr. We were also
allowing weird ASTs to effectively disable this information: tighten
that up and require that CallExprs always have a ParenExpr, TupleExpr,
or (as a temporary hack) a TypeExpr whose representation is a
TupleTypeRepr as their argument prior to type checking. This gives us
a more sane AST to work with, and guarantees that we aren't losing
label information.
From the user perspective, this should be NFC, because it's mostly AST
cleanup and staging.
I originally added this so that we would keep the signature around
even if type checking failed, and the function was given an
ErrorType.
Add a formal check to the AST verifier for this, and set the signature
in a few places where it wasn't being set.
Note that since we only serialize valid declarations, we don't have
to serialize a reference to the generic signature separately, but we
do have to remember to set it when deserializing, which wasn't being
done for destructors.
The fix for methods to lower the dynamic method type from the substituted AST type of the expression also needed to be applied to the optional chaining, subscript, and property paths.
This also exposed a problem in the Clang importer, where imported subscript accessors would get the unbound generic context type as their Self parameter type instead of the type with the correct generic parameters. Fix this by renaming the all-too-convenient ParamDecl::createSelf factory to `createUnboundSelf`, and introduce a new `createSelf` that uses the bound generic type.
Fixes rdar://problem/26447758.
Initializers are inherited by synthesizing an implicit decl which
delegates to super.init(). Previously this was only done if the
class and superclass were concrete.
The only thing missing was that we weren't computing an interface
type for the synthesized constructor. There are two steps to this:
- First, we must map the contextual types of the superclass
initializer's ParamDecls to the subclass generic context.
- Second, we must set the interface type by calling the new
configureInterfaceType() method, extracted from from
validateGenericSignature().
Note that configureInterfaceType() now uses the new
AbstractFunctionDecl::hasThrows() flag to set the 'throws' bit on
the function type. Previously, validateGenericFuncSignature()
would look at getThrowsLoc().isValid(), which is not correct for
imported, implicitly-generated or de-serialized decls that 'throw',
because none of those have source location information.
We still don't allow inheriting initializers which have their
own generic parameter list, like 'init<T>(t: T) {...}'. That
requires a little bit more refactoring.
Progress on <rdar://problem/23376955>.
The verifier now asserts that Throws, ThrowsLoc and isBodyThrowing()
match up.
Also, add /*Label=*/ comments where necessary to make the long argument
lists easier to read, and cleaned up some inconsistent naming conventions.
I caught a case where ClangImporter where we were passing in a loc as
StaticLoc instead of FuncLoc, but probably this didn't affect anything.