Commit Graph

449 Commits

Author SHA1 Message Date
Huon Wilson
07c5ab8fb2 Implement \ syntax for Swift key paths.
This introduces a few unfortunate things because the syntax is awkward.
In particular, the period and following token in \.[a], \.? and \.! are
token sequences that don't appear anywhere else in Swift, and so need
special handling. This is somewhat compounded by \foo.bar.baz possibly
being \(foo).bar.baz or \(foo.bar).baz (parens around the type), and,
furthermore, needing to distinguish \Foo?.bar from \Foo.?bar.

rdar://problem/31724243
2017-05-01 16:06:15 -07:00
Joe Groff
3d178be169 Merge pull request #8875 from jckarter/keypaths
Keypaths
2017-04-21 17:51:17 -07:00
Slava Pestov
b0c1799f45 Sema: Merge CSGen's canSatisfy() with TypeChecker::typesSatisfyConstraint() 2017-04-20 00:37:38 -07:00
Slava Pestov
f4b91cd118 AST: Remove unused 'resolver' argument from TypeBase::getSuperclass() 2017-04-20 00:37:38 -07:00
Joe Groff
595e0e4ede Merge branch 'master' into keypaths 2017-04-19 18:38:24 -07:00
swift-ci
62d077d2d3 Merge pull request #8776 from DougGregor/operator-availability-31592529 2017-04-14 09:57:22 -07:00
Doug Gregor
c739ab127c [Constraint Solver] Respect availability in operator-performance hacks.
We have various hacks in the constraint solver to improve the
compile-time performance characteristics of operators. Some of those
didn't respect availability annotations, causing us to incorrectly
choose an unavailable operator when available options exist.

Fixes rdar://problem/31592529.
2017-04-14 09:24:13 -07:00
Slava Pestov
db58e02cb2 Sema: Hook up layout constraints to the solver
There were various problems with layout constraints either
being ignored or handled incorrectly. Now that I've exercised
this support with an upcoming patch, there are some fixes
here.

Also, introduce a new ExistentialLayout::getLayoutConstriant()
which returns a value for existentials which are class-constrained
but don't have a superclass or any class-constrained protocols;
an example would be AnyObject, or AnyObject & P for some
non-class protocol P.

NFC for now, since these layout-constrained existentials cannot
be constructed yet.
2017-04-13 21:17:05 -07:00
Mark Lacey
03e2040891 [Constraint system] Remove redundant duplicates of favored constraints.
When creating disjunctions with favored constraints in constraint
optimization, we actually ended up duplicating the constraint that we
favor, resulting with extra constraints in the disjunction.

Noticed while debugging other issues.
2017-04-12 16:01:19 -07:00
Joe Groff
7eebb27153 Sema: Infer the specific type of a key path literal from the mutability of the resolved components. 2017-04-10 16:06:40 -07:00
Joe Groff
964dc0e174 Sema: (wip) Overload resolution for keypath subscripts.
TODO: Some diagnostic regressions:
test-macosx-x86_64/Compatibility/tuple_arguments.swift
test-macosx-x86_64/Constraints/diagnostics.swift
test-macosx-x86_64/Constraints/tuple_arguments.swift
test-macosx-x86_64/expr/unary/keypath/keypath.swift
test-macosx-x86_64/expr/unary/selector/selector.swift
2017-04-09 16:38:02 -07:00
Joe Groff
fc23781906 Sema: First pass at type-checking Swift key paths.
TODO:

- Select the KeyPath subclass corresponding to the write capability of the key path components
- Figure out an issue with unresolved solutions being chosen with contextually-typed keypaths
- Diagnostic QoI
2017-04-04 11:31:15 -07:00
Joe Groff
a5ca6ccd61 Restructure KeyPathExpr to allow more kinds of components.
Expand the representation in anticipation of more kinds of components. NFC intended yet.
2017-04-04 11:31:15 -07:00
Joe Groff
eb5d006e40 Rename ObjCKeyPathExpr -> KeyPathExpr.
We can use the same general shape of expression for native key paths.
2017-04-04 11:31:15 -07:00
Xi Ge
3ad7df273f [SourceKit] DocSupport: constraint extensions provide default implementation too. rdar://25692947 (#8398) 2017-03-28 15:55:39 -07:00
Xi Ge
6e3698f7e8 SourceKit: for DocSupport, report default implementations of inherited protocols in sub-protocol's extensions. rdar://25692947 (#8394)
For instance:

protocol P1 { 
  func foo() 
}
protocol P2 : P1 { 
  func bar() 
}
extension P2 { 
  func foo() {} 
}

We report the foo() in P2's extension as the default implementation of foo() declared in P1.
2017-03-28 12:10:29 -07:00
Xi Ge
fb842c789a IDE: Hide the implementation detail of ResolvedMemberResult. NFC (#8385) 2017-03-27 20:47:20 -07:00
Xi Ge
5663f6799f IDE: Simplify/Refactor some code that collects the default implementations in protocol extensions. NFC (#8381) 2017-03-27 18:14:45 -07:00
Mark Lacey
4a4e0f4ab8 [Constraint solver] Minor tweak to where constraint propagation runs.
No real functionality at this point - move the point of invocation for
the moment.
2017-03-21 19:32:32 -07:00
practicalswift
83526fe224 [gardening] Use .is<T>() instead of .getAs<T>() if the result is not needed 2017-03-20 22:54:01 +01:00
Mark Lacey
041a25ecf1 [Constraint solver] More progress on the constraint solver type map. 2017-03-14 21:56:13 -07:00
Slava Pestov
d73bb452ec Sema: Fix 'super' method calls inside local generic functions
It is generally useful to allow 'super' method calls inside a
closure, so you can have overrides that do things like:

  override func foo() {
    doSomething { super.foo() }
  }

However this didn't work if the closure was a local generic
function because we didn't map the 'super' type into the
right generic context.
2017-03-08 20:10:58 -08:00
Slava Pestov
80e3cbab08 Sema: Fix 'super' calls from methods returning 'Self'
We have a quirk where TypeBase::getSuperclass() on DynamicSelfType
returns the underlying class type, and not the superclass of the
underlying class type. As a result, we would emit a SuperRefExpr
whose type was the type of 'self' and not the type of 'super'.

Fixes <rdar://problem/30853768>.
2017-03-04 16:37:39 -08:00
Xi Ge
c9dad65c81 IDETypeChecking: fix a memory leak. (#7849) 2017-03-01 16:45:23 -08:00
Joe Groff
c6dc44d5de Merge pull request #7841 from jckarter/leading-dot-pattern-fallback
Sema: Let `.foo` patterns fall back to being ExprPatterns if they don't match an enum case.
2017-03-01 08:55:25 -08:00
Joe Groff
fc16cb5dda Sema: Let .foo patterns fall back to being ExprPatterns if they don't match an enum case.
This lets you match `case .foo` when `foo` resolves to any static member, instead of only a `case`, albeit without the exhaustiveness checking and subpattern capabilities of proper cases. While we're here, adjust the type system we set up for unresolved patterns embedded in expressions so that we give better signal in the error messages too.
2017-02-28 21:51:39 -08:00
Mark Lacey
f32824296a Add an empty constraint propagation pass.
This is disabled by default but enabled under the frontend option
-propagate-constraints.

The idea here is to have a pass that enforces local consistency in our
constraint system, in order to reduce the domains of constraint
variables, speeding up the solving of the constraint system.

The initial focus will be on reducing the size of the disjunctions for
function overloads with the hope that it substantially improves the
performance of type checking many expressions.
2017-02-23 15:04:07 -08:00
Slava Pestov
5296d02485 AST: More include-what-you-use gardening 2017-02-12 00:51:26 -08:00
Slava Pestov
cf4043b668 AST: Get rid of old form of Type::subst()
First, add some new utility methods to create SubstitutionMaps:

- GenericSignature::getSubstitutionMap() -- provides a new
  way to directly build a SubstitutionMap. It takes a
  TypeSubstitutionFn and LookupConformanceFn. This is
  equivalent to first calling getSubstitutions() with the two
  functions to create an ArrayRef<Substitution>, followed by
  the old form of getSubstitutionMap() on the result.

- TypeBase::getContextSubstitutionMap() -- replacement for
  getContextSubstitutions(), returning a SubstitutionMap.

- TypeBase::getMemberSubstitutionMap() -- replacement for
  getMemberSubstitutions(), returning a SubstitutionMap.

With these in place, almost all existing uses of subst() taking
a ModuleDecl can now use the new form taking a SubstitutionMap
instead. The few remaining cases are explicitly written to use a
TypeSubstitutionFn and LookupConformanceFn.
2017-02-03 19:55:40 -08:00
Doug Gregor
21ee10b63b [Type checker] Detangling the constraints of interpolated string literals.
Constraint generation for interpolated string literals was
meticulously producing a constraint system that included all of the
generated calls to init(stringInterpolationSegment:). While accurate,
this is completely unnecessary (because the
ExpressibleByStringInterpolation protocol allows *anything* to be
interpolated) and leads to large, intertwined constraint systems
where:

(1) There are two additional type variables per string interpolation
segment, and
(2) Those type variables form a bridge between the string
interpolation's type variable and the type variables of each string
interpolation segment, and
(3) init(stringInterpolationSegment:) tends to be overloaded (4
overloads, down from 17 due to
29353013c0)

which left each string interpolation as a large connected component
with big disjunctions.

Drop the calls to init(stringInterpolationSegment:) from the
constraint system. This eliminates two type
variables per segment (due to (1) going away), and breaks the bridge
described in (2), so that each string interpolation segment is
treated as an separate connected component and, therefore, will be
solved independently. The actual resolution of
init(stringInterpolationSegment:) overloads is pushed to the
constraint application phase, where we are only dealing with concrete
types and *much* smaller constraint systems.

Fixes rdar://problem/29389887 more thoroughly.
2017-01-30 10:03:14 -08:00
Doug Gregor
207fffc6fe [Type checker] Limit the number of type variables introduced for placeholders.
The type checker introduces fresh type variables for editor
placeholders that are encountered in the source. If there are many
such editor placeholders, we'll create a large number of type
variables with very little context, which can cause poor scaling in
the type checker. Since we get very little information out of these
type variables, artificially limit the number of type variables we
create (to 2) and rotate through them.

Another piece of rdar://problem/29389887.
2017-01-28 20:59:24 -08:00
John McCall
39b65f49a0 Track the actual DC of a member access in the constraint system.
Without this, CSGen/CSSimplify and CSApply may have differing
opinions about whether e.g. a let property is settable, which
can lead to invalid ASTs.

Arguably, a better fix would be to remove the dependency on the
exact nested DC.  For example, we could treat lets as settable
in all contexts and then just complain later about invalid
attempts to set them.  Or we could change CSApply to directly
use the information it already has about how an l-value is used,
rather than trying to figure out whether it *might* be getting set.
But somehow, tracking a new piece of information through the
entire constraint system seems to be the more minimal change.

Fixes rdar://29810997.
2017-01-26 00:14:21 -05:00
Colin Douglas Howell
fb235125fb [CSGen] Fix for exponential dictionary literal behavior in SR-3668
In ConstraintGenerator::visitDictionaryExpr(), if the dictionary_expr has a
contextual type which is also a dictionary type, use it to add a new type
constraint for each of the dictionary_expr's elements. This has a huge effect
on solver performance for dictionary literals with elements that have
overloading. The approach closely follows that used in
ConstraintGenerator::visitArrayExpr(), which has included a similar
optimization (from git commit a22b391) for over two and a half years.

I've also added a couple of new test cases which would trigger the bug without
this fix.
2017-01-21 23:47:01 -08:00
swift-ci
808c48401f Merge pull request #6743 from swiftix/wip-partial-pre-specializations-wip-layout-constraints 2017-01-12 10:12:44 -08:00
Pavel Yaskevich
f142568eaa [Diagnostics] Improve diagnostics for expressions involving ternary operators
FailureDiagnosis::visitApplyExpr is going to attempt to type-check
argument expression multiple times - with and without allowing free
type variables, since first type-check might mutate AST if (sub-expression
type-checks correctly) it's required to fix up ternary operations
represented as IfExpr to it's original condition form, because IfExpr
is going to convert Bool into implicit call `(Bool) -> () -> Int1`
upon successful type-check, which is not handled by either
ConstraintGenerator nor ExprRewriter because they don't expect
well-formed type-checked IfExpr is input.

Resolves: <rdar://problem/29850459>.
2017-01-11 21:25:45 -08:00
Roman Levenstein
29180ca1a0 Add support for layout requirements with layout constraints.
This commit introduces new kind of requirements: layout requirements.

This kind of requirements allows to expose that a type should satisfy certain layout properties, e.g. it should be a trivial type, have a given size and alignment, etc.
2017-01-11 19:21:45 -08:00
Slava Pestov
7731d4c6cb Sema: Remove some unnecessary calls to getCanonicalType() 2017-01-08 21:01:13 -08:00
practicalswift
6d1ae2a39c [gardening] 2016 → 2017 2017-01-06 16:41:22 +01:00
Mark Lacey
7f64b6853f Improve handling of types in constraint system.
Several fixes in order to make handling of types more consistent.

In particular:

- Expression types used within the constraint system itself always use
  the type map.

- Prior to calling out to any TypeChecker functions, the types are
  written back into the expression tree. After the call, the types are
  read back into the constraint system type map.

- Some calls to directly set types on the expressions are reintroduced
  in places they make sense (e.g. when building up new expressions that
  are then passed to typeCheckExpressionShallow).

ConstraintSystem::setType() is still setting the type on the expression
nodes at the moment, because there is still some incorrect handling of
types that I need to track down (in particular some issues related to
closures do not appear to be handled correctly). Similarly, when we
cache the types in the constraint system map, we are not clearing them
from the expression tree yet.

The diagnostics have not been updated at all to use the types from
the constraint system where appropriate, and that will need to happen as
well before we can remove the write from ConstraintSystem::setType()
into the expression and enable the clearing of the expression tree type
when we cache it in the constraint system.
2017-01-05 11:54:34 -08:00
Slava Pestov
7258861d73 Merge pull request #6515 from xedin/crasher-28588
[QoI] While merging equivalence classes don't forget to merge fixed types (if any).
2017-01-03 19:35:47 -08:00
Joe Groff
796df2dc44 Merge pull request #6429 from jckarter/type-of-by-overload-resolution
`withoutActuallyEscaping`
2017-01-03 18:47:29 -08:00
Slava Pestov
7db9ac9e3f Merge pull request #6518 from jtbandes/a-chain-is-only-as-strong-as-its-weakest-link
[CSGen] handle ForceValueExpr in LinkedExprAnalyzer
2017-01-03 18:39:14 -08:00
Jacob Bandes-Storch
25cb143b8e [CSGen] handle ForceValueExpr in LinkedExprAnalyzer
The default behavior was looking *through* the ForceValueExpr, so in this test case the LinkedExprAnalyzer thought it was dealing with Optional<Double> rather than Double. Resolves SR-1122.
2017-01-01 02:36:51 -08:00
Pavel Yaskevich
fac59ce4ee [Diagnostics] Improve diagnostics of self assignment of the anonymous closure parameters 2016-12-31 19:00:30 -08:00
Pavel Yaskevich
d37e93d3c2 [QoI] While merging equivalence classes don't forget to merge fixed types (if any)
Otherwise merging of the representative equivalence classes leaves constraint
system and graph disconnected, which might leave to incorrect solutions.
2016-12-31 01:29:04 -08:00
Pavel Yaskevich
047f7e092f [QoI] Allow computeAssignDestType to return UnresolvedType to facilitate diagnostics
Instead of returning empty type when RValue destination of the assignment
could not be determined, let's return it unresolved directly instead and
let it be handled by coerceToType, which is going to produce special expression
(UnresolvedTypeConversionExpression) which facilitates better diagnostics.
2016-12-24 18:05:07 -08:00
Joe Groff
0c9297862f Sema: Handle type-checking for withoutActuallyEscaping.
withoutActuallyEscaping has a signature like `<T..., U, V, W> (@nonescaping (T...) throws<U> -> V, (@escaping (T...) throws<U> -> V) -> W) -> W, but our type system for functions unfortunately isn't quite that expressive yet, so we need to special-case it. Set up the necessary type system when resolving an overload set to reference withoutActuallyEscaping, and if a type check succeeds, build a MakeTemporarilyEscapableExpr to represent it in the type-checked AST.
2016-12-22 17:51:26 -08:00
Doug Gregor
e97ab635ea [Constraint solver] Separate bridging conversions from other conversions.
Previously, bridging conversions were handled as a form of "explicit
conversion" that was treated along the same path as normal
conversions in matchTypes(). Historically, this made some
sense---bridging was just another form of conversion---however, Swift
now separates out bridging into a different kind of conversion that is
available only via an explicit "as". This change accomplishes a few
things:

* Improves type inference around "as" coercions. We were incorrectly
  inferring type variables of the "x" in "x as T" in cases where a
  bridging conversion was expected, which cause some type inference
  failures (e.g., the SR-3319 regression).

* Detangles checking for bridging conversions from other conversions,
  so it's easier to isolate when we're applying a bridging
  conversion.

* Explicitly handle optionals when dealing with bridging conversions,
  addressing a number of problems with incorrect diagnostics, e.g.,
  complains about "unrelated type" cast failures that would succeed at
  runtime.

Addresses rdar://problem/29496775 / SR-3319 / SR-2365.
2016-12-21 13:46:14 -08:00
Doug Gregor
642c8ed3eb [Constraint solver] Collapse getBaseTypeFor(Array|Set)Type into is(Array|Set)Type.
Follow the pattern set by isDictionaryType() of performing the query
and extracting the underlying key/element types directly. We often
need both regardless. NFC
2016-12-21 13:46:13 -08:00
Slava Pestov
4ed17f0f63 AST: Add a new 'isBeingValidated' flag to replace a couple of other flags
Previously, validateDecl() would check if the declaration had an
interface type and use that as an indication not to proceed.

However for functions we can only set an interface type after
checking the generic signature, so a recursive call to validateDecl()
on a function would "steal" the outer call and complete validation.

For generic types, this meant we could have a declaration with a
valid interface type but no generic signature.

Both cases were problematic, so narrow workarounds were put in
place with additional new flags. This made the code harder to
reason about.

This patch consolidates the flags and establishes new invariants:

- If validateDecl() returns and the declaration has no interface
  type and the isBeingValidated() flag is not set, it means one
  of the parent contexts is being validated by an outer recursive
  call.

- If validateDecl() returns and the declaration has the
  isBeingValidated() flag set, it may or may not have an interface
  type. In this case, the declaration itself is being validated
  by an outer recursive call.

- If validateDecl() returns and the declaration has an interface
  type and the isBeingValidated() flag is not set, it means the
  declaration and all of its parent contexts are fully validated
  and ready for use.

In general, we still want name lookup to find things that have an
interface type but are not in a valid generic context, so for this
reason nominal types and associated types get an interface type as
early as possible.

Most other code only wants to see fully formed decls, so a new
hasValidSignature() method returns true iff the interface type is
set and the isBeingValidated() flag is not set.

For example, while resolving a type, we can resolve an unqualified
reference to a nominal type without a valid signature. However, when
applying generic parameters, the hasValidSignature() flag is used
to ensure we error out instead of crashing if the generic signature
has not yet been formed.
2016-12-19 01:38:23 -08:00