Commit Graph

411 Commits

Author SHA1 Message Date
Doug Gregor
49b833b51a [Type checker] Eliminate the 'literalConformanceProto' state on type variables.
The 'literalConformanceProto' field of
TypeVariableType::Implementation didn't take into account equivalence
classes of type variables. Eliminate it, and either look at the actual
expressions (for optimizing constraints during constraint generation)
or the actual constraints on a given type variable (for determining
whether to include optionals in the set of potential type variable
bindings).

(cherry picked from commit 6bdd9cfae5)
2016-10-13 16:22:01 -07:00
Doug Gregor
01fa24cc9b Speculatively revert "[Type checker] Eliminate the 'literalConformanceProto' state on type variables."
This reverts commit 6bdd9cfae5. This
commit *appears* to be breaking something in Dollar involving
inference with array literals and 'nil'; pull it back for more
investigation.
2016-10-12 09:20:16 -07:00
Doug Gregor
6bdd9cfae5 [Type checker] Eliminate the 'literalConformanceProto' state on type variables.
The 'literalConformanceProto' field of
TypeVariableType::Implementation didn't take into account equivalence
classes of type variables. Eliminate it, and either look at the actual
expressions (for optimizing constraints during constraint generation)
or the actual constraints on a given type variable (for determining
whether to include optionals in the set of potential type variable
bindings).
2016-10-11 17:09:13 -07:00
Doug Gregor
331937a129 [Type checker] Track defaulted constraints based on their locator. NFC
While, tracking defaulted constraints based on their type variable
usually works in practice, it can break if the type variable ends up
being equivalent to some other type variable that. Instead, record the
locators associated with Defaultable constraints where we used the
default, which are easier to work with during constraint application.
2016-10-11 17:09:13 -07:00
Doug Gregor
c2b9759cd3 Simplify ConstraintSystem::getFixedTypeRecursive and use it consistently.
We had a few places that were performing ad hoc variants of
ConstraintSystem::getFixedTypeRecursive(); simplify it's interface so
we can use it everywhere consistently. Fixes rdar://problem/27261929.
2016-10-11 17:08:52 -07:00
Pavel Yaskevich
054e3e4eb4 [Diagnostics] SR-2242: Fix diagnostic when argument label is omitted 2016-09-23 17:17:59 -07:00
Doug Gregor
e5b9ad7f64 [Type checker] Don't overflow array bounds with #fileLiteral *ahem*.
Fixes rdar://problem/26586984.
2016-09-21 23:08:58 -07:00
practicalswift
f250a2349b [gardening] Remove duplicate words. 2016-09-16 20:09:34 +02:00
practicalswift
b19481f887 [gardening] Fix 67 recently introduced typos 2016-09-16 11:16:07 +02:00
practicalswift
9185c052a9 [gardening] Fix inconsistent headers 2016-09-14 20:48:28 +02:00
Pavel Yaskevich
f590a1ba03 [Type Checker] Extend Path Consistency algorithm to cover collections
ExprCollector is extended to cover all generic collections instead of
only dictionary expressions. Contextual type propagation is extended
to support partial solving of collections embedded into coerce expressions.
2016-09-13 01:34:14 -07:00
Pavel Yaskevich
2011e502ad [Type Checker] Prevent Path Consistency algorithm from aborting too aggressively
Instead of failing shrinking when there are no solutions for current
sub-expression, let's restore overload domains for previously solved
sub-expressions and move on trying to solve next expression in the queue.
2016-08-26 17:21:04 -07:00
Pavel Yaskevich
8e04a84239 [Type checker] Introduce directional path consistency algorithm
DPC algorithm tries to solve individual sub-expressions and combine
resolved types as a way to reduce pre-existing OSR domains. Solving
is done bottom-up so each consecutive sub-expression tightens
possible solution domain even further.
2016-08-24 18:40:28 -07:00
Mishal Shah
a84704f4b5 Revert "[Type checker] Introduce directional path consistency algorithm" 2016-08-24 17:53:12 -07:00
Pavel Yaskevich
de51b01195 [Type checker] Introduce directional path consistency algorithm
DPC algoritm tries to solve individual sub-expressions and combine
resolved types as a way to reduce pre-existing OSR domains. Solving
is done bottom-up so each consecutive sub-expression tightens
possible solution domain even further.
2016-08-24 14:38:46 -07:00
Doug Gregor
f99904ac66 Eliminate the useless flag -enable-experimental-collection-casts.
This eliminates a pile of now-dead code in:
  * The type checker, where we no longer have special cases for bridging conversions
  * The expression ASTs, where we no longer need to distinguish bridging collection up/down casts
  * SILGen, which no longer uses

Still to come is the removal of the
_(set|dictionary)Bridge(From|To)ObjectiveC(Conditional)? entrypoints
from the standard library. They're still used by some tests.
2016-08-19 21:17:10 -07:00
Doug Gregor
51529ae888 Eliminate the -enable-id-as-any flag; it's always on now anyway.
Simplify e.g., ASTContext::getBridgedToObjC(), which no longer needs
the optional return.

Eliminate the now-unused constraint kind for checking bridging to
Objective-C.
2016-08-19 21:17:09 -07:00
Mark Lacey
2ef4a24c8e Fix typos in comments. 2016-08-07 23:43:54 -07:00
John McCall
a6e1e87585 Add implicit conversions and casts from T:Hashable <-> AnyHashable.
rdar://27615802
2016-08-04 23:13:27 -07:00
Doug Gregor
22287ddb58 [Type system] Infer 'Any' for array elements and dictionary values and 'AnyHashable' for dictionary keys.
The id-as-Any work regressed cases where Swift code could specify
heterogeneous collection literals, e.g.,

    var states: [String: Any] = [
      "California": [
        "population": 37_000_000,
        "cities": ["Los Angeles", "San Diego", "San Jose"],
      ],
      "Oregon": [
        "population": 4_000_000,
        "cities": ["Portland", "Salem", "Eugene"],
      ]
    ]

Prior to this, the code worked (when Foundation was imported) because
we'd end up with literals of type [NSObject : AnyObject].

The new defaulting rule says that the element type of an array literal
and the key/value types of a dictionary literal can be defaulted if no
stronger type can be inferred. The default type is:

  Any, for the element type of an array literal or the value type of a
  dictionary literal, or

  AnyHashable, for the key type of a dictionary literal.

The latter is intended to compose with implicit conversions to
AnyHashable, so the most-general inferred dictionary type is
[AnyHashable : Any] and will work for any plausible dictionary
literal.

To prevent this inference from diluting types too greatly, we don't
allow this inference in "top-level" expressions, e.g.,

  let d = ["a" : 1, "b" : "two"]

will produce an error because it's a heterogeneous dictionary literal
at the top level. One should annotate this with, e.g.,

  let d = ["a" : 1, "b" : "two"] as [String : Any]

However, we do permit heterogeneous collections in nested positions,
to support cases like the original motivating example.

Fixes rdar://problem/27661580.
2016-08-04 20:58:13 -07:00
Doug Gregor
87a5e4d8d8 [NFC] ConstrainSystem::getComputedBindings() is dead. Kill it. 2016-08-04 11:21:35 -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
Doug Gregor
604adff1bd [SE-0111] Capture argument labels directly in CallExpr.
Yet another step on the way to SE-0111, capture the argument labels
(and their locations) directly in CallExpr, rather than depending on
them being part of the tuple argument.
2016-07-25 23:14:41 -07:00
Mark Lacey
3ba204694e Do not suppress optional coercion in operators with a nil-literal operand.
This is the hack that has been used to reject things like:
  var i: Int = ...
  if i == nil { }
in the past.

The hack is inconsistent with normal treatment of mixed optional &
non-optional operands, and will be replaced with a warning instead of
treating it as a failure to type check.

There is still a case that we still fail type checking on -
Unsafe*Pointer<> compares to nil. That will be addressed by a separate
commit.

The new warning will be addressed by rdar://problem/27457457. When the
new warnings are updated the test cases modified here will again need to
be updated based on the text of the new warning.
2016-07-21 22:39:33 -07:00
Alex Hoppen
095a68b195 [Sema] Disallow accessing enum elements as instance members
This implements SE-0036.
2016-07-20 19:13:58 +02:00
Ben Langmuir
c8f7da4de1 [CodeCompletion] Support a narrow case for producing trailing closures directly
This adds a narrow special case in code-completion for control-flow-like
methods such as DispatchQueue().sync that are () -> (), to add a new
completion where the trailing closure is immediately expanded rather
than having to invoke placeholder expansion as a second step.

rdar://problem/26628804
2016-07-01 14:16:57 -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
Doug Gregor
e2632c1cfa [Code completion] Teach code completion to use declarations for postfix completions.
Code completion had the ability to use declarations to provide better
code completion results for postfix completions, e.g., calls to
functions/methods, but it wasn't trying to get these declarations from
anywhere. Now, get these declarations from the solution to the
constraint system.

The impetus for this is to use default-argument information from the
declaration rather than the type, but plumbing this information
through also means that we get proper "rethrows" annotations, covered
by <rdar://problem/21010193>, and more specific completions in a
number of other places.

Fixes <rdar://problem/21010193>.
2016-06-16 11:44:42 -07:00
Doug Gregor
2b7d0f9379 [Type checker] Extract default argument information from the callee declaration.
Rather than relying on the embedding of default argument information
into tuple types (which is gross), make sure that the various clients
(type checker, type checker diagnostics, constraint application) can
dig out the callee declaration and retrieve that information from
there.
2016-06-09 17:35:12 -07:00
Doug Gregor
01682af23a Revert "[Type checker] Be more rigorous about extracting argument labels from calls."
This reverts commit 93dac8f759.
2016-06-03 16:29:31 -07:00
Doug Gregor
93dac8f759 [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.

This is a slightly-pared-back version of
3753d779bc that isn't so rigid in its
interpretation of ASTs. I'll tighten up the semantics over time.
2016-06-03 14:45:21 -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
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
Jordan Rose
16f857c78c [Sema] Use a TypeLoc for conversions with contextual types.
With a TypeLoc, we have a chance to offer diagnostics or even fix-its
to the contextual type, even though it's not represented by an
expression in the constraint system. This commit mostly just passes it
through, without attempting to use it anywhere or even pass a real
TypeLoc (with a valid TypeRepr).

(It does drop the contextual type parameter from
typeCheckExpressionShallow, since there were zero callers using it.)

No functionality change...yet.
2016-04-21 13:36:53 -07:00
practicalswift
f02cf29742 [gardening] Fix recently introduced typo: "specifiy" → "specify" 2016-04-12 10:31:38 +02:00
Xi Ge
0b50648263 [sema] Add a fixit for label-mismatch tuple patterns in for-each statement. rdar://25671800
In the following code example, compiler emits an error of "cannot express tuple conversion...". However,
this is trivially fixable by adding multiple labels in the tuple pattern of the for-each statement. This
commit adds such fixit.

func foo(array : [(some: Int, (key: Int, value: String))]) {
  for (i, (k, v)) in array {
  }
}
2016-04-11 19:09:59 -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
Josef Willsher
de18967992 [Sema] Improved error message for static functions on existential metatypes (#2127)
Type level lookups can fail because the lookup is on an existential
metatype, like `MyProtocol.staticMethod(_:)` is invalid; however the
error message is unclear: “static member 'staticMethod(_:)' cannot be
used on instance of type ‘MyProtocol.Protocol’”.

This fix checks the base of member lookups that failed with the reason
UR_TypeMemberOnInstance for being existential metatypes. It produces
the clearer message “static member ‘staticMethod(_:)’ cannot be used on
protocol metatype ‘MyProtocol.Protocol’”. This change makes it clear
that the use of a static member on the *existential* metatype is the
problem.
2016-04-10 19:03:20 -07:00
John McCall
563057ca98 When performing member lookup into a type during type-checking,
immediately discard as non-viable any declarations that cannot be
called due to argument-label mismatch.

This heuristic already existed, but it was badly out-of-date vs.
the current language rules on argument-passing.  Change it to use
the standard argument matching algorithm.

This greatly reduces the number of overloads we consider for certain
kinds of expression, most importantly explicit initialization syntax
('T(x)').  Ordinary type-matching will quickly reject such calls,
but backtracking will discard this rejection.  Thus this heuristic
can greatly decrease the total work done by the type-checker when
something else in the system is causing a combinatorial explosion.

The diagnostic changes in the test-suite seem acceptable to me.

Shout-out to Doug for pointing out multiple places where I didn't
need to reinvent the wheel.
2016-04-08 09:39:04 -07:00
gregomni
098f8e0ebf [SR-839][Sema] Better fixits for optional expressions
In member ref expressions, if the base is optional, and the expected
expression result is either optional or unknown, suggest a fixit that
makes it into an optional chain expr rather than force unwrapping.

Since in many cases the actual fixit is emitted during diagnosis, and
thus, while type checking sub exprs with no contextual type specified
(so nothing to check for preferring optionality), we also need an
additional flag to pass down from FailureDiagnosis for whether we
prefer to fix as force unwrapping or optional chaining.

I attempted to do this same job via providing a convert type but
setting the ConvertTypeIsOnlyAHint flag on the type checker, but
unfortunately there are a lot of other moving parts that look at that
type, even if it is only supposed to be a hint, so an additional flag
to the CS ended up being cleaner.
2016-03-01 22:57:24 -08:00
Chris Lattner
b2fabdadcc move diagnoseArgumentLabelError to CSDiags.cpp now that it is the only client. 2016-02-12 17:33:22 -08:00
Chris Lattner
accffe5a11 now that argument relabeling fixits are handled by CSDiags, remove a bunch of
code from Fix and ConstraintSystem.  NFC.
2016-02-12 17:28:52 -08:00
Jordan Rose
36a44cf308 Replace uses of llvm::Fixnum with llvm::PointerEmbeddedInt.
The two types are nearly identical, and Fixnum is only in the Swift branches of LLVM,
not in mainline LLVM.

I do want to add ++ to PointerEmbeddedInt and fix some of this ugliness, but that'll
have to go through LLVM review, so it might take a bit.
2016-02-11 09:52:07 -08:00
saisi
6b3c5898e4 Fixed some niggling typos 2016-01-30 04:46:12 -05:00
practicalswift
45049f2763 [gardening] Fix recently introduced typos 2016-01-22 22:37:54 +01: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
Joe Pamer
fb03b7974a Pave the way for contracting edges between closure parameter bindings. 2016-01-22 12:34:33 -08:00
Joe Pamer
37032b2a58 Take first steps towards simplifying the constraint graph by performing edge contraction. 2016-01-22 12:34:32 -08:00