Commit Graph

64 Commits

Author SHA1 Message Date
Pavel Yaskevich
84d034c388 [CSOptimizer] Don't reduce the ranking for non-default literal types
Since each candidate and overload choice are considered independenty
there is no way to judge whether non-default literal type is going
to result in a worse solution than non-default one.
2025-06-27 23:43:10 -07:00
Pavel Yaskevich
6bbc101a98 [Diagnostics] Correctly diagnose situations when immutable value is passed to inout parameter
Currently the note is going to point to the "callee" but that is
incorrect when the failure is related to an argument of a call.

Detect this situation in `RValueTreatedAsLValueFailure::diagnoseAsNote`
and produce a correct note.

Resolves: rdar://150689994
2025-06-06 14:36:19 -07:00
Pavel Yaskevich
218346c285 [CSRanking] Adjust isDeclMoreConstrainedThan to account for invertible protocols
Use of invertible protocols doesn't make type parameter more
constrained.
2024-02-09 17:16:50 -08:00
Luciano Almeida
6d85bd54d3 [Sema] Handle coercion in ambiguity note emission 2023-03-12 15:26:38 -03:00
Luciano Almeida
5fee07b73f [CSDiagnostics] Adapt diagnostics to handle new CoercionOperand elt 2023-03-11 18:47:53 -03:00
Luciano Almeida
f5c68dbeb9 [Sema] Handle FunctionArgument anchored in coerce expr in getCalleeLocator 2023-02-22 21:03:44 -03:00
Artem Chikin
c5e1b6baa9 Adjust tests to account for presence of implicit import of '_SwiftConcurrencyShims' 2023-01-13 11:20:35 -08:00
Anthony Latsis
e57359a5c7 Merge pull request #60591 from AnthonyLatsis/migrate-test-suite-to-gh-issues-4
Gardening: Migrate test suite to GH issues p. 4
2022-08-20 04:53:15 +03:00
Anthony Latsis
7fc8377e1c Gardening: Migrate test suite to GH issues: Constraints (1/5) 2022-08-17 15:21:51 +03:00
Luciano Almeida
89c1a4e597 [tests] Add extra test case for _ pattern hole 2022-08-12 10:03:21 -03:00
Pavel Yaskevich
399d3490d4 [ConstraintSystem] Add a tailored ambiguity diagnostic for non-conforming result type 2022-07-25 10:45:45 -07:00
Alex Hoppen
5ba66aae3e Add test case for #60029
The issue has been fixed by allowing holes for variables in paterns.
2022-07-20 09:47:18 +02:00
Philip Turner
4b8ba3c1ce Don't Unnecessarily Invalidate Unreferenced Generic Parameters (#41128) 2022-02-03 09:20:31 -08:00
Pavel Yaskevich
2b58a75f97 [Diagnostics] Fix requirement note to properly handle layout requirements
Layout requirement doesn't have a second type since it's always `AnyObject`,
requirement failure note should handle that, otherwise in no assertion builds
this would crash in diagnostic engine trying to emit the note.

Resolves: rdar://79672230
2021-06-25 14:08:43 -07:00
Pavel Yaskevich
2b207e8f07 [Diagnostics] Augment "expected parameter" note with an argument type
Currently ambiguity notes attached to a candidate only mention
expected type and its position. To improve clarify of such notes
it's useful to print argument type as well since it's not always
clear what it is at the first glance at the code.

Resolves: SR-14634
Resolves: rdar://78224323
2021-05-26 12:58:35 -07:00
Pavel Yaskevich
22832080e2 [ConstraintSystem] Don't propagate holes through supertype inference
Disallow holes to be inferred as supertype bindings  while inferring
bindings from other type variables (based on transitivity of subtype
conversions), otherwise it would be possible to record a hole without
recording associated fix.

Resolves: rdar://problem/64368545
2020-06-18 10:53:50 -07:00
Pavel Yaskevich
13b4fcc5e7 [Diagnostics] Diagnose ambiguity related to contextual type specifically 2020-06-12 11:47:04 -07:00
Varun Gandhi
a1716fe2a6 [Diagnostics] Update compiler diagnostics to use less jargon. (#31315)
Fixes rdar://problem/62375243.
2020-04-28 14:11:39 -07:00
Suyash Srijan
211394099f [CSDiagnostics] Offer a fix-it to insert a return type placeholder when returning from a void function (#29747)
* [CSDiagnostics] Offer a fix-it to insert a return type when returning from a void function

* [CSDiagnostics] Make sure the function name is not empty

The function name will be empty in some cases, for example for property setters. In cases where the function name is empty, skip the note and fix-it.

* [Test] Update existing diagnostics
2020-02-11 10:25:16 +00:00
Holly Borla
43712bb860 [Diagnostics] Diagnose general ambiguity failures in diagnoseAmbiguityWithFixes. 2020-01-07 15:05:54 -08:00
Hamish Knight
e2096ae34d [CSDiagnostics] Tweak candidate note text for arg mismatch
Number the parameters starting at 1 in order to
match other diagnostics such as
diag::missing_argument_positional, and change the
text to make it explicit that we're referring to
the parameter position (rather than argument
position).
2019-10-03 15:26:31 -07:00
Pavel Yaskevich
001f46231c [Diagnostics] Fix a typo in argument mismatch diagnostic note 2019-09-13 22:35:52 -07:00
Pavel Yaskevich
a1643d94f7 [Diagnostics] NFC: Update all of the improved test-cases 2019-09-13 22:35:52 -07:00
Brent Royal-Gordon
a72be0fb7d Sort overloads in suggestPotentialOverloads()
When the compiler fails to find an overload with suitable parameter or return types, it often attaches a note listing the available overloads so that users can find the one they meant to use. The overloads are currently ordered in a way that depends on the order they were declared, so swift-evolve would sometimes cause tests involving these diagnostics to fail.

This change emits the list in a textually-sorted order instead. The names were already being sorted as they were inserted into a std::set, so this shouldn’t significantly slow down the diagnostic.
2018-12-12 11:58:57 -08:00
Mark Lacey
c0007f8168 Revert "[ConstraintSystem] Fix the ordering of functions with optional parame…" 2018-07-19 00:21:12 -07:00
Mark Lacey
d271f4b057 [ConstraintSystem] Ensure we prefer f(_: Any) to f(_: Any?) when both work.
...unless the argument is an `Any?`, in which case we prefer `f(_: Any?)`.

This change also results in our selecting f<T>(_: T) over f(_:
Any). Coercing with 'as Any' makes it possible to explicitly select
the Any overload. Previously there was no way to select the generic
overload.
2018-07-18 11:44:04 -07:00
Mark Lacey
186c2f251a [ConstraintSystem] Fix the ordering of functions with optional parameters.
Treat non-optional generic parameters as being more specialized than
optional generic parameters, and penalize any solutions that involve
generic arguments that are themselves Optional.

By doing these things, we can remove the special-cased code for the
two overloads of '??' in the stdlib, instead treating the (T?, T)
overload as better than the (T?, T?) overload except where a user
actually passes an optionally-typed value as the second parameter.

Fixes: rdar://problem/19748710
2018-07-18 11:43:44 -07:00
Doug Gregor
945c09b1cc [Type checker] Improve diagnostics when an optional value is not unwrapped.
When we determine that an optional value needs to be unwrapped to make
an expression type check, use notes to provide several different
Fix-It options (with descriptions) rather than always pushing users
toward '!'. Specifically, the errors + Fix-Its now looks like this:

    error: value of optional type 'X?' must be unwrapped to a value of
        type 'X'
      f(x)
        ^
    note: coalesce using '??' to provide a default when the optional
        value contains 'nil'
      f(x)
        ^
          ?? <#default value#>
    note: force-unwrap using '!' to abort execution if the optional
        value contains 'nil'
      f(x)
         ^
         !

Fixes rdar://problem/42081852.
2018-07-13 11:02:04 -07:00
Doug Gregor
8342f77bc4 [Overloading] Adjust @autoclosure parameter types to their result types.
For the purposes of partial ordering of declarations (e.g., in
overload resolution), adjust `@autoclosure` parameter types to the
result type of the autoclosure, i.e., the type against which the
argument will be matched. This makes overload resoluton agnostic to
`@autoclosure`.

Fixes SR-6472.
2017-11-27 15:32:23 -08:00
Pavel Yaskevich
5998cd645f [ConstraintSolver] Penalize conversions from String to UnsafePointer
There are possible situations when we find solutions with String
and String -> UnsafePointer conversions at the same time for
expressions with default string literals. In order to disambiguite
such situations let's prefer solutions without String -> UnsafePointer
conversions if possible.
2017-06-01 14:43:43 -07:00
Mark Lacey
44882d2d2a [Constraint solver] Fix Swift 3 compatibility issue with overloaded operators.
Recent changes to the stdlib resulted in some expressions involving
literals and operators that have both generic and non-generic overloads
to become ambiguous. The ambiguity is due to an old performance hack in
the solver which unfortunately needs to remain in place at the moment to
avoid regressing expression type checker performance.

This commit changes the performance hack a bit in that instead of
stopping visiting the options in a disjunction as soon as we have a
solution involving non-generic operators and come across a constraint
involving generic operators, we instead continue visiting the elements
in the disjunction, but just skip over the generic operators.

Fixes rdar://problem/31695865 and rdar://problem/31698831.
2017-05-02 18:27:15 -07:00
Doug Gregor
e25244f3c6 [Type checker] Ignore argument labels when ordering declarations.
When comparing the parameters of two declarations for the purpose of
partial ordering, it doesn't make sense to compare the parameter
labels: they're dealt with separately and aren't conceptually part of
the type.
2017-02-08 20:54:25 -08: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
7fed7b49ed Sema: Maintain invariant that invalid FuncDecls always have an ErrorType
Otherwise, overload resolution and CSDiag disagree on what a viable
candidate is, so we can end up in a situation where the OverloadDeclRefExpr
has a concrete type that doesn't match the argument list in an ApplyExpr,
which causes a crash in CSDiag.
2016-12-21 14:20:26 -05:00
swift-ci
fe1cd74221 Merge pull request #5808 from xedin/r28051973 2016-11-28 17:01:38 -08:00
Pavel Yaskevich
2707a9c585 [Diagnostics] Improve diagnostics of overloaded mutating methods
Add special logic to FailureDiagnosis::visitApplyExpr to
handle situation like following:

struct S {
  mutating func f(_ i: Int) {}
  func f(_ f: Float) {}
}

Given struct has an overloaded method "f" with a single argument of
multiple different types, one of the overloads is marked as
"mutating", which means it can only be applied on LValue base type.
So when struct is used like this:

let answer: Int = 42
S().f(answer)

Constraint system generator is going to pick `f(_ f: Float)` as
only possible overload candidate because "base" of the call is immutable
and contextual information about argument type is not available yet.
Such leads to incorrect contextual conversion failure diagnostic because
type of the argument is going to resolved as (Int) no matter what.
To workaround that fact and improve diagnostic of such cases we are going
to try and collect all unviable candidates for a given call and check if
at least one of them matches established argument type before even trying
to re-check argument expression.

Resolves: <rdar://problem/28051973>.
2016-11-28 14:23:14 -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
Pavel Yaskevich
dd01b7e184 [Diagnostics] SR-2208: Improve failure diagnostics for apply expressions 2016-10-26 14:34:05 -07:00
Trent Nadeau
0cc851568a Updated tests to use @discardableResult and _ = . 2016-05-11 22:53:38 -04: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
Doug Gregor
42bb2528dd [Overload resolution] Prefer functions with fewer defaulted/variadic arguments.
When comparing two functions for overload resolution, break apart the
parameter lists to compare individual parameters rather than comparing
the tuples. This allows us to prefer functions with fewer arguments to
ones with more, defaulted or variadic arguments. That preference was
already encoded in the constraint optimizer, which led to some strange
behavior where the preference was expressed for function calls but not
for calls to initializers. Fixes rdar://problem/24128153.

The standard library change tweaks the anachronistic, unavailable
"print" variants somewhat. The only behavior change here is a slight
regression for cases like:

  print(a: 1, b: 2)

where we used to produce a diagnostic:

  Please wrap your tuple argument in parentheses: 'print((...))'

but we now get:

  argument labels '(a:, b:)' do not match any available overloads

However, this regression will happen at some point *anyway*, if
SE-0029 (or anything else that removes the implicit tuple splat
operation) goes through.
2016-02-05 11:41:01 -08:00
Chris Lattner
96eaa14f3b Fix an arbitrary restriction where we would not propagate the result type of
call expression onto a callee when it was a binary expression.  Doing this
requires improving the diagnostics for when the contextual result type is
incompatible with all candidates, but that is general goodness all around.

This fixes:
<rdar://problem/22333090> QoI: Propagate contextual information in a call to operands

and improves a number of diagnostics where the problem is that an operator
is used in a context that expects a type that it cannot produce.



Swift SVN r31891
2015-09-11 06:12:05 +00:00
Chris Lattner
5e7b067f4f Add an example of a poor diagnostic.
Swift SVN r31889
2015-09-11 05:08:28 +00:00
Chris Lattner
ea813c6e12 assign some dead results to _. NFC.
Swift SVN r31414
2015-08-22 22:27:36 +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
Chris Lattner
dff93b512b Now that we have the notion of an uncurry level, we can do a lot more
detailed analysis of callees, which give us overload sets in more cases,
producing notes more consistently, and producing much better diagnostics
for the curried cases in test/Constraints/diagnostics.swift.

This also allows us to eliminate getCalleeName, which simplifies things
in CSDiags.


Swift SVN r30491
2015-07-22 05:37:39 +00:00
Chris Lattner
5d3dc0d77b Now that sufficient complexity is pushed into the right corners of the compiler,
we can start taking advantage of ambiguously typed subexpressions in CSDiags.  We
start by validating the callee function of ApplyExprs, which substantially improves
our abilities to generate precise diagnostics about malformed calls.

This is the minimal introduction of this concept to CSDiags, a lot of refactoring
is yet to come, however, this is enough to resolve:

<rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression
<rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.

one of the testcases from:
<rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type

and a bunch of other places where we got weird "unexpected trailing closure" 
diagnostics that made no sense.  As usual, it is two steps forward and one step back,
as this exposed some other weird latent issues like:
<rdar://problem/21900971> QoI: Bogus conversion error in generics case




Swift SVN r30429
2015-07-21 01:06:55 +00:00
Chris Lattner
63f99a486c Move CallExpr diagnostics over to the same overload candidate diagnosis
facilities used by operators etc.  This required a bunch of changes to make
the diagnostics changes strictly an improvement:

  - Teach the new path about calls to TypeExprs.
  - Teach evaluateCloseness some simple things about varargs.
  - Make the generic diagnosis logic produce a better error when there is 
    exactly one match.

Overall, the resultant diagnostics are a step forward: we now produce candidate
set notes more uniformly, and the messages about some existing ones are 
more specific.  This is just another stepping stone towards progress though.



Swift SVN r30057
2015-07-10 04:26:42 +00:00
Chris Willmore
fd5812be50 Don't assume that a ValueDecl in a type DeclContext with function type
is an instance method. Make sure it's a non-static function before
attempting to strip the implicit self parameter from the type.

<rdar://problem/20886179> compiler error

Swift SVN r29732
2015-06-26 05:39:38 +00:00
Joe Groff
bebfa969bd Sema: Allow 'x.init' references on metatype expressions.
If 'x.init' appears as a member reference other than 'self.init' or 'super.init' within an initializer, treat it as a regular static member lookup for 'init' members. This allows a more explicit syntax for dynamic initializations; 'self.someMetatype()' looks too much like it's invoking a method. It also allows for partial applications of initializers using 'someMetatype.init' (though this needs some SILGen fixes, coming up next). While we're in the neighborhood, do some other correctness and QoI fixes:

- Only lookup initializers as members of metatypes, not instances, and add a fixit (instead of crashing) to insert '.dynamicType' if the initializer is found on an instance.
- Make it so that constructing a class-constrained archetype type correctly requires a 'required' or protocol initializer.
- Warn on unused initializer results. This seems to me like just the right thing to do, but is also a small guard against the fact that 'self.init' is now valid in a static method, but produces a newly-constructed value instead of delegating initialization (and evaluating to void).

Swift SVN r29344
2015-06-08 04:11:28 +00:00