Commit Graph

998 Commits

Author SHA1 Message Date
Pavel Yaskevich
70c59afb40 [ConstraintSystem] Move "outer" candidates handling to simplifyMemberConstraint
Further simplify `addOverloadSet` and move "outer" candidate handling
to the only place where it comes up - `simplifyMemberConstraint`.
Also move constraint generation for choices into a separate method.

This is a stepping stone on the path to enable attaching fixes to
the overload choices.
2019-03-12 14:46:35 -07:00
Pavel Yaskevich
c2590c0dec [ConstraintSystem] Simplify addOverloadSet
- Remove whole disjunction favoring which has no effect;
- Avoid creating separate disjunction for "inner" choices,
  which is going to be flattened later anyway.
2019-03-08 18:25:32 -08:00
Doug Gregor
1d6cb4f28f [Constraint solver] Remove unused ConstraintSystem::getUnboundBindOverloads() 2019-03-05 21:40:48 -08:00
Doug Gregor
b83bb70bac [Constraint solver] Look through optional binding for overload sets.
When we’re trying to find the overload set corresponding to a particular
type variable, look through “optional object of” constraints that represent
the use of ? binding or ! forcing. This allows us to find overload sets
when referring to, e.g., @objc optional protocol requirements.
2019-03-05 21:40:48 -08:00
Doug Gregor
b993c6e076 [Constraint solver] Move tryOptimizeGenericDisjunction() into partitioning
This narrow favoring rule makes more sense as part of disjunction
partitioning, because it is not dependent on the use site at all and
should only kick in when other options fail.
2019-03-05 15:01:46 -08:00
Doug Gregor
fae2d1b2ac Merge pull request #23088 from DougGregor/solver-disjunction-favoring
[Constraint solver] Generalize disjunction favoring
2019-03-05 14:41:56 -08:00
Doug Gregor
d2c7c8d5ee [Constraint solver] Enable favoring of disjunction constraints during solving
Allow constraints to be favored during solving, and unwound after exiting
that particular solver scope. We're not using this yet.
2019-03-05 10:30:51 -08:00
Pavel Yaskevich
f70c43a028 Merge pull request #23085 from xedin/diag-OoO-arguments
[ConstraintSystem] Diagnose out-of-order arguments via fixes
2019-03-05 00:52:23 -08:00
Pavel Yaskevich
5dd5454a75 [CSSimplify] Determine if argument is out-of-order while matching labels
Instead of rerouting out-of-order into re-labeling during diagnostics,
let's do that as part of the label matching algorithm.
2019-03-04 20:03:30 -08:00
Doug Gregor
ae4949d27c [Constraint solver] Remove a hand-rolled clone of getUnboundBindOverloadDisjunction
Use the real one instead.
2019-03-04 15:59:59 -08:00
Doug Gregor
c0917c90d2 [Constraint solver] Revert the "common type" optimization.
The "common type" optimization isn't really buying us anything at this
point, because we're not able to make much use of the common structure
often enough. Revert the "common type" optimization for now... I'll
bring it back when there's enough optimization infrastructure around
it to make it compelling.
2019-03-04 15:00:45 -08:00
Doug Gregor
8151a34f6a [Constraint solver] Merge the two areConservativelyCompatibleArgumentLabels()
The decl-based version is only used by the OverloadChoice-based version
anyway.
2019-03-03 22:51:33 -08:00
Doug Gregor
603d5d6f20 [Constraint solver] Synchronize argument label setting/retrievable.
The walker that was setting argument labels was looking through ! and ?
postfix expressions, but the lookup code itself was not, leading to missed
opportunities for filtering based on argument labels. Generalize the
transformation that maps from the function expression down to the locator
for which we will retrieve argument labels.
2019-03-01 21:45:39 -08:00
Doug Gregor
233cf6ffa6 [Constraint solver] Address feedback from Pavel and Slava. 2019-03-01 20:54:48 -08:00
Doug Gregor
bdc961d8c6 [Constraint solver] Do argument label matching during apply simplification.
When simplifying a function application constraint, check the argument
labels for that application against the disjunction containing the overload
set, disabling any overloads with mis-matching labels. This is staging for
several different directions:

* Eliminating the argument label matching from performMemberLookup, where it
does not belong
* More aggressively filtering the overload set when we have some concrete
information about argument types
* Identifying favored constraints when we have some concrete information
about argument types

At present, the only easily-visible effect of this change is that
we now properly handle argument label matching for non-member functions.
2019-02-28 23:53:08 -08:00
Doug Gregor
5f99d91ea8 [Constraint solver] Compute common apply result type in the solver.
Constraint generation for function application expressions contains a simple
hack to try to find the common result type for an overload set containing
callable things. Instead, perform this “common result type” computation
when simplifying an applicable function constraint, so it is more
widely applicable.
2019-02-27 23:30:03 -08:00
Doug Gregor
a2e9c60e9b [Constraint solver] Remove dead declarations.
These functions appear to have been part of an implementation of constraint
propagation that was removed or never committed; remove them. NFC
2019-02-27 23:30:02 -08:00
Doug Gregor
1ab417cd8e [Constraint system] Compute and use a common type among overloads.
Given an overload set, attempt to compute a "common type" that
abstracts over all entries in the overload set, providing more
structure for the constraint solver.
2019-02-22 21:53:34 -10:00
Pavel Yaskevich
75b5824bf9 Merge pull request #22480 from xedin/rdar-47871590
[ConstraintSystem] Diagnose conditional requirement failures via fixes
2019-02-11 14:58:08 -08:00
Pavel Yaskevich
6fd1600534 [ConstraintSystem] Diagnose conditional requirement failures via fixes
Extend existing `RequirementFailure` functionality to support
conditional requirement failures. Such fixes are introduced
only if the parent type requirement has been matched successfully.

Resolves: rdar://problem/47871590
2019-02-08 11:16:54 -08:00
Slava Pestov
e18a61c3b4 Sema: Remove unused parameter from getTypeOfReference() 2019-02-07 23:46:31 -05:00
Pavel Yaskevich
9a1e92ec0a [AST] Add getDecl parameter to Expr::isTypeRerefence
So it could be extended to support not yet fully type-checked
AST when used by constraint system solver.
2019-02-05 18:09:51 -08:00
Pavel Yaskevich
7d830cee8b [ConstraintSystem] Add a fix to detect invalid partial application
Currently supported only partial applications of instance methods
marked as `mutating`.
2019-01-25 13:29:11 -08:00
Pavel Yaskevich
e604261805 [ConstraintSystem] Track AST depth information directly
Instead of storing information about expression depths in the
solver state (which gets recomputed for salvage) let's track
it directly in constraint system, which also gives solver
access to it when needed e.g. for fixes.
2019-01-23 18:44:53 -08:00
Pavel Yaskevich
49c40d92f6 [AST] Augment getDepthMap with information about parent expressions
Which is very useful for the solver because otherwise it'd have to
compute and store this information twice.
2019-01-23 18:21:07 -08:00
Pavel Yaskevich
ffa49969f5 [ConstraintSystem] Mark generic parameter bindings as potentially incomplete by default
This helps to postpone attempting bindings related to generic
parameters with all else being equal.

Consider situation when function has class requirement on its
generic parameter. Without such requirement solver would infer
sub-class for `T`. But currently when requirement is present base
class is inferred instead, because when bindings for such generic
parameter are attempted early single available binding at that
point comes from the requirement.

```swift
class BaseClass {}
class SubClass: BaseClass {}

struct Box<T> { init(_: T.Type) {} }

func test<T: BaseClass>(box: Box<T>) -> T.Type {
  return T.self
}

test(box: .init(SubClass.self)) // `T` expected to be `SubClass`
```

Resolves: [SR-9626](https://bugs.swift.org/browse/SR-9626)
Resolves: rdar://problem/47324309
2019-01-16 14:07:36 -08:00
Slava Pestov
33871548b3 Clean up TypeVariableType::Implementation::mustBeMaterializable(), etc 2019-01-12 14:10:11 -05:00
Pavel Yaskevich
74a8ee177e [Diagnostics] Diagnose missing members via fixes
Try to fix constraint system in a way where member
reference is going to be defined in terms of its use,
which makes it seem like parameters match arguments
exactly. Such helps to produce solutions and diagnose
failures related to missing members precisely.

These changes would be further extended to diagnose use
of unavailable members and other structural member failures.

Resolves: rdar://problem/34583132
Resolves: rdar://problem/36989788
Resolved: rdar://problem/39586166
Resolves: rdar://problem/40537782
Resolves: rdar://problem/46211109
2019-01-09 17:29:49 -08:00
Pavel Yaskevich
60fb2bf94e [CSFix] Try to fix missing member by defining it based on use
If lookup couldn't find anything matching given name, let's try to
fake its presence based on how member is being used. This is going
to help (potentially) type-check whole expression and diagnose the
problem precisely.
2019-01-09 14:35:27 -08:00
Robert Widmann
426fe886dc [SR-8272] Drop the last remnants of LogicValue
Removes the _getBuiltinLogicValue intrinsic in favor of an open-coded
struct_extract in SIL.  This removes Sema's last non-literal use of builtin
integer types and unblocks a bunch of cleanup.

This patch would be NFC, but it improves line information for conditional expression codegen.
2018-12-19 23:14:59 -05:00
Pavel Yaskevich
637692ccf8 [ConstraintSystem] NFC: Define {activate, deactivate}Constraint to make that logic reusable 2018-12-18 10:24:11 -08:00
Slava Pestov
2f61230627 Sema: Remove vestigial rvalue varargs code path 2018-12-16 01:02:56 -05:00
Joe Groff
b701dc4f10 Merge pull request #21277 from jckarter/archetype-subclass-api
Push ArchetypeType's API down to subclasses.
2018-12-13 06:36:09 -08:00
Joe Groff
89979137fc Push ArchetypeType's API down to subclasses.
And clean up code that conditionally works only with certain kinds of archetype along the way.
2018-12-12 19:45:40 -08:00
Doug Gregor
88d34a1c7c [Constraint solver] De-priority SIMD operators.
The new SIMD proposal introduced a number of new operators, the presence of
which causes more "expression too complex" failures. Route around the
problem by de-prioritizing those operators, visiting them only if no
other operator could be chosen. This should limit the type checker
performance cost of said operators to only those expressions that need
them OR that already failed to type-check.

Fixes rdar://problem/46541800.
2018-12-11 16:34:37 -08:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08:00
Mark Lacey
56a636066b [ConstraintSystem] Make checkTypeOfBinding do one job rather than two.
Hoist the call to hasNilLiteralConstraint into the one caller that
cares about this.
2018-11-29 21:00:32 -08:00
Pavel Yaskevich
783f0345f7 Merge pull request #20693 from xedin/forward-autoclosure-diagnostic
[CSDiagnostics] Add custom diagnostic for invalid @autoclosure forwarding
2018-11-22 11:52:03 -08:00
Rintaro Ishizaki
5df5711b67 [CodeCompletion] Rework getOperatorCompletions() (#20632)
In postfix completion, for operator completion, we do:

  1. Type check the operand without applying it, but set the resolved
     type to the root of the expression.
  2. For each possible operators:
      i. Build temporary binary/postfix expression
      ii. Perform type checking to see whether the operator is applicable 

This could be very slow especially if the operand is complex.

* Introduce `ReusePrecheckedType` option to constraint system. With
  this option, CSGen respects pre-stored types in expressions and doesn't
  take its sub-expressions into account.
  * Improve type checking performance because type variables aren't
     generated for sub-expressions of LHS (45511835)
  * Guarantee that the operand is not modified by the type checker because
     expression walkers in `CSGen` doesn't walk into the operand.

* Introduce `TypeChecker::findLHS()` to find LHS for a infix operator from
  pre-folded expression. We used to `foldSequence()` temporary
  `SequenceExpr` and find 'CodeCompletionExpr' for each attempt.
  * No need to flatten folded expression after initial type-checking.
  * Save memory of temporary `BinaryExpr` which used to be allocated by
    `foldSequence()`.
  * Improve accuracy of the completion. `foldSequence()` recovers invalid
    combination of operators by `left` associative manner (with
    diagnostics). This used to cause false-positive results. For instance,
    `a == b <HERE>` used to suggest `==` operator. `findLHS()` returns
    `nullptr` for such invalid combination.

rdar://problem/45511835
https://bugs.swift.org/browse/SR-9061
2018-11-22 21:20:51 +09:00
Pavel Yaskevich
cc780e3292 [ConstraintSystem] Make sure that @autoclosure argument detection works for subscripts/members
Currently logic in `matchCallArguments` could only detect argument
being an @autoclosure parameter for normal calls and operators.

This patch extends it to support subscripts and unresolved member calls.
2018-11-21 12:17:25 -08:00
Pavel Yaskevich
82bd1b9871 [CSBindings] Couple of small PotentialBindings cleanups
- Use `int` instead of `unsigned int` to represent # of non-defaultable bindings.
  Because the formula is `-(Total - Defaultable)` which could only be `0` or negative.

- Increase number of defaultable bindings iff the binding is accepted.
2018-11-13 11:59:44 -08:00
Pavel Yaskevich
061eec53a2 Merge pull request #20486 from xedin/rdar-45659733-2.0
[CSBindings] Detect situations when type variable bindings could be i…
2018-11-12 13:23:05 -08:00
Dan Zheng
2863b6cc64 Gardening for @dynamicMemberLookup. (#20498)
* Gardening for `@dynamicMemberLookup`.

- Unify code style of `@dynamicMemberLookup` and `@dynamicCallable` implementations.
  - Use consistent variable names, diagnostic messages, doc comments, etc.
- Move `@dynamicMemberLookup` test to `test/attr` directory.
2018-11-11 21:54:19 -05:00
Pavel Yaskevich
fa1e2d33aa [CSBindings] Detect situations when type variable bindings could be incomplete
When `bind param` constraint is associated with a given
type variable a set of bindings collected for it is
potentially incomplete, because binding gathering doesn't
look through related type variables. Which means that
such type variable has to be de-prioritized until
`bind param` constraint is resolved or there is just
nothing else to try, otherwise there is a risk that
solver would skip some of the valid solutions.

This only affects type variable that appears one the
right-hand side of the `bind param` constraint and
represents result type of the closure body, because
left-hand side gets types from overload choices.

Resolves: rdar://problem/45659733
2018-11-09 15:27:27 -08:00
Pavel Yaskevich
c4c9cc32fb Revert "[CSBindings] Detect situations when type variable bindings could be incomplete"
This reverts commit 4f708890c1.
2018-11-09 11:50:19 -08:00
Dan Zheng
2a4e1b83fd Implement @dynamicCallable. (#20305)
* Implement dynamically callable types (`@dynamicCallable`).

- Implement dynamically callable types as proposed in SE-0216.
  - Dynamic calls are resolved based on call-site syntax.
  - Use the `withArguments:` method if it's defined and there are no
    keyword arguments.
  - Otherwise, use the `withKeywordArguments:` method.
- Support multiple `dynamicallyCall` methods.
  - This enables two scenarios:
    - Overloaded `dynamicallyCall` methods on a single
      `@dynamicCallable` type.
    - Multiple `dynamicallyCall` methods from a `@dynamicCallable`
      superclass or from `@dynamicCallable` protocols.
  - Add `DynamicCallableApplicableFunction` constraint. This, used with
    an overload set, is necessary to support multiple `dynamicallyCall`
    methods.
2018-11-09 09:49:14 -08:00
Brent Royal-Gordon
9bd1a26089 Implementation for SE-0228: Fix ExpressibleByStringInterpolation (#20214)
* [CodeCompletion] Restrict ancestor search to brace

This change allows ExprParentFinder to restrict certain searches for parents to just AST nodes within the nearest surrounding BraceStmt. In the string interpolation rework, BraceStmts can appear in new places in the AST; this keeps code completion from looking at irrelevant context.

NFC in this commit, but keeps code completion from crashing once TapExpr is introduced.

* Remove test relying on ExpressibleByStringInterpolation being deprecated

Since soon enough, it won’t be anymore.

* [AST] Introduce TapExpr

TapExpr allows a block of code to to be inserted between two expressions, accessing and potentially mutating the result of its subexpression before giving it to its parent expression. It’s roughly equivalent to this function:

  func _tap<T>(_ value: T, do body: (inout T) throws -> Void) rethrows -> T {
    var copy = value
    try body(&copy)
    return copy
  }

Except that it doesn’t use a closure, so no variables are captured and no call frame is (even notionally) added.

This commit does not include tests because nothing in it actually uses TapExpr yet. It will be used by string interpolation.

* SE-0228: Fix ExpressibleByStringInterpolation

This is the bulk of the implementation of the string interpolation rework. It includes a redesigned AST node, new parsing logic, new constraints and post-typechecking code generation, and new standard library types and members.

* [Sema] Rip out typeCheckExpressionShallow()

With new string interpolation in place, it is no longer used by anything in the compiler.

* [Sema] Diagnose invalid StringInterpolationProtocols

StringInterpolationProtocol informally requires conforming types to provide at least one method with the base name “appendInterpolation” with no (or a discardable) return value and visibility at least as broad as the conforming type’s. This change diagnoses an error when a conforming type does not have a method that meets those criteria.

* [Stdlib] Fix map(String.init) source break

Some users, including some in the source compatibility suite, accidentally used init(stringInterpolationSegment:) by writing code like `map(String.init)`. Now that these intializers have been removed, the remaining initializers often end up tying during overload resolution. This change adds several overloads of `String.init(describing:)` which will break these ties in cases where the compiler previously selected `String.init(stringInterpolationSegment:)`.

* [Sema] Make callWitness() take non-mutable arrays

It doesn’t actually need to mutate them.

* [Stdlib] Improve floating-point interpolation performance

This change avoids constructing a String when interpolating a Float, Double, or Float80. Instead, we write the characters to a fixed-size buffer and then append them directly to the string’s storage.

This seems to improve performance for all three types, but especially for Double and Float80, which cannot always fit into a small string when stringified.

* [NameLookup] Improve MemberLookupTable invalidation

In rare cases usually involving generated code, an overload added by an extension in the middle of a file would not be visible below it if the type had lazy members and the same base name had already been referenced above the extension. This change essentially dirties a type’s member lookup table whenever an extension is added to it, ensuring the entries in it will be updated.

This change also includes some debugging improvements for NameLookup.

* [SILOptimizer] XFAIL dead object removal failure

The DeadObjectRemoval pass in SILOptimizer does not currently remove reworked string interpolations as well as the old design because their effects cannot be described by @_effects(readonly). That causes a test failure on Linux. This change temporarily silences that test. The SILOptimizer issue has been filed as SR-9008.

* Confess string interpolation’s source stability sins

* [Parser] Parse empty interpolations

Previously, the parser had an odd asymmetry which caused the same function to accept foo(), but reject “\()”. This change fixes the issue.

Already tested by test/Parse/try.swift, which uses this construct in one of its throwing interpolation tests.

* [Sema] Fix batch-mode-only lazy var bug

The temporary variable used by string interpolation needs to be recontextualized when it’s inserted into a synthesized getter. Fixes a compilation failure in Alamofire.

I’ll probably follow up on this bug a bit more after merging.
2018-11-02 19:16:03 -07:00
Pavel Yaskevich
4f708890c1 [CSBindings] Detect situations when type variable bindings could be incomplete
When `bind param` constraint is associated with a given type
variable a set of bindings collected for it is potentially
incomplete, because binding gathering doesn't look through related
type variables. Which means that such type variable has to be
de-prioritized until `bind param` constraint is resolved
or there is just nothing else to try, otherwise there is a
risk that solver would skip some of the valid solutions.

Resolves: rdar://problem/45659733
2018-10-31 17:58:54 -07:00
Greg Titus
d20fdf5f82 Merge pull request #19920 from gregomni/8757
[Sema][QoI] Call out missing conformances in protocol witness candidates.
2018-10-22 16:39:51 -07:00
Mark Lacey
5b4a332b0e [ConstraintSystem] Sort the designated types based on actual argument types.
In cases where we have multiple designated types, sort the types that
were designated for this operator based on any information we can
gather about actual argument types at usage sites.

We can consider extending this further in a future commit to ignore
designated types when we have concrete type information that we are
confident of.
2018-10-21 13:14:27 -07:00