Commit Graph

71 Commits

Author SHA1 Message Date
Allan Shortlidge
6f55aa4170 Tests: Remove -disable-availability-checking in tests that use opaque types.
Use the `%target-swift-5.1-abi-triple` substitution to compile the tests for
deployment to the minimum OS versions required for use of opaque types, instead
of disabling availability checking.
2024-10-19 19:39:18 -07:00
Pavel Yaskevich
2c9d05991f [CSBindings] Prevent BindingSet::isViable from dropping viable bindings
I think the original idea was to elide `Array<$T>` if there is
a binding a resolved generic arguments i.e. `Array<Float>`, but
the check doesn't account for the fact that bindings could be
of different kinds and there are some implicit conversions that
could be missed if we remove the bindings.

For example, given the following constraints:

`Array<$T0> conv $T1`
`$T1 conv Array<(String, Int)>`

`$T0` can be a supertype of `Array<$T0>` and subtype of `Array<(String, Int)>`.

The solver should accept both types as viable bindings because the
`$T0` could be bound to `(key: String, value: Int)` and that would
match `Array<(String, Int)>` conversion.
2024-09-16 09:54:12 -07:00
Pavel Yaskevich
6ca4a3da4d [Tests] Add a test-case that regresses if generic arguments are attempted sooner
This is related to 22e0f4a3d6.

Binding inference doesn't mark type variables that appear in
dependent member chains as "adjacent" which means that type
variables that represent generic arguments cannot be attempted
sooner due to incomplete information provided by the inference.

To fix this we'd need to remove `findInferrableTypeVars` and
replace its uses with `Type::getTypeVariables(...)`. This is
a risky change that would require some evaluation because it
could end breaking existing code but it would make sure that
for cases like `Row<$T0> conv $T1.ArrayLiteralElement` `$T0`
always gets associated with `$T1`.
2024-09-05 15:07:58 -07:00
Pavel Yaskevich
32d265154f [ConstraintSystem] Add cache for conformance lookups
`lookupConformance` request is not cached and constraint solver
performs a lot of them for the same type (i.e. during disjunction
solving), let's try to cache previously performed requests to
see whether additional memory use is worth the performance benefit.
2023-09-20 00:59:22 +01:00
Anthony Latsis
f76f6acbf0 Revert "Sema: Emit diagnostics when walking into collection literals with defaulted types"
This reverts commit f608802cfe.
2023-04-20 21:55:40 +03:00
Anthony Latsis
593c6a3887 Merge pull request #60592 from AnthonyLatsis/migrate-test-suite-to-gh-issues-5
Gardening: Migrate test suite to GH issues p. 5
2022-08-20 04:53:48 +03:00
Anthony Latsis
da8d035b0b Gardening: Migrate test suite to GH issues: Constraints (2/5) 2022-08-19 06:43:11 +03:00
Sima Nerush
f608802cfe Sema: Emit diagnostics when walking into collection literals with defaulted types
Resolves https://github.com/apple/swift/issues/60011

Gardening: clean up `checkTypeDefaultedCollectionExpr` function
2022-08-15 22:45:21 -06:00
Anthony Latsis
fbac0c4c34 Add regression test to close #43503 2022-07-09 16:47:55 +03:00
Holly Borla
12459cff80 [Diagnostics] Print 'any' in diagnostic arguments. 2022-03-05 14:26:45 -08:00
Hamish Knight
449537e2ff [test] Add overloaded init array test case
This uncovered some faulty CSRanking logic in
one of my refactorings.
2021-09-17 10:52:45 +01:00
Pavel Yaskevich
7ce37dd14d [TypeChecker] NFC: Adjust test-cases improved by changes in binding inference 2020-07-15 20:50:50 -07:00
Pavel Yaskevich
0ecedfa5ea Revert "[ConstraintSystem] Make it possible to infer subtype bindings through argument conversions"
Reverts apple/swift#30006. It caused a regression that we'd like to address before re-landing:

```swift
struct X {
  var cgf: CGFloat
}

func test(x: X?) {
  let _ = (x?.cgf ?? 0) <= 0.5
}
```

This reverts commit 0a6b444b49.
This reverts commit ed255596a6.
This reverts commit 3e01160a2f.
This reverts commit 96297b7e39.

Resolves: rdar://problem/60185506
2020-03-07 20:16:56 -08:00
Pavel Yaskevich
96297b7e39 [CSStep] Always attempt literal bindings in diagnostic mode
In case of contextual failures such bindings could produce
better solutions with fewer fixes.
2020-02-21 17:47:39 -08:00
Pavel Yaskevich
a1643d94f7 [Diagnostics] NFC: Update all of the improved test-cases 2019-09-13 22:35:52 -07:00
Pavel Yaskevich
c30845fa74 [ConstraintSystem] Detect and diagnose missing generic arguments
Introduce a fix to detect and diagnose situations when omitted
generic arguments couldn't be deduced by the solver based on
the enclosing context.

Example:

```swift
struct S<T> {
}

_ = S() // There is not enough context to deduce `T`
```

Resolves: rdar://problem/51203824
2019-05-29 16:39:41 -07:00
Pavel Yaskevich
b9a0ca6afb [ConstraintSystem] Detect and diagnose conversion failures related to collection element types
Detect and diagnose a contextual mismatch between expected
collection element type and the one provided (e.g. source
of the assignment or argument to a call) e.g.:

```swift
let _: [Int] = ["hello"]

func foo(_: [Int]) {}
foo(["hello"])
```
2019-05-14 17:33:11 -07: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
Ding Ye
617e057f03 [Sema] Avoid merging type variables that can have different results in CS.
This patch avoids merging type variables inside UnresolvedMemberExpr
and those outside, because they may not always be equivalent in CS.

Resolves: SR-8385.
2018-07-27 21:46:12 +10:00
Anthony Latsis
4099e85da6 [Diagnostics & Tests] SR-6052 Prevent nil capitalization (#16256)
And provide better semantic background by surrounding 'nil' in ticks when it is referred to as a value

Added missing tests for certain cases involving nil capitalization
2018-05-03 09:10:30 -07:00
Mark Lacey
9385dbb3fb Fix exponential type checking of tuple literals.
This fixes two easy cases where we would go exponential in type
checking tuple literals.

Instead of generating a conversion to a single type variable (which
results in one large constraint system), we generate a conversion ot
the same type that appears in the initializer expression (which for
tuples is a tuple type, which naturally splits the constraint system).

I experimented with trying to generalize this further, but ran into
problems getting it working, so for now this will have to do.

Fixes rdar://problem/20233198.
2018-03-26 14:46:03 -07:00
Ben Cohen
e2cc88269e Remove underscore from ArrayProtocol 2018-01-14 20:23:20 -08:00
Doug Gregor
ffb0d55b35 Eliminate extraneous uses of -enable-experimental-conditional-conformances 2017-12-18 22:56:22 -08:00
Robert Widmann
1d6f11ab54 Refactor ArrayExpr visitor for better QoI
Also remove mention of the word “contextual” type from the diagnostic
that rewrites array literals into dictionary literals and scale back
the scope of the diagnostic.  This method was catching and
mis-diagnosing too many errors that could better be handled by invalid
conversion diagnostics.
2017-12-15 18:20:36 -05:00
Doug Gregor
dc8b970051 [SE-0143] Eliminate assertions blocking the use of conditional conformances.
Early on in the development of conditional conformances, we put in a bunch
of assertions for code that uses `conformsToProtocol()` but wasn't handling
conditional conformances. Now, `conformsToProtocol()` handles conditional
conformances by default, and these assertions are tripping up code
that would work.

Remove the assertions and add test cases that used to trip up the
assertions (but now work).
2017-12-04 11:28:00 -08:00
Mark Lacey
37cb6a80b3 Make Type::join return Any by default.
For the moment, update the sole caller to not infer Any in cases where
neither argument was Any. This is in part because not all the cases are
handled here and the result of inferring Any will be to miss appropriate
bindings in certain cases. It is also in part because by inferring Any
we may end up deferring diagnostics until later in a function, which may
result in very hard to understand diagnostics for users.

This will be revisted once all the cases are properly handled here.
2017-09-24 16:20:00 -07:00
Mark Lacey
5770748b56 Eliminate name duplication in test case. 2017-09-14 15:22:11 -07:00
Mark Lacey
524b7f2a78 [Constraint system] Properly infer types for collections of vars.
When we saw lvalue- or inout-types we were not appropriately looking at
the underlying types when performing a join. As a result we would infer
Any in cases where we should have inferred a common supertype.

rdar://problem/31127419
2017-07-14 17:12:01 -07:00
Pavel Yaskevich
4e6677e7c4 [QoI] Improve contextual error diagnostics related to calls
Currently some contextual errors are discovered too late
which leads to diagnostics of unrelated problems like argument
mismatches, these changes attempt to improve the situation
and try to diagnose contextual errors related to calls
before everything else.

Resolves: SR-5045, rdar://problem/32934129
2017-06-26 13:12:32 -07:00
Slava Pestov
fa155bf1d1 Sema: Rework typeCheckBinding() to use the new foundSolution() callback
Record the initializer type as soon as we have a solution, before
it is applied, and get the type from the constriant system instead
of from the final type checked expression.

Note that the coerceToMaterializable() was unnecessary, since we
always coerce the value to an rvalue type with coerceToType().

Eventually coerceToMaterializable() should go away.

This is mostly NFC, except using the result of simplifyType() rather
than the type of the final expression changes some diagnostics where it
appears we were previously losing sugar.

Also this accidentally fixes a crasher. Unfortunately the underlying
issue is still there (applying a solution has bugs with opened
existentials "leaking" out) -- this merely masks the problem by
getting the initializer type directly from the constriant system.
2017-05-24 17:21:28 -07:00
Slava Pestov
d63bf4ee41 Sema: Fix for bogus ParenType showing up in deduced associated types
When matching inputs of a function type, be sure to
strip off ParenType sugar so that we don't end up
with ParenTypes in associated type witnesses.

This fixes various issues with SE-0110.

Fixes <rdar://problem/32214649>.
2017-05-17 00:39:46 -07:00
Ben Cohen
ea2f64cad2 [stdlib] Add Sequence.Element, change ExpressibleByArrayLiteral.Element to ArrayLiteralElement (#8990)
* Give Sequence a top-level Element, constrain Iterator to match

* Remove many instances of Iterator.

* Fixed various hard-coded tests

* XFAIL a few tests that need further investigation

* Change assoc type for arrayLiteralConvertible

* Mop up remaining "better expressed as a where clause" warnings

* Fix UnicodeDecoders prototype test

* Fix UIntBuffer

* Fix hard-coded Element identifier in CSDiag

* Fix up more tests

* Account for flatMap changes
2017-05-14 06:33:25 -07:00
Toni Suter
09a56c16fd [SR-4347] default to Any? instead of Any if there is a nil literal 2017-04-02 13:26:13 +02:00
Toni Suter
604553fe76 [SR-4347] added more test cases 2017-03-26 14:39:02 +02:00
Toni Suter
d630c3fa87 [SR-4347] Improve inference of optional supertypes 2017-03-25 07:44:33 +01:00
Mark Lacey
00cc26004b [Sema] Penalize conversions to Any.
We previously penalized bindings to Any, and that resulted in
inappropriately rejecting solutions where we bind a decl that is
explicitly typed Any. That penalty was removed in
170dc8acd7, but that has led to a variety
of source compatibility issues.

So now, we'll reintroduce a penalty for Any-typed things, but instead of
penalizing bindings (which happen both because of explicitly-typed
values in the source, and implicitly due to attempting various types for
a particular type variable), penalize casts, which are always present in
some form in the source.

Thanks go to John for the suggestion.

Fixes
  SR-3817 (aka rdar://problem/30311052)
  SR-3786 (aka rdar://problem/30268529)
  rdar://problem/29907555
2017-02-02 17:37:02 -08:00
Slava Pestov
1b92e72ab1 AST: Fix Type::join() to do the right thing with class metatypes
Fixes <rdar://problem/30233451>.
2017-01-27 13:18:15 -08:00
David Farler
b7d17b25ba Rename -parse flag to -typecheck
A parse-only option is needed for parse performance tracking and the
current option also includes semantic analysis.
2016-11-28 10:50:55 -08:00
Doug Gregor
e045429471 [Type Checker] Improve interface to TypeChecker::conformsToProtocol().
This function had a weird, pre-ProtocolConformanceRef interface that
returned true when the type conformed to the protocol, then had a
separate indirect return value for the concrete conformance (if there
is one). Refactor this API, and the similar
TypeChecker::containsProtocol(), to produce an optional
ProtocolConformanceRef, which is far more idiomatic and easier to
use. Push ProtocolConformanceRef into a few more places. Should be NFC
2016-11-14 16:00:58 -08:00
Doug Gregor
ba06709eca [Constraint solver] Dependent members don't "involve type variables".
The constraint solver tries not to solve for type variables that
"involve other type variables", which handles the case where we have
seen a constraint that mentions the type variable under consideration
as well as a different type variable, but in a constraint that we
cannot capture in a binding. Solving for such type variables too early
can lead to missed solutions, so we avoid it.

Tweak the logic for this computation to not consider type variables
mentioned within dependent member types (e.g., $T0.Iterator.Element),
because such types do not affect type inference at all, and therefore
shouldn't prevent solving for the type variable in question.
2016-11-05 23:20:28 -07:00
practicalswift
b19481f887 [gardening] Fix 67 recently introduced typos 2016-09-16 11:16:07 +02:00
Doug Gregor
78b7bb4c4b [Type checker]: Implement 'join' for optional types and a special case for 'nil'.
The join operation for optional types is straightforward to define/implement:

  join(T?, U)  ::= join(T, U)?
  join(T, U?)  ::= join(T, U)?
  join(T?, U?) ::= join(T, U)?

As a special case in the constraint solver, handle the join of a 'nil'
literal with a non-ExpressibleByNilLiteral-conforming concrete type
'T' to produce 'T?'. This allows us, e.g., infer [String?] for the
expressions

  ["hello", nil]

and

   true ? "hello" nil

for example. Fixes rdar://problem/16326914.
2016-08-19 10:46:59 -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
Michael Ilseman
c37751ae96 [noescape by defaul] make noescape the default
This flips the switch to have @noescape be the default semantics for
function types in argument positions, for everything except property
setters. Property setters are naturally escaping, so they keep their
escaping-by-default behavior.

Adds contentual printing, and updates the test cases.

There is some further (non-source-breaking) work to be done for
SE-0103:

- We need the withoutActuallyEscaping function
- Improve diagnostics and QoI to at least @noescape's standards
- Deprecate / drop @noescape, right now we allow it
- Update internal code completion printing to be contextual
- Add more tests to explore tricky corner cases
- Small regressions in fixits in attr/attr_availability.swift
2016-07-29 13:49:08 -07:00
Mark Lacey
12db9071d1 Use ExpressibleByArrayLiteral rather than _ArrayProtocol for test.
Addressing feedback from Dmitri on commit
8ed813080e.
2016-07-29 07:01:42 -07:00
Mark Lacey
8ed813080e Fix crash during type checker diagnostic emission.
We were crashing attempting to diagnose the case where we cannot assign
an array literal to a type conforming to _ArrayProtocol because we don't
know the element types of the conforming type.

We still don't give a great diagnostic for this, so I've
opened (rdar://problem/27594154) to track improving it.

Resolves rdar://problem/25563498.
2016-07-28 12:00:34 -07:00
John McCall
c8c41b385c Implement SE-0077: precedence group declarations.
What I've implemented here deviates from the current proposal text
in the following ways:

- I had to introduce a FunctionArrowPrecedence to capture the parsing
  of -> in expression contexts.

- I found it convenient to continue to model the assignment property
  explicitly.

- The comparison and casting operators have historically been
  non-associative; I have chosen to preserve that, since I don't
  think this proposal intended to change it.

- This uses the precedence group names and higherThan/lowerThan
  as agreed in discussion.
2016-07-26 14:04: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
Manav Gabhawala
7928140f79 [SE-0046] Implements consistent function parameter labels by discarding extraneous parameter names and adding _ where necessary 2016-04-06 20:21:58 -04:00
practicalswift
9eb2ee0638 [gardening] Fix accidental double spaces 2016-02-14 17:30:44 +01:00