Commit Graph

5910 Commits

Author SHA1 Message Date
Chris Lattner
836b88e320 refactor some code into a helper method, NFC. 2016-02-08 10:06:03 -08:00
Daniel Duan
5242b67476 [Sema] implement better type circularity check
Certain type circularities weren't being checked until this point. Such as

```
struct X<T> { let a: X<X> }
struct Y<T> { let a: (Int, Y<Y>) }
enum Z<T> { case A(Optional<Z<Z>>) }
```

We introduce a more comprehensive approach to detect these in type checker.
After name lookup, exam each value field in declared structs and enums for
self-reference types that creates inifinite sizes.
2016-02-07 22:10:42 -08:00
Doug Gregor
ff8e91399b Merge pull request #1200 from gregomni/generic-func-args
Replace use of getArchetype() in diagnoseGenericParameterErrors()
2016-02-05 13:58:57 -08:00
Doug Gregor
42bb2528dd [Overload resolution] Prefer functions with fewer defaulted/variadic arguments.
When comparing two functions for overload resolution, break apart the
parameter lists to compare individual parameters rather than comparing
the tuples. This allows us to prefer functions with fewer arguments to
ones with more, defaulted or variadic arguments. That preference was
already encoded in the constraint optimizer, which led to some strange
behavior where the preference was expressed for function calls but not
for calls to initializers. Fixes rdar://problem/24128153.

The standard library change tweaks the anachronistic, unavailable
"print" variants somewhat. The only behavior change here is a slight
regression for cases like:

  print(a: 1, b: 2)

where we used to produce a diagnostic:

  Please wrap your tuple argument in parentheses: 'print((...))'

but we now get:

  argument labels '(a:, b:)' do not match any available overloads

However, this regression will happen at some point *anyway*, if
SE-0029 (or anything else that removes the implicit tuple splat
operation) goes through.
2016-02-05 11:41:01 -08:00
Max Moiseev
61c837209b Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-04 16:13:39 -08:00
Chris Lattner
8dedfb31e3 Add support for #file/#line, etc according to SE-0028. __FILE__ and friends
are still accepted without deprecation warning as of this patch.
2016-02-04 14:22:22 -08:00
gregomni
5ba28eda3d Replace use of getArchetype() in diagnoseGenericParameterErrors()
This is a quick follow-up to
<https://github.com/apple/swift/pull/1160>, to replace the becoming
deprecated getArchetype() with doing the same thing via calling through
to ArchetypeBuilder with a declContext.

Uses findGenericSubstitutions() to do so. So this site could take
advantage of destructuring of more complex params containing generics.
Right now, though, that never happens. For complex params the
(unfortunately, worse) diagnosis happens in diagnoseFailureForExpr() on
the argument expression before reaching here. I’d like to improve that
in future work.
2016-02-04 11:56:13 -08:00
Xi Ge
77b7180f1a Rename CodeCompletionTypeChecking.h to IDETypeChecking.h since it's used by more clients now. NFC 2016-02-04 11:09:21 -08:00
Slava Pestov
99b0e77d35 Merge pull request #1160 from gregomni/generic-func-args
[Sema] Extend callee diagnosis to complex args including generics, e.g. (Void) -> T
2016-02-03 22:55:15 -08:00
gregomni
6b30695869 Extend callee diagnosis to complex args including generics, e.g. (Void) -> T
Correctly determine callee closeness for func/ops that include generics
as part of more complicated parameters, i.e. tuple or closure args
containing generics as elements or args/results. Still only handling
single archetypes.

Also added code to check generic substitutions already made in the callee
parameters, which further helps diagnosis.
2016-02-03 22:54:19 -08:00
Jordan Rose
923b9a6201 Don't emit any check for #available of another platform.
Previously we treated the * platform as checking for the minimum
deployment target, but that's definitely unnecessary.

There is a bit of a hack here to avoid diagnosing the 'else' branch as
unreachable: if a constant true/false came from #available, ignore it.
2016-02-03 14:27:13 -08:00
practicalswift
87b98546e6 [gardening] Fix recently introduced typo: "availablity" → "availability" 2016-02-03 22:18:42 +01:00
Jordan Rose
5e0f4b704d [AST] Introduce AvailabilityContext to wrap VersionRange.
This is the beginning of the extension of the availability model
introduced in Swift 2.0 to support two interesting things: inlineable
code and binary frameworks not tied to an OS. The former is critical
to having a stable standard library that isn't shipped with a client app.

(For more information on both of these, see docs/LibraryEvolution.rst.)

The existing availability model enforces that API is not used unless
the developer has already guaranteed its existence. We want to reuse
this logic for these new purposes. Additionally, certain queries about
the AST are dependent on this type of information as well, e.g. "can I
assume this enum will not grow any additional cases?" If the enum comes
from the module being compiled, the answer is usually "yes", but not if
the code asking the question may be inlined into another binary!

(This latter purpose is currently served by ResilienceExpansion down at
the SIL level; my goal is to replace ResilienceExpansion with
AvailabilityContext. It's a bit heavier but would also allow additional
optimization in the future.)

This commit does not change any logic; it only wraps existing uses of
VersionRange in AvailabilityContext if they're not strictly referring to
the OS version.
2016-02-02 17:41:29 -08:00
Xi Ge
ae60159816 [ModulePrint] Add the initial implementation for printing synthesized extensions.
For a concrete type, members from its conforming protocols' extensions can be hard
to manually surface. In this commit, when printing Swift modules, we start to replicate these
extensions and synthesize them as if they are the concrete type's native extensions.

Credit to Doug for suggesting this practice.
2016-02-02 14:53:21 -08:00
Chris Lattner
35bce55e62 When diagnosing some problems with associated types, mark the decl invalid. When forming a type reference to an invalid type decl, have validateType return ErrorType instead of an apparently valid type. This silences some bogus downstream errors in code that references the decl.
This exposes some wierdness with while_parsing_as_left_angle_bracket where
one case the note is being is when resolveType returns a failure.  However,
resolveType can produce a failure without emitting a diagnostic, and this
can lead to us generating a note unattached to an error.  Just remove this
case.
2016-02-02 14:01:43 -08:00
Doug Gregor
6b0febf401 Merge pull request #1009 from gregomni/sr-547
[SR-547][Sema] Invalidate more parts of protocols involved in recursive definitions
2016-02-02 09:13:04 -08:00
practicalswift
10c31294d4 [gardening] Substitute "substitions" with "substitutions". 2016-02-02 10:19:33 +01:00
Slava Pestov
9ae2a5a90b Merge pull request #1151 from slavapestov/sil-parser-interface-types-cleanup
Move SIL parser to GenericFunctionTypes
2016-02-01 21:31:26 -08:00
Chris Lattner
8cc0ab170a fix a potential problem that Jordan noticed by inspection, NFC on the testsuite. 2016-02-01 21:02:00 -08:00
Chris Lattner
94dd92fcb8 Fix compiler_crashers 22725 & 28236 by reworking parameter parsing error
recovery a bit.
2016-02-01 20:50:32 -08:00
Slava Pestov
5b89f7fd6a SIL: Use interface types in the SIL parser
The SIL parser used PolymorphicFunctionType in two places:

- Internals of SILFunctionType parsing

- Overload selection for class_method / super_method / dynamic_method
  instructions

It is better to have Sema construct GenericFunctionType directly
in SIL mode. In particular, the overload selection logic is simpler
now, since it does not have to deal with the fact that
PolymorphicFunctionTypes do not canonicalize.

Mostly NFC, except the SIL printer output is a bit different; for a
generic method on a generic type, the type parameters all come first,
like ``<T><U> G<T> -> (U) -> ()'' -vs- ``<T> G<T> -> <U> (U) -> ()''.

Also, generic constraints look different, instead of ``<`Self` : P>``
we now have ``<Self where Self : P>''.

This patch has two consequences that will become important later:

- While code that constructs PolymorphicFunctionType still exists in
  Sema, the SIL parser was the last major component that *consumed*
  PolymorphicFunctionType.

- Everywhere we set SILFunction::ContextGenericParams, we now have
  a well-formed context GenericSignature available, allowing
  ContextGenericParams to be replaced by a GenericSignature
  eventually.
2016-02-01 20:49:14 -08:00
Slava Pestov
0b337cd912 Sema: Pass outer GenericSignature to checkGenericParamList(), NFC
Previously we would get this from the DeclContext, but this was
wrong in SIL mode. This was exposed by some other changes, but is
NFC for now.
2016-02-01 20:49:13 -08:00
Slava Pestov
86abcd262f Sema: Replace getInterfaceTypeFromInternalType() with ArchetypeBuilder::mapTypeOutOfContext(), NFC 2016-02-01 20:49:13 -08:00
Chris Lattner
6173170c33 fix SR-650: REGRESSION: Assertion failed
When we have a contextual type of Optional<SomeNominal>, we get overload
lookup results indicating that the found member needs to look through the
optional.  Do so!
2016-02-01 13:22:45 -08:00
Chris Lattner
d0a9479d46 Fix compiler_crashers/28246-swift-expr-propagatelvalueaccesskind.swift
Teach CSApply that InOutExpr around an UnresolvedType shouldn't propagate
lvalue access kinds.
2016-01-31 21:08:38 -08:00
saisi
6b3c5898e4 Fixed some niggling typos 2016-01-30 04:46:12 -05:00
Slava Pestov
a54864902b Merge pull request #1134 from gregomni/tuple-element-lvalue
[SR-628][Sema] Mixing lvalues and rvalues in tuple exprs is very unhappy.
2016-01-30 00:02:19 -08:00
Chris Lattner
a63be90828 fix compiler_crashers/28219-swift-lvaluetype-get.swift
Not all types are l-valuable, notably InoutType's.  This seems like a
weird restriction to put in the type checker, but it is the cleanest
solution to this.  The better solution would be to change how
inoutexpr/inouttype are represented completely... maybe someday.
2016-01-29 23:18:33 -08:00
Chris Lattner
ff34db7950 fix a few compiler crashers
These were due to CSDiags not reverting the semantic expr embedded in CollectionExprs
when retypechecking them.
2016-01-29 21:13:57 -08:00
Chris Lattner
061c7eb475 Merge pull request #1142 from Saisi/niggling_typos
Fixed niggling typos
2016-01-29 20:19:54 -08:00
saisi
535d400dc6 Fixed niggling typos 2016-01-29 23:16:25 -05:00
Chris Lattner
d12a4b988d Fix 28244-swift-valuedecl-isinstancemember.swift
Formerly we stopped type checking a PatternBindingDecl when it was marked
as invalid.  This prevented semantic analysis from doing things like expanding
"stored" properties in protocols into computed properties with getters and setter,
causing downstream problems.

Stop doing this, and instead do a bit of work to silence the downstream errors in
a more narrow way.
2016-01-29 14:32:55 -08:00
Slava Pestov
5841cb07a1 Sema: Fix type safety hole with inherited conformances
When checking for permitted uses of Self in the input type of a
protocol requirement's function type, if the parameter itself was
a function we would recurse into its input, and reject all uses
of Self in the parameter type's result. This was the wrong way
around, and in fact we should recurse into the result.

Here is a test case that used to compile successfully and crash;
now it is rejected by the type checker:

    protocol P {
      func f(a: Self -> ())
    }

    protocol Q : P {
      func g()
    }

    class C : P {
      func f(a: C -> ()) { // should not be allowed to witness P.f
        a(C())
      }
    }

    class B : C, Q {
      var x: Int = 17

      func g() {
        print(x)
      }
    }

    func f<T : Q>(t: T) {
      // T == B here
      // t.f has type <T : Q> (T -> ()) -> ()
      t.f({ $0.g() }) // but at runtime, $0 is a C not a B
    }

    f(B())
2016-01-29 12:18:39 -08:00
Slava Pestov
4d34bb1922 Sema: Refactor away SelfInResultType, NFC
SelfInResultType::DynamicSelf was unnecessary because we already
returned SelfUse::Result and handled it correctly if the witness
had a dynamic Self return type.

SelfInResultType::Ignore was only used for constructors, but it
is better to handle them just like FuncDecls with dynamic Self
returns.

Also, the additional VarDecl case was unnecessary.
2016-01-29 12:18:39 -08:00
gregomni
6d54eecd67 Mixing lvalues and rvalues in tuple exprs is very unhappy.
In SR-628 in particular, the problem was an assert that an AccessKind
was being set on a non-lvalue, but there were lots of asserts here in
various scenarios, the most common other ones being an AccessKind not
being set assertion by the ASTVerifier or lvalue-ness not matching
between tuple expr and tuple element expr.

This checks for lvalues in the tuple when a tuple indexing expr is built,
and if there are any, inserts load exprs into the lvalue elements to make all rvalues.
2016-01-29 08:15:03 -08:00
Doug Gregor
5726e7a329 [Sema] Eliminate a foolish little infinite loop I introduced. 2016-01-28 19:49:03 -08:00
Chris Lattner
f923123a89 Simplify some code, remove an obsolete comment (we don't have let/else anymore). 2016-01-28 15:35:05 -08:00
Joe Pamer
ca89d20fde Revert "Add '&' and '|' to the list of potentially symmetric operators."
This reverts commit b1a7ceaf4b.

Accounting for these operators can add complexity in some cases, so I'm
backing out this change pending a more holistic approach.
2016-01-28 13:26:51 -08:00
Doug Gregor
9a0241bb3b SE-0022: Address Jordan's review comments about #selector. 2016-01-28 12:09:57 -08:00
Joe Pamer
096ff9228f When trying out potential bindings for a given type variable, take greater measures not to try the same binding against a bound generic type more than once. Multiple attempts at bindings can result in massive slow downs in overload resolution, because we'll potentially post many duplicate results to the solution. (In cases such as "[0..<10, 0..<10, 0..<10, 0..<10, 0..<10]", for example.) 2016-01-28 11:02:26 -08:00
Joe Pamer
d7fb571855 When solving for type variable bindings, protect against trying the same (potentially unwrapped) binding twice. 2016-01-28 11:02:26 -08:00
Joe Pamer
b1a7ceaf4b Add '&' and '|' to the list of potentially symmetric operators. 2016-01-28 11:02:26 -08:00
Chris Lattner
f585b07db8 Merge pull request #1127 from gregomni/generic-func-args
[Sema] Improve diagnoses on args to generic members
2016-01-28 11:01:48 -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
gregomni
fc3a264ea9 Improve diagnoses on args to generic members
In both figuring out candidate closeness and in diagnosing generic
parameter errors, if the parameter is a GenericTypeParamType, get its
decl’s archetype to perform archetype substitutability checking upon.
2016-01-28 10:23:14 -08:00
Slava Pestov
27da265abb Refactor some random usages of contextual types, NFC 2016-01-27 23:22:33 -08:00
Slava Pestov
418154e160 Merge pull request #1069 from gregomni/sr-38
[SR-38][Sema] Stop emitting duplicate only-as-generic-constraint errors.
2016-01-27 23:01:09 -08:00
gregomni
da93f6cc6d Stop emitting most duplicated only-as-generic-constraint errors.
Set type repr's as invalid after diagnosing an unsupported protocol
to stop duplicate diagnoses.

There were two causes here. First, top-level variable
declarations were being checked once by the Decl checker, and then
again by the Stmt checker. (This caused SR-38.)

Second, the Stmt checker is called by an AST visitor itself, which
already calls it once per statement. Using the
UnsupportedProtocolVisitor here meant that each interior sub statement
would get visited multiple times. Added a setRecurseIntoSubstatements()
on the visitor, and set it to false for the Stmt checker. This keeps
from revisiting statements multiple times.
2016-01-27 20:34:29 -08:00
Adrian Prantl
ecd47e0a81 PlaygroundTransform: Use a global TmpNameIndex to avoid having multiple
temporaries with the same name in the same scope.

rdar://problem/24318554
2016-01-27 14:12:15 -08:00
Denis Vnukov
b72d0532eb Changed TypeChecker::callWitness(...) to use proper location for TupleExpr. 2016-01-27 13:43:42 -08:00