Commit Graph

155 Commits

Author SHA1 Message Date
Mark Lacey
d80cefc154 Do not type check lazy accessor bodies eagerly.
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.
2016-07-06 20:14:05 -07:00
Slava Pestov
68dc9455e7 Sema: Remove redundant mapType{Into,OutOf}Context() calls
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.
2016-07-02 05:39:12 -07:00
Slava Pestov
584eda38ed ClangImporter: More principled use of mapType{Into,OutOf}Context()
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.
2016-07-02 05:36:35 -07:00
Slava Pestov
68c6b1a14b Sema: Minor cleanups, NFC 2016-07-02 05:35:15 -07:00
Ben Langmuir
ea848aeaae Rename C++ macro 'defer' -> 'SWIFT_DEFER'
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.
2016-06-29 14:57:58 -07:00
Slava Pestov
7814c47b71 AST: Slightly change meaning of NominalTypeDecl::getDeclaredType()
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.
2016-06-18 17:15:24 -07:00
Slava Pestov
9ddccaddfc Sema: Move diagnostic for stored properties in protocols from type checking to validation
Otherwise, we might try to do a conformance check on a stored
property requirement, and crash because there is no getter.
2016-06-18 17:05:28 -07:00
Slava Pestov
bbefeb2fc5 Sema: Better support for nested generic functions
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.
2016-06-13 01:22:43 -07:00
Slava Pestov
3620aee91c Sema: Fix for derived classes where the base class has inaccessible initializers
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.
2016-06-06 17:28:55 -06:00
Robert Widmann
8f3031d7b9 Provide a fix for SR-1571 (#2854)
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.
2016-06-03 18:00:08 -07:00
Doug Gregor
ee85891d11 Revert "[Type checker] Be more rigorous about extracting argument labels from calls."
This reverts commit 3753d779bc. It's
causing some type-inference problems I need to investigate.
2016-06-03 10:21:27 -07:00
Doug Gregor
3753d779bc [Type checker] Be more rigorous about extracting argument labels from calls.
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.
2016-06-02 17:15:51 -07:00
Slava Pestov
112511cd1c Remember to set AbstractFunctionDecl's generic signature in a few places
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.
2016-05-28 22:30:40 -07:00
Joe Groff
5e2b20d05f SILGen: Fix crashes when conditionally looking up generic subscripts and properties via AnyObject.
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.
2016-05-24 19:18:37 -07:00
Slava Pestov
0ff0f3c5b9 Sema: Generic classes and subclasses of generic classes now inherit required initializers
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>.
2016-05-21 12:51:51 -07:00
Slava Pestov
170992c39f AST: Add Throws flag and ThrowsLoc to AbstractFunctionDecl
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.
2016-05-21 12:51:50 -07:00
Alex Hoppen
d2e045c8b5 Implement SE-0064 / SR-1239: #selector for property getters and setters
Implements the core functionality of SE-0064 / SR-1239, which
introduces support for accessing the Objective-C selectors of the
getter and setter of an @objc property via #selector(getter:
propertyName) and #selector(setter: propertyName).

Introduce a bunch of QoI around mistakes using #selector to refer to a
property without the "getter:" or "setter:", using Fix-Its to help the
user get it right. There is more to do in this area, still, but we
have an end-to-end feature working.

Much of the implementation and nearly all of the test cases are from
Alex Hoppen (@ahoppen). I've done a bit of refactoring, simplified the
AST representation, and replaced Alex's custom
expression-to-declaration logic with an extension to the constraint
solver. The last bit might be short-lived, based on swift-evolution
PR280, which narrows the syntax of #selector considerably.
2016-05-11 16:51:27 -07:00
Doug Gregor
32aef82571 [Sema] Infer @objc and Objective-C name from conformance to a protocol.
When a particular method/initializer/property/subscript is used to
satisfied a requirement in an @objc protocol, infer both the presence
of @objc and the @objc name so that it matches the requirement. This
eliminates the need to explicitly specify @objc and @objc(foo:bar:) in
most cases. Note that we already did this for overrides, so it's a
generalization of that behavior.

Note that we keep this inference somewhat local, checking only those
protocols that the enclosing context conforms to, to limit
spooky-action-at-a-distance inference. It's possible that we could
lift this restriction later.

Fixes rdar://problem/24049773.
2016-04-28 22:04:18 -07:00
Slava Pestov
e7f0ca0ebf Sema: Synthesize materializeForSet for lazy properties
Fixes <rdar://problem/25707968>.
2016-04-13 20:07:37 -07:00
practicalswift
c760f6dfbf [gardening] Add whitespace: "foo,bar" → "foo, bar" 2016-04-12 22:31:46 +02:00
Doug Gregor
5374081c41 Propagate @objc attribute when inheriting designated initializers. 2016-04-07 13:18:41 -07:00
Joe Groff
88847f177a Sema: Set the interface type of lazy properties during validation.
Otherwise, we end up treating the contextual type as the interface type in situations where the lazy property is seen from other files. Fixes SR-837.
2016-04-04 13:16:10 -07:00
Slava Pestov
bc1fc73b2a Sema: Simpler materializeForSet return type, NFC
The function pointer is a thin function and possibly polymorphic,
so it does not really have an AST type. Instead of pretending it has
an AST type, just return a RawPointer and remove some casts in the
process.
2016-03-14 13:01:03 -07:00
Slava Pestov
a64431418b SILGen: Emit materializeForSet in more cases
Recently I changed Sema to always emit materializeForSet for properties
of structs, to fix issues with duplicate or missing symbols when the
type declaration and conformance are in different translation units.

The same issue can happen with properties of final classes and enums,
so let's simplify the logic by always emitting a materializeForSet
when possible.

The new multifile demonstrate the problem.
2016-03-14 13:01:03 -07:00
Max Moiseev
859db53d87 Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-03-01 12:56:26 -08:00
Joe Groff
e94fcace3f Sema: Infrastructure for DI-style initialization through behaviors.
Allow a behavior protocol to declare an `initStorage` implementation with a parameter. If we have an initializer expression, use `initStorage(initExpr)` to initialize the storage; otherwise, remember the storage declaration and its initializer. Definite
initialization will have to use these to insert the initialization operation for the behavior property at the right place.
2016-03-01 11:51:25 -08:00
Joe Groff
a4fa786a6f Handle a parameter to property behaviors.
For prototyping purposes, we only support a single trailing closure parameter to begin with.
2016-03-01 11:51:25 -08:00
Max Moiseev
a49dab6bf8 Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-29 12:08:52 -08:00
Andrew Trick
ff02652108 Move enums into AttrKind.h.
This reorganization allows adding attributes that refer to types.
I need this for a @_specialize attribute with a type list.

PrintOptions.h and other headers depend on these enums. But Attr.h
defines a lot of classes that almost never need to be included.
2016-02-26 21:10:22 -08:00
Max Moiseev
fcad164e18 Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-22 12:59:57 -08:00
Joe Groff
c6bfac7281 Handle initial value requirements in property behaviors.
If a behavior protocol requires an `initialValue` static property, satisfy the requirement using the initial value expression from the property declaration. This lets us implement `lazy` as a property behavior.
2016-02-22 08:43:17 -08:00
Joe Groff
e49a50bbee Sema: Fix crash when behavior protocol is missing initStorage requirement.
Would be nice to have `guard` in C++...
2016-02-20 15:01:06 -08:00
Joe Groff
a1ef412815 Sema/SILGen: Get property behavior implementations to codegen.
Fix some interface type/context type confusion in the AST synthesis from the previous patch, add a unique private mangling for behavior protocol conformances, and set up SILGen to emit the conformances when property declarations with behaviors are visited. Disable synthesis of the struct memberwise initializer if any instance properties use behaviors; codegen will need to be redesigned here.
2016-02-20 15:01:06 -08:00
Joe Groff
26e55ce465 Sema: Initial parsing and synthesis for properties with behaviors.
Parse 'var [behavior] x: T', and when we see it, try to instantiate the property's
implementation in terms of the given behavior. To start out, behaviors are modeled
as protocols. If the protocol follows this pattern:

  ```
  protocol behavior {
    associatedtype Value
  }
  extension behavior {
    var value: Value { ... }
  }
  ```

then the property is instantiated by forming a conformance to `behavior` where
`Self` is bound to the enclosing type and `Value` is bound to the property's
declared type, and invoking the accessors of the `value` implementation:

  ```
  struct Foo {
    var [behavior] foo: Int
  }

  /* behaves like */

  extension Foo: private behavior {
    @implements(behavior.Value)
    private typealias `[behavior].Value` = Int

    var foo: Int {
      get { return value }
      set { value = newValue }
    }
  }
  ```

If the protocol requires a `storage` member, and provides an `initStorage` method
to provide an initial value to the storage:

  ```
  protocol storageBehavior {
    associatedtype Value

    var storage: Something<Value> { ... }
  }
  extension storageBehavior {
    var value: Value { ... }

    static func initStorage() -> Something<Value> { ... }
  }
  ```

then a stored property of the appropriate type is instantiated to witness the
requirement, using `initStorage` to initialize:

  ```
  struct Foo {
    var [storageBehavior] foo: Int
  }

  /* behaves like */

  extension Foo: private storageBehavior {
    @implements(storageBehavior.Value)
    private typealias `[storageBehavior].Value` = Int
    @implements(storageBehavior.storage)
    private var `[storageBehavior].storage`: Something<Int> = initStorage()

    var foo: Int {
      get { return value }
      set { value = newValue }
    }
  }
  ```

In either case, the `value` and `storage` properties should support any combination
of get-only/settable and mutating/nonmutating modifiers. The instantiated property
follows the settability and mutating-ness of the `value` implementation. The
protocol can also impose requirements on the `Self` and `Value` types.

Bells and whistles such as initializer expressions, accessors,
out-of-line initialization, etc. are not implemented. Additionally, behaviors
that instantiate storage are currently only supported on instance properties.
This also hasn't been tested past sema yet; SIL and IRGen will likely expose
additional issues.
2016-02-20 15:01:05 -08:00
Dmitri Gribenko
dd75aed67a Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-17 14:40:05 -08:00
Dmitri Gribenko
efaa39ea79 stdlib: add first argument labels and some other changes to conform to API guidelines 2016-02-15 23:47:54 -08:00
Max Moiseev
3a3984877a Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-15 15:43:34 -08:00
Daniel Duan
efe230774b [AST] rename some isXXX methods to getAsXXX
There's a group of methods in `DeclContext` with names that start with *is*,
such as `isClassOrClassExtensionContext()`. These names suggests a boolean
return value, while the methods actually return a type declaration. This
patch replaces the *is* prefix with *getAs* to better reflect their interface.
2016-02-11 16:23:40 -08:00
Max Moiseev
61c837209b Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-04 16:13:39 -08:00
Slava Pestov
27da265abb Refactor some random usages of contextual types, NFC 2016-01-27 23:22:33 -08:00
Denis Vnukov
4f92a08987 Adding a location of the var/let/inout to ParamDecl 2016-01-27 13:43:42 -08:00
Denis Vnukov
db6582c72b Fixed several AST nodes wrongly marked with implicit/explicit flag 2016-01-27 13:43:39 -08:00
Doug Gregor
8336419844 Include completion source location information compound DeclNames.
When one spells a compound declaration name in the source (e.g.,
insertSubview(_:aboveSubview:), keep track of the locations of the
base name, parentheses, and argument labels.
2016-01-25 14:13:13 -08:00
Doug Gregor
fd3f03f3be Remove UnresolvedConstructorExpr.
UnresolvedConstructorExpr is not providing any value here; it's
essentially just UnresolvedDotExpr where the name refers to an
initializer, so use that instead. NFC
2016-01-20 17:09:02 -08:00
Doug Gregor
c9c1d1390c [SE-0021] Allow naming of specific initializers via "self.init(foo:bar:)". 2016-01-20 17:09:02 -08:00
Slava Pestov
1d77d810fd Re-apply "Sema: Always synthesize accessors for structs, unless they were imported from Clang"
This reverts commit 24a70e17ea.
2016-01-20 15:04:10 -08:00
Max Moiseev
9a018bd77d Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-01-20 14:38:22 -08:00
Mark Lacey
24a70e17ea Revert "Sema: Always synthesize accessors for structs, unless they were imported from Clang"
This reverts commit 2b6ab633fc because it
at least breaks:
    Swift :: stdlib/SequenceType.swift.gyb
and possibly also results in some or all of these failures:
    Swift :: compiler_crashers/27944-swift-astvisitor.swift
    Swift :: compiler_crashers/28200-swift-typebase-getdesugaredtype.swift
    Swift :: stdlib/CollectionType.swift.gyb
    Swift :: stdlib/MicroStdlib.swift
2016-01-20 08:32:39 -08:00
Slava Pestov
2b6ab633fc Sema: Always synthesize accessors for structs, unless they were imported from Clang
This fixes the issue that "SILGen: Correctly emit accessors synthesized to
witness protocol requirements" was meant to solve, but in a simpler way.

A better fix would be to first address the issue where @_transparent
function bodies are not serialized in some cases, and then only emit
synthesized accessors as needed, in the original version of this patch.
To fix the duplicate symbol issues, we would emit the synthesized
accessors with shared linkage, which would always work once serialized
bodies were available.

For resilient structs of course, we'll always need to emit accessors
anyway.
2016-01-20 02:11:53 -08:00
Slava Pestov
5273249838 Sema: Fix for setter->isMutating() check before setter was type checked
With an upcoming patch we would call setMutating() on materializeForSet
before computing the setter's isMutating() in the case where a setter
was explicitly declared 'nonmutating'.

Fix that by replacing the setter->isMutating() call with a direct
computation of the expected result.

It seems that the materializeForSet of protocol protocol requirements
has to be mutating, even if the protocol is a class protocol or the
property is nonmutating -- I need to investigate why and fix SILGen
to not make this assumption, but in the meantime, opt-out of the
new logic with protocol requirements to avoid more breakage.
2016-01-20 01:50:17 -08:00