Commit Graph

127 Commits

Author SHA1 Message Date
Chris Lattner
fe9fe47b7e Implement support for generic typealiases. 2016-03-07 22:20:16 -08:00
Chris Lattner
868a795566 Introduce a new class between TypeDecl and NominalTypeDecl named GenericTypeDecl.
This factors the DeclContext and generic signature behavior out of NTD, allowing
it to be reused in the future.  NFC.
2016-03-04 23:09:15 -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
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
Doug Gregor
9a0241bb3b SE-0022: Address Jordan's review comments about #selector. 2016-01-28 12:09:57 -08:00
Doug Gregor
1a830fa541 SE-0022: Deprecate string-literal-as-selector in favor of #selector.
Introduce Fix-Its to aid migration from selectors spelled as string
literals ("foo:bar:", which is deprecated), as well as from
construction of Selector instances from string literals
(Selector("foo:bar"), which is still acceptable but not recommended),
to the #selector syntax. Jump through some hoops to disambiguate
method references if there are overloads:

    fixits.swift:51:7: warning: use of string literal for Objective-C
         selectors is deprecated; use '#selector' instead
      _ = "overloadedWithInt:" as Selector
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          #selector(Bar.overloaded(_:) as (Bar) -> (Int) -> ())

In the cases where we cannot provide a Fix-It to a #selector
expression, we wrap the string literal in a Selector(...) construction
to suppress the deprecation warning. These are also easily searchable
in the code base.

This also means we're doing more validation of the string literals
that go into Selector, i.e., that they are well-formed selectors and
that we know about some method that is @objc and has that
selector. We'll warn if either is untrue.
2016-01-28 10:58:27 -08:00
Zach Panzarino
e3a4147ac9 Update copyright date 2015-12-31 23:28:40 +00:00
Chris Lattner
feace85d5a Enhance SubscriptDecl to be a DeclContext, so it can hold its indices.
This is necessary for some other work I'm doing, which really wants
paramdecls to have reasonable declcontexts.  It is also a small step
towards generic subscripts.
2015-12-31 12:38:28 -08:00
practicalswift
85e2e6eb9a Fix a vs. an 2015-12-26 14:40:16 +01:00
Slava Pestov
74e575e638 Sema: Add DeclContext::getGenericTypeContextDepth()
Now that generic signatures of types include generic parameters
introduced by outer generic functions, we need to know to skip
them when forming bound generic types or substitutions.

Add a function that computes the depth of the innermost generic
context that is not a generic type context.
2015-12-15 22:59:38 -08:00
Slava Pestov
57dfb45ba6 Sema: Add DeclContext::isGenericTypeContext()
Once nested generic parameter lists are properly chained, we need a
way of checking if we're inside a generic type context that's
distinct from just checking if we have a generic type signature
available.

This distinguishes between these two cases:

class A<T> {
  // generic signature
  func method() -> T { // <T> A<T> -> () -> T
  }
}

func f<T>() {
  class A {
    // no generic signature
    func method() -> T { // A -> () -> T
    }
  }
}
2015-12-14 13:46:45 -08:00
Doug Gregor
3855bb824b Sort protocol conformances for serialization and SILGen emission.
Determinism++, otherwise NFC

Swift SVN r30169
2015-07-13 22:16:57 +00:00
Doug Gregor
fab5e741bd Unrevert "Sema: Make derived conformances work from extensions"
Update IRGen test for 32/64-bit differences.

Swift SVN r28988
2015-05-24 17:55:42 +00:00
Ted Kremenek
a575727a2b Revert "Sema: Make derived conformances work from extensions"
Speculatively revert; this looks like it is breaking the iOS bots.

Swift SVN r28963
2015-05-23 15:26:55 +00:00
Slava Pestov
9388a955dc Sema: Make derived conformances work from extensions
This is more complex than it could be if ExtensionDecl and NominalTypeDecl
had a common ancestor in the Decl hierarchy, however this is not possible
right now because TypeDecl inherits from ValueDecl.

Fixes <rdar://problem/20981254>.

Swift SVN r28941
2015-05-23 01:21:10 +00:00
Slava Pestov
1e31d0c5e0 AST: Move DerivedGlobalDecls from NominalTypeDecl to InterableDeclContext, NFC
Progress on <rdar://problem/20981254>.

Swift SVN r28931
2015-05-22 20:28:19 +00:00
Slava Pestov
5899e62637 AST: Add dynamic cast from Decl to IterableDeclContext
Also allow cast<> from any Decl to DeclContext, not just ValueDecl.
An example of a Decl that is a DeclContext but not a ValueDecl is
ExtensionDecl.

The const_cast<> hack is horrid but its needed to deal with both const
and non-const operands in the patch that eventually uses this.

Note that this adds an explicit 'const auto' to the prior usage of
cast<DeclContext> in Mangling.cpp.

NFC

Progress on <rdar://problem/20981254>.

Swift SVN r28929
2015-05-22 20:28:16 +00:00
Doug Gregor
570e5acc09 Make extension-related DeclContext queries more robust.
Resolve extensions when we need them, but don't bother when we
don't. Among other things, this lets us identify a protocol extension
before it's been fully validated. No behavior change for anything we
have written now.

Swift SVN r28891
2015-05-21 22:40:21 +00:00
Jordan Rose
2ad796627a Revert "Prefer compiler-provided conformances to those required by other protocols."
This may not be the right solution. Even if it is, there are SourceKit tests
that need updating.

This reverts commit r28849 / rdar://problem/21007417.

Swift SVN r28852
2015-05-20 21:32:56 +00:00
Jordan Rose
1ad7651e19 Prefer compiler-provided conformances to those required by other protocols.
Previously, we'd warn on this code:

  enum Suit { case Spades, Hearts, Clubs, Diamonds }
  extension Suit : Comparable {}
  func <(...) {...}

because both Comparable and the synthesized conformance to Hashable imply
a conformance to Equatable. However, that's silly: Suit already has a
synthesized conformance to Equatable associated with the main 'enum'
declaration, not the extension. These compiler-provided conformances are
part of the language and something people rely on, so rank them higher than
conformances implied by conforming to a refined protocol.

rdar://problem/21007417

Swift SVN r28849
2015-05-20 20:48:04 +00:00
Joe Groff
ae1f3af9be AST: Add the ability to dyn_cast a ValueDecl to DeclContext.
Swift SVN r28341
2015-05-08 23:57:23 +00:00
Doug Gregor
b8995b0aa3 Transform the Module class into ModuleDecl.
Modules occupy a weird space in the AST now: they can be treated like
types (Swift.Int), which is captured by ModuleType. They can be
treated like values for disambiguation (Swift.print), which is
captured by ModuleExpr. And we jump through hoops in various places to
store "either a module or a decl".

Start cleaning this up by transforming Module into ModuleDecl, a
TypeDecl that's implicitly created to describe a module. Subsequent
changes will start folding away the special cases (ModuleExpr ->
DeclRefExpr, name lookup results stop having a separate Module case,
etc.).

Note that the Module -> ModuleDecl typedef is there to limit the
changes needed. Much of this patch is actually dealing with the fact
that Module used to have Ctx and Name public members that now need to
be accessed via getASTContext() and getName(), respectively.

Swift SVN r28284
2015-05-07 21:10:50 +00:00
Doug Gregor
38cc1fe5c6 Remove LazyResolver arguments from API entry points to the conformance lookup table.
Swift SVN r26838
2015-04-02 00:06:01 +00:00
Doug Gregor
abee3281e3 Basic partial ordering for members of protocol extensions.
Implement simplistic partial ordering rules for members of protocol
extensions. Specifically:
  - A member of a concrete type is more specialized than a member of a
  protocol extension
  - A member of a protocol extension of P1 is more specialized than a
  member of a protocol extension of P2 if P1 inherits from P2

This achieves most of what rdar://problem/20335936 covers, but does
not yet handle ordering between constrained protocol extensions.

Swift SVN r26723
2015-03-30 19:14:48 +00:00
Doug Gregor
3d77855b31 Start allowing extensions of protocol types.
Remove the semantic restrictions that prohibited extensions of
protocol types, and start making some systematic changes so that
protocol extensions start to make sense:
  - Replace a lot of occurrences of isa<ProtocolDecl> and
    dyn_cast<ProtocolDecl> on DeclContexts to use the new
    DeclContext::isProtocolOrProtocolExtensionContext(), where we want
    that behavior to apply equally to protocols and protocol extensions.
  - Eliminate ProtocolDecl::getSelf() in favor of
    DeclContext::getProtocolSelf(), which produces the appropriate
    generic type parameter for the 'Self' of a protocol or protocol
    extension. Update all of the callers of ProtocolDecl::getSelf()
    appropriately.
  - Update extension validation to appropriately form generic
    parameter lists for protocol extensions.
  - Methods in protocol extensions always use the witnesscc calling
  convention.

At this point, we can type check and SILGen very basic definitions of
protocol extensions with methods that can call protocol requirements,
generic free functions, and other methods within the same protocol
extension.

Regresses four compiler crashers but improves three compiler
crashers... we'll call that "progress"; the four regressions all hit
the same assertion in the constraint system that will likely be
addressed as protocol extensions starts working.

Swift SVN r26579
2015-03-26 04:50:51 +00:00
Doug Gregor
479660b54b When !NDEBUG, track the contexts of archetype types.
Helps with debugging when archetypes get tangled together. NFC

Swift SVN r26439
2015-03-23 19:00:51 +00:00
Doug Gregor
7708c5a65e Start moving away from (Nominal)?TypeDecl::getProtocols().
Instead, use other entry points, particularly those that use the conformance lookup table.

Swift SVN r26412
2015-03-22 12:35:21 +00:00
Doug Gregor
b75e03b724 Eliminate the annoying scratch buffer from getLocalConformances(). NFC
Swift SVN r26322
2015-03-19 22:10:05 +00:00
Xi Ge
520df97787 [CodeCompletion] Adopt a more efficient algorithm
to find the nearest AST parent that meets a certain condition

Swift SVN r26134
2015-03-14 08:30:16 +00:00
Xi Ge
8367428ed0 [CodeCompletion] Literal complete.
When code completing a literal expr, it is likely that code completion engine only collects the expr
that is not fully type checked. Therefore, no members of the literal can be suggested. To address this,
we try to climb up expr hierarchy in AST to find an expr with a nominal type, and use the nominal type
to finish code completion.
rdar://20059173

Swift SVN r26116
2015-03-14 00:34:32 +00:00
Doug Gregor
9271a24a92 Introduce a protocol conformance registry for nominal types.
(Note that this registry isn't fully enabled yet; it's built so that
we can test it, but has not yet taken over the primary task of
managing conformances from the existing system).

The conformance registry tracks all of the protocols to which a
particular nominal type conforms, including those for which
conformance was explicitly specified, implied by other explicit
conformances, inherited from a superclass, or synthesized by the
implementation.

The conformance registry is a lazily-built data structure designed for
multi-file support (which has been a problematic area for protocol
conformances). It allows one to query for the conformances of a type
to a particular protocol, enumerate all protocols to which a type
conforms, and enumerate all of the conformances that are associated
with a particular declaration context (important to eliminate
duplicated witness tables).

The conformance registry diagnoses conflicts and ambiguities among
different conformances of the same type to the same protocol. There
are three common cases where we'll see a diagnostic:

1) Redundant explicit conformance of a type to a protocol:

    protocol P { }
    struct X : P {  }
    extension X : P { } // error: redundant explicit conformance

2) Explicit conformance to a protocol that collides with an inherited
  conformance:

    protocol P { }
    class Super : P { }
    class Sub : Super, P { } // error: redundant explicit conformance

3) Ambiguous placement of an implied conformance:

    protocol P1 { }
    protocol P2 : P1 { }
    protocol P3 : P1 { }

    struct Y { }
    extension Y : P2 { }
    extension Y : P3 { } // error: ambiguous implied conformance to 'P1'

  This happens when two different explicit conformances (here, P2 and
  P3) placed on different declarations (e.g., two extensions, or the
  original definition and other extension) both imply the same
  conformance (P1), and neither of the explicit conformances imply
  each other. We require the user to explicitly specify the ambiguous
  conformance to break the ambiguity and associate the witness table
  with a specific context.

Swift SVN r26067
2015-03-12 21:11:23 +00:00
Doug Gregor
0242f5af18 Add DeclContext::isNominalTypeOrNominalTypeExtensionContext(). NFC
Swift SVN r26065
2015-03-12 21:11:09 +00:00
Devin Coughlin
7ea8aa82ea [Sema] Validate declaration version range availability within lexical scope
This commit validates @availability() attribute version ranges to ensure that
a declaration is not more available than its lexically containing scope. To do so,
we find the inner-most declaration containing an @availability attribute that itself
has an @availability attribute and check that first attribute's available
version range is contained in the enclosing declaration's available range. If not,
we emit a diagnostic.

This commit removes a FIXME for checking @availability and overrides. It appears that
the FIXME is a copy/paste to/from AttributeOverrideChecker, where it still resides.

Swift SVN r25453
2015-02-21 01:34:38 +00:00
David Farler
51f8070abe Serialize local types
Local type declarations are saved in the source file during parsing,
now serialized as decls. Some of these may be defined in DeclContexts
which aren't Decls and previously weren't serialized. Create four new
record kinds:

* PatternBindingInitializer
* DefaultArgumentInitializer
* AbstractClosureExpr
* TopLevelCodeDecl

These new records are used to only preserve enough information for
remangling in the debugger, and parental context relationships.

Finally, provide a lookup API in the module to search by mangled name.
With the new remangling API, the debugging lifecycle for local types
should be complete.

The extra LOCAL_CONTEXT record will compressed back down in a
subsequent patch.

Swift SVN r24739
2015-01-27 01:49:54 +00:00
David Farler
cad9f99929 Revert "Serialize local types and provide a lookup API"
Changing the design of this to maintain more local context
information and changing the lookup API.

This reverts commit 4f2ff1819064dc61c20e31c7c308ae6b3e6615d0.

Swift SVN r24432
2015-01-15 00:33:10 +00:00
David Farler
fab3d491d9 Serialize local types and provide a lookup API
rdar://problem/18295292

Locally scoped type declarations were previously not serialized into the
module, which meant that the debugger couldn't reason about the
structure of instances of those types.

Introduce a new mangling for local types:
[file basename MD5][counter][identifier]
This allows the demangle node's data to be used directly for lookup
without having to backtrack in the debugger.

Local decls are now serialized into a LOCAL_TYPE_DECLS table in the
module, which acts as the backing hash table for looking up
[file basename MD5][counter][identifier] -> DeclID mappings.

New tests:
* swift-ide-test mode for testing the demangle/lookup/mangle lifecycle
of a module that contains local decls
* mangling
* module merging with local decls

Swift SVN r24426
2015-01-14 22:08:47 +00:00
Jordan Rose
9ddd23c0ff Invert DeclContext::is[Non]CascadingContextForLookup.
...and a few other things.

Attempting to remove a few negations to minimize confusion.
No intended functionality change.

Swift SVN r23970
2014-12-17 02:42:48 +00:00
Jordan Rose
99075516ce Use "cascading/non-" terms for dependencies instead of "private/non-".
"private" is a very overloaded term already. "Cascading" instead of
"non-private" is a bit more clear about what will happen with this sort
of lookup.

No functionality change. There are some double negatives I plan to clean
up in the next commit, but this one was supposed to be very mechanical.

Swift SVN r23969
2014-12-17 02:42:45 +00:00
Jordan Rose
5033d915a3 Dependencies: Private functions do not affect downstream files.
This adds a check to isPrivateContextForLookup, and also changes Sema to
use a function itself as the lookup context for non-generic functions'
result types (like generic functions already do). It also moves
isPrivateContextForLookup onto DeclContext itself, to be used in the next
commits.

Swift SVN r23633
2014-12-03 02:56:00 +00:00
John McCall
667eae6c1f Clarify that the new declaration is placed after the
addMember hint and fix the splicing logic.

Fortunately, this wasn't extensively used.

Swift SVN r22013
2014-09-17 08:08:06 +00:00
Jordan Rose
cacec395db Drop the separate "LookupName" type for discriminated lookup.
Now that there's just one entry point for discriminated lookup, there's not
really a need for this extra abstraction.

One thing still up in the air is unqualified lookup support for discriminator
preferences (for, say, breakpoint conditions), but we'll cross that bridge
when we come to it.

Part of rdar://problem/17632175

Swift SVN r21755
2014-09-06 00:18:05 +00:00
John McCall
2c239766a5 Declare the alignments of various AST types in their own
header so that we can freely form PointerIntPairs and
PointerUnions without worrying about header circularity.

Swift SVN r21694
2014-09-04 01:16:09 +00:00
Jordan Rose
1f5d81d5dc Teach swift-ide-test to look up entities by mangled name.
Currently this only handles top-level nominal types. We're just trying to
emulate what the debugger does when it needs to go from a mangled name to
an AST node, so it's okay that the cases handled here are very restricted.
We just want to make sure that the debugger is /able/ to do what it needs
to do.

This does not yet handle nested (non-top-level) values; that will require
changes to DeclContext::lookupQualified.

Part of rdar://problem/17632175

Swift SVN r21690
2014-09-03 23:42:13 +00:00
Jordan Rose
bbfedf989d Change qualified lookup to take a (DeclName, discriminator) pair.
This is in preparation for allowing demangling to match up with a particular
AST node, even if there are two private decls with the same name in the same
module. This commit doesn't actually change anything about the lookup; the
next commits will start adding support for the various lookups-with-
discriminators. (This is mostly only useful for the debugger.)

Part of rdar://problem/17632175

Swift SVN r21689
2014-09-03 23:42:11 +00:00
Chris Lattner
f693c5c83f fix rdar://17405715 - lazy property crashes silgen of implicit memberwise initializer
The issue here is that SILGen is expecting the argument pattern for the
synthesized ConstructorDecl to line up with the stored property list for the
decl containing the constructor.  This is super fragile and probably the wrong
way to go (it would be better for sema to synthesize the entire ctor and make it
not be magical at all in silgen), but do a small fix to improve the situation
by inserting the lazy property storage next to the computed lazy property.



Swift SVN r19642
2014-07-07 22:25:52 +00:00
Jordan Rose
f4296846b0 [Serialization] Allow witness conformances to be "incomplete" when writing.
This just means we haven't deserialized them properly yet. As soon as we
try to /do/ something with the conformance, we'd pull in what we need, but
for reserializing (i.e. module-merging) we can generally just keep going.

<rdar://problem/17251682>

Swift SVN r19540
2014-07-03 22:56:34 +00:00
Chris Lattner
c5d96a97a2 fix multi-stmt closures, whose bodies may not be typechecked yet.
Swift SVN r17918
2014-05-12 03:00:37 +00:00
Chris Lattner
ab7725aaae introduce a new DeclContext::isClassOrClassExtensionContext helper method,
which will consolidate a bunch of places that this is used.

I'd appreciate review on this, because I can never keep getDeclaredTypeOfContext
vs getDeclaredTypeInContext straight.


Swift SVN r17891
2014-05-11 22:10:19 +00:00
Dmitri Hrybenko
35c587aadf Code completion: don't complete associated types on non-metatypes
Swift SVN r16817
2014-04-25 12:46:32 +00:00