Commit Graph

75 Commits

Author SHA1 Message Date
Pavel Yaskevich
d83ec7b3a5 [Diagnostics] Diagnose existential mismatch in a literal collection element position
If key or value of a literal collection expression doesn't conform
to protocol(s) expected by the contextual existential type, let's
diagnose that via a tailed collection mismatch fix instead of a
generic conformance one.

Resolves: rdar://103045274
2025-05-28 14:33:18 -07:00
Pavel Yaskevich
c84a34677a [AST] Special handling for existentials with superclass and marker protocols
Even if protocol is not self-conforming it should be okay to produce
a conformance based on superclass if protocol bounds of the existential
are all marker protocols.

Superclass concrete conformance is wrapped into an inherited conformance
in such cases to reference the existential.
2024-03-07 13:05:40 -08:00
Slava Pestov
fbab90b89a Sema: Fix crash when pre-checking expression of the form P(<<literal>>) where P is a protocol
Fixes https://github.com/apple/swift/issues/61517
2022-10-14 21:29:51 -04:00
Anthony Latsis
7fc8377e1c Gardening: Migrate test suite to GH issues: Constraints (1/5) 2022-08-17 15:21:51 +03:00
Luciano Almeida
1505d7cc14 [Diagnostic][Sema] Record locator with OptionalPayload dropped for contextual mismatch fixes for existentials 2022-03-16 18:31:50 -03:00
Holly Borla
12459cff80 [Diagnostics] Print 'any' in diagnostic arguments. 2022-03-05 14:26:45 -08:00
Anthony Latsis
d36aecca49 Diag: Make 'could_not_use_member_on_existential' less assertive 2022-02-23 10:24:51 +03:00
Holly Borla
c2594d1338 [FrontendOptions] Remove the -enable-explicit-existential-types flag. 2022-02-17 17:54:59 -08:00
Holly Borla
d971d489d6 [Type System] With explicit existential types, make sure existential
metatypes always wrap the constraint type directly, and the instance
type of an existential metatype is an existential type.
2022-01-13 19:30:44 -08:00
Abdul Ajetunmobi
f8c737b1ec SR-13976: Improve compiler error message: "partial application of ‘mutating’ method is not allowed” 2021-10-06 19:59:09 +01:00
Pavel Yaskevich
cf13e292e7 [CSBindings] Account for literal bindings when checking "subtype of existential" property
It's important to know whether a binding set has all of its bindings
as subtypes of some existential type(s), type variables like that
should be delayed.

Incremental binding inference introduced a bug into computation of
this property by checking only directly inferable bindings, but
it's also important to check that there are no literal requirements
that can produce bindings, because that would mean that type variable
can never be just a subtype of existential type(s).

Resolves: rdar://77570994
2021-05-26 10:10:35 -07:00
Pavel Yaskevich
4f19ba2c2a [CSSimplify] Teach transitive conformance check about Unsafe{Mutable}RawPointer conversions 2021-04-09 10:27:17 -07:00
Pavel Yaskevich
2137e1bafd [TypeChecker] NFC: Add a test-case to test condition requirements interaction with transitive conformance checks 2021-04-08 16:02:32 -07:00
Pavel Yaskevich
ea9539d47f [CSSimplify] Add AnyHashable check to simplifyTransitivelyConformsTo
Just like `Optional` and `UnsafePointer` argument could be implicitly
converted to `AnyHashable`.
2021-04-08 13:41:25 -07:00
Pavel Yaskevich
ae8efa38d5 [TypeChecker] NFC: Add a couple of tests for inference with optional/pointer promotion 2021-03-31 17:26:24 -07:00
Pavel Yaskevich
fa5c7120ef [ConstraintSystem] Ignore value-to-optional conversions to correctly detect conformance failures
If there is a conformance failure related to existential conversion
let's ignore that fact that there could be an implicit value-to-optional
conversion involved, because it's not the main issue in cases like
that.

Resolves: rdar://problem/70814576
2020-11-03 15:51:55 -08:00
Holly Borla
7f2d4c0a99 [CSApply] When applying constraint fixes for a solution, only coalesce
fixes of the same kind.
2019-11-11 10:08:25 -08:00
Pavel Yaskevich
d90117bb8a [Diagnostics] Remove argument handling from conformance failures
Argument-to-Parameter mismatch handles conformance failures
related to arguments, so the logic in `MissingConformanceFailure`
which wasn't entirely correct is now completely obsolete.

Resolves: rdar://problem/56234611
2019-10-14 00:34:37 -07:00
Greg Titus
93aa4baccc Remove FIXME and workaround for long fixed '??' bug 2019-08-13 11:57:44 -07:00
Pavel Yaskevich
5b22e4b69a [TypeChecker] NFC: Add a test-case for rdar://problem/50512161 2019-06-14 15:10:33 -07:00
Pavel Yaskevich
6b35f5df4d [TypeChecker] Don't try to validate generic requirements when unbound generic types are involved
If one of the generic parameters is missing let's give solver a
chance to diagnose the problem, otherwise there is a risk of failing
type resolution and not producing any diagnostics.

Resolves: rdar://problem/50099849
2019-05-31 15:14:05 -07:00
Pavel Yaskevich
17643a30e0 [ConstraintSystem] Move missing contextual protocol detection to matchExistentialTypes 2019-05-17 12:53:27 -07:00
Pavel Yaskevich
d4e8d583ae Revert "[ConstraintSystem] Use missing conformance fix to diagnose contextual failures" 2019-05-17 12:45:55 -07:00
Pavel Yaskevich
d5c561b44e [ConstraintSystem] Move missing contextual protocol detection to matchExistentialTypes 2019-05-15 15:37:36 -07:00
Slava Pestov
a3c15f2f6b Sema: References to TypeDecls should always be TypeExpr
In a few corner cases we built DeclRefExpr and MemberRefExpr
for references to types. These should just be TypeExpr so that
SILGen doesn't have to deal with it.

This also fixes a bug where a protocol typealias with an
unbound generic type could not be accessed properly from
expression context, but that is just so incredibly obscure.
2019-04-14 23:28:13 -04:00
Sam Lazarus
8f0d9976a8 Test: Moved tests for typealias access through metatypes into protocols tests 2019-04-05 23:33:52 -04:00
Slava Pestov
e2c9c52c93 AST/Sema/SILGen: Implement tuple conversions
TupleShuffleExpr could not express the full range of tuple conversions that
were accepted by the constraint solver; in particular, while it could re-order
elements or introduce and eliminate labels, it could not convert the tuple
element types to their supertypes.

This was the source of the annoying "cannot express tuple conversion"
diagnostic.

Replace TupleShuffleExpr with DestructureTupleExpr, which evaluates a
source expression of tuple type and binds its elements to OpaqueValueExprs.

The DestructureTupleExpr's result expression can then produce an arbitrary
value written in terms of these OpaqueValueExprs, as long as each
OpaqueValueExpr is used exactly once.

This is sufficient to express conversions such as (Int, Float) => (Int?, Any),
as well as the various cases that were already supported, such as
(x: Int, y: Float) => (y: Float, x: Int).

https://bugs.swift.org/browse/SR-2672, rdar://problem/12340004
2019-03-27 18:12:05 -04:00
Mark Lacey
8b55a0f61b SE-0054: Rework diagnostics for IUOs and revise Swift 3 /4 semantics.
For Swift 3 / 4:

Deprecate the spelling "ImplicitlyUnwrappedOptional", emitting a warning
and suggesting "!" in places where they are allowed according to
SE-0054.

In places where SE-0054 disallowed IUOs but we continued to accept them
in previous compilers, emit a warning suggesting "Optional" or "?"  as
an alternative depending on context and treat the IUO as an Optional,
noting this in the diagnostic.

For Swift 5:

Treat "ImplicitlyUnwrappedOptional" as an error, suggesting
"!" in places where they are allowed by SE-0054.

In places where SE-0054 disallowed IUOs, emit an error suggestion
"Optional" or "?" as an alternative depending on context.
2017-11-18 11:41:53 +09:00
David Zarzycki
78298c8d2a [Sema] Remove vestigial member lookup path
The normal lookup path can handle all constructors just fine.
2017-08-09 20:25:09 -04:00
Arnold Schwaighofer
8146104b7e Revert "Simplify performMemberLookup()" 2017-08-09 10:56:38 -07:00
David Zarzycki
823e3e16c0 [Sema] Remove vestigial member lookup path
The normal lookup path can handle all constructors just fine.
2017-08-08 21:26:55 -04:00
Pavel Yaskevich
29b8f5615d [QoI] Fix crash when constructing existential metatype without '.init'
Resolves: SR-4301.
2017-05-29 22:08:50 -07:00
Slava Pestov
edeb157964 Sema: Fix call to Self-returning methods with refined protocols
Regression from the following commit:

<9db06ee36d>

Fixes <rdar://problem/29868979>.
2017-01-04 15:48:38 -08:00
Slava Pestov
b5da219d11 Sema: Fix crash when closing an existential reference necessitates tuple-to-tuple conversion 2017-01-03 21:49:44 -08:00
Slava Pestov
9db06ee36d Sema: Fixes for handling of 'Self'-returning methods
Protocol methods returning optionals, metatypes and functions
returning 'Self' are now handled correctly in Sema when
accessed with a base of existential type, eg:

protocol Clonable {
  func maybeClone() -> Self?
  func cloneMetatype() -> Self.Type
  func getClonerFunc() -> () -> Self
}

let c: Clonable = ...
let _: Clonable = c.maybeClone()
let _: Clonable.Type = c.cloneMetatype()

Previously, we were unable to model this properly, for
several reasons:

- When opening the function type, we replaced the return
  value in openedFullType _unconditionally_ with the
  existential type. This was broken if the return type
  was not the 'Self' parameter, but rather an optional,
  metatype or function type involving the 'Self' parameter.

- It was also broken because we lost information; if the
  return type originally contained an existential, we had
  no way to draw the distinction. The 'hasArchetypeSelf()'
  method was a hint that the original type contained a
  type parameter, but it was inaccurate in some subtle cases.

- Since we performed this replacement on both the
  'openedFullType' and 'openedType', CSApply had to "undo"
  it to replace the existential type with the opened
  existential archetype. This is because while the formal
  type of the access returns the existential type, in
  reality it returns the opened type, and CSApply has to
  insert the correct ErasureExpr.

  This was also done unconditionally, but even if it were
  done more carefully, it would do the wrong thing because
  of the 'loss of information' above.

- There was something fishy going on when we were dealing
  with a constructor that was declared on the Optional type
  itself, as seen in the fixed type_checker_crasher.

- TypeBase::eraseOpenedExistential() would transform a
  MetatypeType of an opened existential into a MetatypeType
  of an existential, rather than an ExistentialMetatypeType
  of the existential type.

The new logic has the following improvements:

- When opening a function type, we replace the 'Self' type
  parameter with the existential type in 'openedType', but
  *not* 'openedFullType'. This simplifies CSApply, since it
  doesn't have to "undo" this transformation when figuring
  out what coercions to perform.

- We now only use replaceCovariantResultType() when working
  with Self-returning methods on *classes*, which have more
  severe restrictions than protocols. For protocols, we walk
  the type using Type::transform() and handle all the cases
  properly.

- Not really related to the above, but there was a whole
  pile of dead code here concerning associated type references.

Note that SILGen still needs support for function conversions
involving an existential erasure; in the above Clonable example,
Sema now models this properly but SILGen still crashes:

let _: () -> Clonable = c.getClonerFunc()

Fixes <rdar://problem/28048391>, progress on <rdar://problem/21391055>.
2017-01-03 21:49:00 -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
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
Joe
3938d5682a [SE-0095] [Runtime], [Demangler], & AST printer updated to new composition syntax
- All parts of the compiler now use ‘P1 & P2’ syntax
- The demangler and AST printer wrap the composition in parens if it is
in a metatype lookup
- IRGen mangles compositions differently
    - “protocol<>” is now “swift.Any”
    - “protocol<_TP1P,_TP1Q>” is now “_TP1P&_TP1Q”
- Tests cases are updated and added to test the new syntax and mangling
2016-07-19 12:01:37 -07:00
Joe
a6dad0091b [SE-0095] Initial parsing implementation for '&' composition syntax
This commit defines the ‘Any’ keyword, implements parsing for composing
types with an infix ‘&’, and provides a fixit to convert ‘protocol<>’

- Updated tests & stdlib for new composition syntax
- Provide errors when compositions used in inheritance.
Any is treated as a contextual keyword. The name ‘Any’
is used emit the empty composition type. We have to
stop user declaring top level types spelled ‘Any’ too.
2016-07-19 12:01:02 -07:00
Chris Lattner
2c81c8a114 add some parens to the testsuite, NFC. 2016-05-05 23:19:08 -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
Slava Pestov
6812b6926b Sema: Cleanups and minor fixes for protocol 'Self' types
We had four duplicated implementations of checking how a protocol
requirement uses 'Self', all slightly wrong or incomplete:

- When deciding if the protocol type can be used as an existential.
  This one would just ignore 'Self' in the return type of a method
  completely, which was incorrect for cases where 'Self' is
  contravariant but part of the return value, for example:

  func foo() -> (Self -> ())

- When deciding if a member access can be performed on an existential
  value. This is distinct from the former, because the member may
  have been defined in a protocol extension, in which case it cannot
  be used even if the protocol type can be used as an existential.
  Unfortunately, this implementation was overly conservative, and
  would reject uses of 'Self' where Sema could in fact erase the
  existential type, for example:

  func foo() -> Self??
  func foo() -> Self.Type
  func foo() -> (Self, Self)

  This function handled function return types correctly, effectively
  plugging the leak in the previous code. It did lead to inconsistent
  behavior with protocols that had contravariant Self in requirements
  though; sometimes we would diagnose uses of the existential type,
  other times we would only complain about specific members.

- When deciding if a method in a non-final class can model a protocol
  requirement. This one was the most elaborate one, but here
  contravariance and uses of associated types are actually okay, so
  it was written to pick up covariant 'Self' only. However, it also
  did not handle metatypes and tuples.

- When opening the type of member of an existential, we would check
  if the return value was 'Self' or an optional of 'Self', but again
  this check was too conservative, so after the previous three were
  fixed, we could reference members on existentials that did not
  have a correct opened type.

Now, these have been combined into one check. To fix some crashes,
Sema's implementation of erasing existentials now relies on
coerceToType() instead of hand-rolling a few coercions of its own,
and wrapping the rest in CovariantFunctionConversionExpr, which
didn't make much sense if the result was not a function type.

SILGen still does not support function type conversions where an
existential return value is being erased; these would silently
miscompile before, but crash with an assertion now, because they
are correctly modeled as a FunctionConversionExpr, and not
CovariantFunctionConversionExpr.
2016-02-28 23:52:35 -08:00
practicalswift
31ff35e1dd Use 80 column headers consistently. 2016-01-04 01:35:02 +01:00
Slava Pestov
4e7a4177dc Sema: Non-trivial function conversions now work
This removes the totally lame diagnostic telling the user to wrap
their function in a closure.

Some exotic Objective-C metatype to AnyObject conversions are still
missing, and there aren't any executable tests yet. Both will be
addressed soon.

Swift SVN r31527
2015-08-27 08:44:20 +00:00
Chris Lattner
248727780f Now that enough yaks are cleanly shaven, completely reimplement how
we process contextual constraints when producing diagnostic.  Formerly,
we would aggressively drop contextual type information on the floor under
the idea that it would reduce constraints on the system and make it more
likely to be solvable.  However, this also has the downside of introducing
ambiguity into the system, and some expr nodes (notably closures) cannot
usually be solved without that contextual information.

In the new model, expr diagnostics are expected to handle the fact that
contextual information may be present, and bail out without diagnosing an
error if that is the case.  This gets us more information into closures,
allowing more specific return type information, e.g. in the case in
test/expr/closure/closures.swift.

This approach also produces more correct diagnostics in a bunch of other
cases as well, e.g.:

-  var c = [:]  // expected-error {{type '[_ : _]' does not conform to protocol 'DictionaryLiteralConvertible'}} 
+  var c = [:]  // expected-error {{expression type '[_ : _]' is ambiguous without more context}}

and the examples in test/stmt/foreach.swift, test/expr/cast/as_coerce.swift,
test/expr/cast/array_iteration.swift, etc.

That said, this another two steps forward, one back thing.  Because we
don't handle propagating sametype constraints from results of calls to their
arguments, we regress a couple of (admittedly weird) cases.  This is now 
tracked by:
<rdar://problem/22333090> QoI: Propagate contextual information in a call to operands

There is also the one-off narrow case tracked by:
<rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments



Swift SVN r31319
2015-08-18 23:55:02 +00:00
Chris Lattner
9d9b8aaf35 move protocol conformance errors away from being diagnosed as a Failure, instead
putting it into the expr diagnostics path, allowing more contextual messages.


Swift SVN r30920
2015-08-01 18:31:59 +00:00
Chris Lattner
97e6a50148 Start using contextual information from function calls to diagnose issues in their
argument.  For now we start with some of the most simple cases: single argument 
calls.  This dramatically improves the QoI for error messages in argument lists,
typically turning a error+note combo into a single specific error message.

Some minor improvements coming (and also generalizing this to n-ary calls), but it 
is nice that all the infrastructure is starting to come together...



Swift SVN r30905
2015-08-01 04:37:52 +00:00
David Farler
7a49dda2c8 Add @warn_unused_result to map, flatMap, and filter
rdar://problem/21971932

Swift SVN r30849
2015-07-31 05:15:10 +00:00
Chris Lattner
5a2577a1b5 improve the diagnostic for invoking a method on an exsitential that is not allowed,
fixing <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc



Swift SVN r30844
2015-07-31 04:45:01 +00:00
Joe Groff
1d49d927e1 stdlib: Mark many higher-order function interfaces as 'rethrows'.
This covers:

- Lifetime-extending wrappers, like withExtendedLifetime, withCString, and withUnsafe*Pointer
- 'map' and friends on Optional
- 'indexOf'

A few APIs I haven't gotten to yet in this first pass:

- Autoclosure APIs, like assert, &&, etc.
- the 'isOrderedBefore' predicate for sorting APIs. The sorting implementation does some microoptimizations with 'inout' closures that violate rethrows checking.
- Strict 'map', 'filter', and friends on CollectionType. These need some plumbing in Lazy to be able to thread a Result-forming transformation through.

This version of the patch updates some protocol customization implementations that I missed the first time around, and includes the tests I forgot to add in the previous iteration.

Swift SVN r30790
2015-07-30 05:28:17 +00:00