Commit Graph

751 Commits

Author SHA1 Message Date
Joe Groff
c748ba6c12 Merge pull request #3870 from jckarter/no-bridged-default-literal-types
Sema: Don't try bridged classes as default literal types.
2016-07-29 22:16:53 -07:00
Doug Gregor
b9363fe6bd [SE-0111] Enable SE-0111 by default. 2016-07-29 17:28:24 -07:00
Joe Groff
11f03cd8b5 Sema: Don't try bridged classes as default literal types.
One last bit of SE-0072. We shouldn't fall back to bridged classes in the absence of type context for literals anymore. By itself, this kind of hoses the use of literals with NS types, but I think we can get most of the QoI back with overlay changes I plan to propose following this.
2016-07-29 15:18:31 -07:00
Doug Gregor
202cf2e754 [SE-0111] Track function reference kinds in member references.
Extend the handling of function reference kinds to member references
(e.g., x.f), and therefore the logic for stripping argument labels. We
appear to be stripping argument labels from all of the places where it
is required.
2016-07-28 15:41:59 -07:00
Doug Gregor
a9536906ff [SE-0111] Drop argument labels on references to function values.
When referencing a function in the type checker, drop argument labels
when we don't need them to type-check an immediate call to that
function. This provides the semantic behavior of SE-0111, e.g.,
references to functions as values produce unlabeled function types,
without the representational change of actually dropping argument
labels from the type system.

At the moment, this only works for bare references to functions. It
still needs to be pushed through more of the type checker and more AST
nodes to work in the general case.

Keep this work behind the frontend flag
-suppress-argument-labels-in-types for now.
2016-07-28 15:40:11 -07:00
Slava Pestov
57c58176bc AST: Remove noreturn bit from function types 2016-07-24 00:15:34 -07:00
Doug Gregor
c56f96d237 [Type checker] Synthesize member operator '==' for Equatable enums.
Rather than synthesizing a global operator '==' for Equatable enums,
synthesize a member operator, which is more idiomatic and much
cleaner.

To make sure that these synthesized operators can actually be found,
start considering operator requirements in protocols
more generally in the type checker, so that, e.g., "myEnum == myEnum"
will type-check against Equatable.== and, on successful type-check,
will call the (newly-synthesized) witness for '=='. This both makes it
easier to make sure we find the operators in, e.g., complex multi-file
and lazy-type checking scenarios, and is a step toward the
type-checking improvements described in SE-0091.
2016-07-21 12:54:27 -07:00
Doug Gregor
80f0852504 [SE-0091] Allow 'static' operators to be declared within types and extensions thereof.
Allow 'static' (or, in classes, final 'class') operators to be
declared within types and extensions thereof. Within protocols,
require operators to be marked 'static'. Use a warning with a Fix-It
to stage this in, so we don't break the world's code.

Protocol conformance checking already seems to work, so add some tests
for that. Update a pile of tests and the standard library to include
the required 'static' keywords.

There is an amusing name-mangling change here. Global operators were
getting marked as 'static' (for silly reasons), so their mangled names
had the 'Z' modifier for static methods, even though this doesn't make
sense. Now, operators within types and extensions need to be 'static'
as written.
2016-07-18 23:18:57 -07:00
Robert Widmann
f97e5dcb0e [SE-0115][1/2] Rename *LiteralConvertible protocols to ExpressibleBy*Literal. This
change includes both the necessary protocol updates and the deprecation
warnings
suitable for migration.  A future patch will remove the renamings and
make this
a hard error.
2016-07-12 15:25:24 -07:00
Slava Pestov
409af27eb3 Sema: Use DeclContext::getSelfInterfaceType() and DeclContext::getSelfTypeInContext() more, NFC
There are many places where we do the 'if inside a protocol, get the
Self type parameter, otherwise, use the declared type' dance.
We actually have really handy utility methods that encapsulate this,
so let's use them more.
2016-07-02 05:35:15 -07:00
Slava Pestov
004f145ba4 Sema: Fix some problems with generic typealiases
The underlying type can now refer to generic parameters from an
outer context, and we allow qualified and unqualified access to
such typealiases.

One problem remains, with specializations of generic typealiases
in expression parsing context, marked with FIXME in the test.
2016-06-23 23:14:38 -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
bc968c699a Sema: Nuke getGenericTypeContextDepth()
Now that ConstraintSystem::openGeneric() is the only remaining
caller of this function, inline it in there and open-code the
logic.

Also, add a hack for opening nominal types contained inside
protocol types. This is invalid, but we should not crash, so
bind the type variable for the protocol 'Self' type to the
'Self' archetype, since it will not be equated with anything
otherwise.
2016-06-16 22:57:30 -07:00
Slava Pestov
f6fff1bcef Sema: Split off openFunctionType() from openType()
- Change openGeneric() to take two DeclContexts, one is the generic
  context for the signature and the second is the generic context
  containing the declaration being opened

- This allows us to clean up the logic around skipProtocolSelfRequirement;
  instead of testing both the DeclContext and its parent, we know
  exactly what DeclContext to test. Also, use the right Self type here,
  instead of always using (0, 0)

- Now that we have the right DeclContexts handy, we can move the
  getGenericTypeContextDepth() call into openGeneric(), simplifying
  callers

- Now that openType() no longer opens generic signatures, it takes fewer
  parameters
2016-06-16 22:55:17 -07:00
Slava Pestov
92d5bd2404 Sema: Fix when opening type with minOpeningDepth != 0
This fixes a regression from my previous patch fixing some issues
with nested generic functions:

<bbefeb2fc5>
2016-06-16 22:52:19 -07:00
Slava Pestov
19f72c8593 ClangImporter: Fix diagnostics for NS* prefix stripping from generic types
We were failing to create an unavailable TypeAlias for the old name
in the case the renamed type was generic, leading to poor diagnostics.

Also, Sema resolves generic TypeAliases very early, while building
a Type from a TypeRepr -- this means the unavailable/deprecated
check runs too late to catch generic TypeAlises.

Add a hack where we preserve a reference to the original TypeAliasDecl
by way of constructing a SubstitutedType which desugars to the
replacement type, rather than resolving the replacement type
directly, so that the availability check can pick it up.

A better fix for this would be to introduce a BoundGenericAliasType
sugared type, but that's a bigger change that can come later.

Fixes <rdar://problem/26206263>.
2016-05-25 00:32:11 -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
practicalswift
092007bf12 [gardening] Fix recently introduced typos. 2016-04-19 21:48:05 +02:00
Doug Gregor
bc158c31bf [Sema] Improve diagnostics for witness mismatches against @objc protocols.
Simplify and improve the checking of @objc names when matching a
witness to a requirement in the @objc protocol. First, don't use
@objc-ness as part of the initial screening to determine whether a
witness potentially matches an @objc requirement: we will only reject
a potential witness when the potential witness has an explicit
"@nonobjc" attribute on it. Otherwise, the presence of @objc and the
corresponding Objective-C name is checked only after selecting a
candidate. This more closely mirrors what we do for override checking,
where we match based on the Swift names (first) and validate
@objc'ness afterward. It is also a stepping stone to inferring
@objc'ness and @objc names from protocol conformances.

Second, when emitting a diagnostic about a missing or incorrect @objc
annotation, make sure the Fix-It gets the @objc name right: this might
mean adding the Objective-C name along with @objc (e.g.,
"@objc(fooWithString:bar:)"), adding the name to an
unadorned-but-explicit "@objc" attribute, or fixing the name of an
@objc attribute (e.g., "@objc(foo:bar:)" becomes
@objc(fooWithString:bar:)"). Make this diagnostic an error, rather
than a note on a generic "does not conform" diagnostic, so it's much
easier to see the diagnostic and apply the Fix-It.

Third, when emitting the warning about a non-@objc near-match for an
optional @objc requirement, provide two Fix-Its: one that adds the
appropriate @objc annotation (per the paragraph above), and one that
adds @nonobjc to silence the warning.

Part of the QoI improvements for conformances to @objc protocols,
rdar://problem/25159872.
2016-04-19 10:22:23 -07:00
Greg Parker
125a146365 Revert "[Sema] Improve diagnostics for witness mismatches against @objc protocols." and "Improve diagnostics for selector collisions with @objc optional requirements."
This reverts commits 46269299cd
and 27279866ad
and c826a408dd.

The changes broke test bots, including
https://ci.swift.org/job/oss-swift-package-osx/1348/
2016-04-19 05:52:33 -07:00
Doug Gregor
46269299cd [Sema] Improve diagnostics for witness mismatches against @objc protocols.
Simplify and improve the checking of @objc names when matching a
witness to a requirement in the @objc protocol. First, don't use
@objc-ness as part of the initial screening to determine whether a
witness potentially matches an @objc requirement: we will only reject
a potential witness when the potential witness has an explicit
"@nonobjc" attribute on it. Otherwise, the presence of @objc and the
corresponding Objective-C name is checked only after selecting a
candidate. This more closely mirrors what we do for override checking,
where we match based on the Swift names (first) and validate
@objc'ness afterward. It is also a stepping stone to inferring
@objc'ness and @objc names from protocol conformances.

Second, when emitting a diagnostic about a missing or incorrect @objc
annotation, make sure the Fix-It gets the @objc name right: this might
mean adding the Objective-C name along with @objc (e.g.,
"@objc(fooWithString:bar:)"), adding the name to an
unadorned-but-explicit "@objc" attribute, or fixing the name of an
@objc attribute (e.g., "@objc(foo:bar:)" becomes
@objc(fooWithString:bar:)"). Make this diagnostic an error, rather
than a note on a generic "does not conform" diagnostic, so it's much
easier to see the diagnostic and apply the Fix-It.

Third, when emitting the warning about a non-@objc near-match for an
optional @objc requirement, provide two Fix-Its: one that adds the
appropriate @objc annotation (per the paragraph above), and one that
adds @nonobjc to silence the warning.

Part of the QoI improvements for conformances to @objc protocols,
rdar://problem/25159872.
2016-04-18 17:08:06 -07:00
John McCall
c0021e1c62 Only check the minimal set of generic requirements when opening
a generic function type during constraint solving, as opposed to
checking a bunch of implicit things that we already know.  This
should significantly improve the efficiency of checking uses of
generic APIs by reducing the total number of type variables and
constraints.

It is becoming increasingly funny to refer to this minimized generic
signature as the "mangling" signature.

The test changes are kind of a wash: in one case, we've eliminated
a confusing extra error, but in another we've caused the confusing
extra error to refer to '<<error type>>'.  Not worth fighting right
now.  The reference-dependencies change is due to not needing to
pull in all of those associated types anymore, which seems correct.
2016-04-11 14:53:29 -07:00
Chris Lattner
8ad365b30e Rework ReplaceDependentTypes to call into applyUnboundGenericArguments
to remap an unbound generic type into a bound generic type.  This shares
a common codepath to make way for future progress.

This exposed a case where we'd produce invalid ASTs in some testcases
in the validation tests because started asserting on the invalid code.
Solve this by detecting the problem and producing a circularity error.

Overall, NFC.
2016-03-06 22:50:53 -08:00
Slava Pestov
5e020e62da Nuke more trivial usages of getDeclaredTypeInContext(), NFC 2016-02-16 23:08:57 -08:00
gregomni
37d05ea0dc Improved handling of mixed lvalues & rvalues in tuple exprs
My previous commit here didn’t work correctly for nested tuples, both
because it didn’t recurse into them to propagate access kind correctly
and because an outer TupleIndex overload (when indexing into the nested
tuple) could still be expecting an lvalue type.

This fix is much better. ConstraintSystem::resolveOverload now
correctly always expects rvalue types from rvalue tuples. And during
applyMemberRefExpr, if the overload expects an rvalue but the tuple
contains lvalues, coerceToType() correctly does any recursive munging
of the tuple expr required.
2016-02-15 20:59:53 -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
Slava Pestov
27da265abb Refactor some random usages of contextual types, NFC 2016-01-27 23:22:33 -08:00
Joe Pamer
762fc2a0ab - Do not update the work list whilst contracting edges.
- Temporarily disable contraction of conversion constraints.
2016-01-22 12:34:33 -08:00
John McCall
1f3b3142b4 Distinguish conformance and superclass generic requirements.
As part of this, use a different enum for parsed generic requirements.

NFC except that I noticed that ASTWalker wasn't visiting the second
type in a conformance constraint; fixing this seems to have no effect
beyond producing better IDE annotations.
2016-01-11 16:07:37 -08:00
Jacob Bandes-Storch
b97cb48c2b [AST] Fix inconsistent handling of generic args & params during BoundGenericType::getSubstitutions
A decl’s full GenericSignature is set during validateGenericTypeSignature().

Then during ConstraintSystem::openTypes(), in ReplaceDependentTypes, the GenericArgs list is built from the generic signature (via getGenericParamTypes()) and passed into a new BoundGenericType.

In BoundGenericType::getSubstitutions(), the GenericArgs are assumed to match getGenericParamsOfContext()->getParams().

However, in reality, the GenericArgs include all levels of generic args, whereas getGenericParamsOfContext() are the params of the innermost context only, so the params array is accessed past its end.

This commit changes NominalTypeDecl::getGenericParamTypes() to return the innermost params, in order to match the output of BoundGenericType::getGenericArgs(). For clarity and to hopefully prevent future confusion, we also rename getGenericParamTypes() to getInnermostGenericParamTypes().
2016-01-09 02:19:28 -08:00
Doug Gregor
2a626b40ae [Constraint system] Remove some unused code. NFC
We don't do substitutions based on archetypes here any more.
2016-01-03 22:28:01 -08:00
Doug Gregor
e1fe27bd5f [Constraint system] Eliminate DependentTypeOpener. NFC
Eliminate the last client of DependentTypeOpener,
RequirementTypeOpener, which tracked the opened Self type when doing
witness/requirement matching and substituted in the known type
witnesses for that protocol. It had a bunch of dead logic hanging
around from the days where we used the constraint system to deduce
type witnesses. Now, a simple substitution suffices.

With its last client gone, remove DependentTypeOpener as well.
2016-01-02 21:51:22 -08:00
Doug Gregor
75cb941440 [Constraint System] Kill the ArchetypeOpener; bind type variables instead. NFC
The ArchetypeOpener was used only to replace dependent types with
archetypes (or concrete types) within the opening context. We can do
the same simply by letting the constraint system create type variables
and then binding those type variables to the appropriate
archetypes/concrete types in that context.

Eliminate the two DependentTypeOpener entry points that were only used
by the ArchetypeOpener.
2016-01-02 15:28:12 -08:00
Chris Lattner
a30ae2bf55 Merge pull request #836 from zachpanz88/new-year
Update copyright date
2015-12-31 19:36:14 -08:00
Chris Lattner
7daaa22d93 Completely reimplement/redesign the AST representation of parameters.
Parameters (to methods, initializers, accessors, subscripts, etc) have always been represented
as Pattern's (of a particular sort), stemming from an early design direction that was abandoned.
Being built on top of patterns leads to patterns being overly complicated (e.g. tuple patterns
have to have varargs and default parameters) and make working on parameter lists complicated
and error prone.  This might have been ok in 2015, but there is no way we can live like this in
2016.

Instead of using Patterns, carve out a new ParameterList and Parameter type to represent all the
parameter specific stuff.  This simplifies many things and allows a lot of simplifications.
Unfortunately, I wasn't able to do this very incrementally, so this is a huge patch.  The good
news is that it erases a ton of code, and the technical debt that went with it.  Ignoring test
suite changes, we have:
   77 files changed, 2359 insertions(+), 3221 deletions(-)

This patch also makes a bunch of wierd things dead, but I'll sweep those out in follow-on
patches.

Fixes <rdar://problem/22846558> No code completions in Foo( when Foo has error type
Fixes <rdar://problem/24026538> Slight regression in generated header, which I filed to go with 3a23d75.

Fixes an overloading bug involving default arguments and curried functions (see the diff to
Constraints/diagnostics.swift, which we now correctly accept).

Fixes cases where problems with parameters would get emitted multiple times, e.g. in the
test/Parse/subscripting.swift testcase.

The source range for ParamDecl now includes its type, which permutes some of the IDE / SourceModel tests
(for the better, I think).

Eliminates the bogus "type annotation missing in pattern" error message when a type isn't
specified for a parameter (see test/decl/func/functions.swift).

This now consistently parenthesizes argument lists in function types, which leads to many diffs in the
SILGen tests among others.

This does break the "sibling indentation" test in SourceKit/CodeFormat/indent-sibling.swift, and
I haven't been able to figure it out.  Given that this is experimental functionality anyway,
I'm just XFAILing the test for now.  i'll look at it separately from this mongo diff.
2015-12-31 19:24:46 -08:00
Zach Panzarino
e3a4147ac9 Update copyright date 2015-12-31 23:28:40 +00:00
Slava Pestov
d6ea5d8717 Sema: Chain all generic parameter lists
Previously, methods on DeclContext for getting generic parameters
and signatures did not walk up from type contexts to function
contexts, or function contexts to function contexts.

Presumably this is because SIL doesn't completely support nested
generics yet, instead only handling these two special cases:

- non-generic local function inside generic function
- generic method inside generic type

For local functions nested inside generic functions, SIL expects
the closure to not have an interface type or generic signature,
even if the contextual type signature contains archetypes.
This should probably be revisited some day.

Recall that these cases are explicitly rejected by Sema diagnostics
because they lack SIL support:

- generic function inside generic function
- generic type inside generic function

After the previous patches in this series, it becomes possible to
construct types that are the same as before for the supported uses of
nested generics, while introducing a more self-consistent conceptual
model for the unsupported cases.

Some new tests show we generate diagnotics in various cases that
used to crash.

The conceptual model might still not be completely right, and of
course SIL, IRGen and runtime support is still missing.
2015-12-16 11:32:56 -08: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
f43a5fec87 Sema: Remove dead code, NFC 2015-12-15 22:59:38 -08:00
Doug Gregor
881484bfd2 Clean up deduplication of dynamic AnyObject lookup results.
Use ObjCSelector rather than some seriously dodgy string
manipulation. Should be NFC.
2015-12-14 15:29:35 -08:00
Ben Langmuir
4082355244 Split KnownProtocolKind enum case from protocol name
This avoids us using reserved identifiers as the enum case names of all
our underscored protocols like _ObjectiveCBridgeable. I used the
convention PROTOCOL_WITH_NAME to mirror how the known identifiers work.

Swift SVN r32924
2015-10-27 23:10:36 +00:00
Ben Langmuir
2d465b8a32 Remove unused literal convertible protocol descriptions
Formerly used in creating friendly type-checker diagnostics, these seem
to be dead now.

Swift SVN r32921
2015-10-27 21:52:53 +00:00
Dmitri Hrybenko
2e51d23875 Un-ifdef object literals
Swift SVN r32880
2015-10-25 07:50:53 +00:00
Chris Willmore
49e5130103 Allow inout closure param type to be inferred from context or usage.
Introduce a new constraint kind, BindParam, which relates the type of a
function parameter to the type of a reference to it from within the
function body. If the param type is an inout type, the ref type is an
lvalue type with the same underlying object type; otherwise the two
types must be the same. This prevents DeclRefExprs from being inferred
to have inout type in some cases.

<rdar://problem/15998821> Fail to infer types for closure that takes an inout argument

Swift SVN r32183
2015-09-23 18:46:12 +00:00
Chris Lattner
16a51639ef Fix <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
Introduce a new "OpenedGeneric" locator for when openGeneric opens a generic
decl into a plethora of constraints, and use this in CSDiags to distinguish 
whether a constraint refers to an Expr as a whole or an "aspect" of the constraint.

Use that information in FailureDiagnosis::diagnoseGeneralConversionFailure
to know whether (as a fallback) we can correctly re-typecheck an entire expr 
to obtain a missing type.  If we are talking about an aspect of the expr, then
this clearly won't work.

The upshot of this is that where we previously compiled the testcase in 22519983
to:

y.swift:31:9: error: type '(inout _) -> Bool' does not conform to protocol 'RawRepresentable'
let a = safeAssign
        ^

we now produce the somewhat more useful:
y.swift:31:9: error: argument for generic parameter 'T' could not be inferred
let a = safeAssign
        ^
y.swift:27:6: note: in call to function 'safeAssign'
func safeAssign<T: RawRepresentable>(inout lhs: T) -> Bool {
     ^



Swift SVN r31620
2015-09-02 05:15:22 +00:00
Slava Pestov
7e7191478a AST: Split off a new replaceSelfParameterType() method and clean up some code, NFC
Swift SVN r31478
2015-08-26 04:21:12 +00:00
Chris Willmore
51f08e0285 Add FileReference object literals and _FileReferenceLiteralConvertible protocol.
<rdar://problem/21781451> Add file literal to Swift

Swift SVN r31232
2015-08-13 22:38:55 +00:00
Jordan Rose
953424072e Guard "object literals" feature with SWIFT_ENABLE_OBJECT_LITERALS.
This is not a feature we're releasing at the moment, so provide a way
to turn it off.

rdar://problem/21935551

Swift SVN r30966
2015-08-04 00:16:52 +00:00
Joe Pamer
d4e165688b When opening the type of a member reference for a given overload, and the context of the self type is a class-constrained existential, do not automatically wrap the self type in an inout. Doing so leads to mismatched expectations during constraint application, which will result in a compiler crash. (rdar://problem/22012606)
Swift SVN r30724
2015-07-28 21:12:21 +00:00
Chris Lattner
a8d9aec957 revert r30641, it wasn't correct. We produce better diagnostics for the
cases I was worried about anyway now.


Swift SVN r30651
2015-07-26 05:33:33 +00:00