Commit Graph

86 Commits

Author SHA1 Message Date
Pavel Yaskevich
4132aa04f9 [Tests] NFC: Update all of the test-cases improved by changes to generic argument mismatch handling 2025-06-03 00:49:06 -07:00
Pavel Yaskevich
55b8d9538d [CSSimplify] Rework how/when mismatches between optional types are fixed
- Don't attempt to insert fixes if there are restrictions present, they'd inform the failures.

  Inserting fixes too early doesn't help the solver because restriction matching logic would
  record the same fixes.

- Adjust impact of the fixes.

  Optional conversions shouldn't impact the score in any way because
  they are not the source of the issue.

- Look through one level of optional when failure is related to optional injection.

  The diagnostic is going to be about underlying type, so there is no reason to print
  optional on right-hand side.
2024-09-10 10:35:05 -07:00
Pavel Yaskevich
58ffca8f74 [ConstraintSystem] Don't produce partially matching note if none of the overloads matched 2023-05-09 14:11:38 -07:00
Anthony Latsis
da8d035b0b Gardening: Migrate test suite to GH issues: Constraints (2/5) 2022-08-19 06:43:11 +03:00
Pavel Yaskevich
2a9903dfe4 [Diagnostics] Check whether missing conformance could be fixed by using .rawValue
A lot of operators (and most likely regular functions a well) have
overloads that accept i.e. a generic parameter that conforms to
`StringProtocol`, so the best fix in situations when argument is
a raw representable type would be to check whether `.rawValue`
conforms to the expected protocol and use it if so.

Resolves rdar://problem/75367157
2021-03-15 16:53:45 -07:00
Luciano Almeida
19727f2cc2 [Sema][test] Adjusting all missing downcast diagnostics failures 2020-11-28 18:17:18 -03:00
Luciano Almeida
c09af513a0 [tests] Adjusting regression tests argument mismatch diagnostics on suit 2020-07-23 20:05:27 -03:00
Luciano Almeida
43fd786ae0 [SR-5688] [Sema] Handle key path component base type on MemberAccessOnOptionalBaseFailure (#32376)
* [CSDiagnostics] Adjusting MemberAccessOnOptionalBaseFailure to be able to handle key path component member base types

* [tests] Adding regression tests for SR-5688

* [CSDiagnostics] Adjusting source range to diagnose/insert the fixes in correct location

* [tests] Adjusting regression tests to handle the fixits

* [AST] Creating an helper getSourceRange function for KeyPathExpr::Component

* [ConstraintSystem] Store member base type when recording UnwrapOptionalBase fix

* [AST] Creating a new diagnostic note for removing optional from written type

* [CSDiagnostics] Adjusting logic around MemberAccessOnOptionalBaseFailure to emit the correct diagnostics and fixes

* [tests] Adjusting regression tests to add subscript and key path root cases with respective diagnostics

* [Diagnostics] Adjusting message to mention base type

* [CSDiagnostics] Better naming for method/variable that represents base source range

* [CSDiagnostics] Adjusting to use the stored base member only when member is a key path component.

* [Diagnostics] Adjusting minor typos and code

* [AST] Adjusting keypath root diagnostic note message for use unwrapped type

* [CSDiagnostics] Adjusments in MemberAccessOnOptionalBaseFailure diagnostics as per suggestion

* [tests] Adding more test cases for SR-5688

* [CSDiagnostics] Adjusting fixits for key path root and range for diagnostics

* [CSSimplify] Attempt to diagnose InsertExplicitCall for optional function return types when possible on simplifyOptionalObjectConstraint

* [tests] Adding TODO to improve the diagnostics refering to key path root infered as optional types

* [CSDiagnostics] Adjusting comments

* [CSSimplify] Adjusting logic on simplifyOptionalObjectConstraint to attempt InsertCall fix before remove unwrap

* [CSDiagnostics] Adjust the logic to use resolveType on MemberAccessOnOptionalBaseFailure construction
2020-06-25 20:07:03 -03:00
Pavel Yaskevich
d9594c712a [TypeChecker] NFC: Adjust tests improved by new approach for ambiguity diagnosis 2020-06-12 11:47:03 -07:00
Doug Gregor
836bc57fe5 [AST Walker] Stop visiting the bodies of closures as expressions.
Single-expression closures have always been traversed differently
from multi-statement closures. The former were traversed as if the
expression was their only child, skipping the BraceStmt and implicit
return, while the later was traversed as a normal BraceStmt.
Unify on the latter treatment, so that traversal

There are a few places where we unintentionally relied on this
expression-as-child behavior. Clean those up to work with arbitrary
closures, which is an overall simplification in the logic.
2020-06-04 23:06:32 -07:00
Pavel Yaskevich
5dbced972f [Diagnostics] Allow failure diagnostic implementation to extend getAnchor
Some of the diagnostics have special rules about anchor location,
let's make `getAnchor` virtual and allow sub-class to override
default implementation.
2020-04-14 11:30:11 -07:00
Hamish Knight
dc4b089b9f [CS] Don't fix an _OptionalNilComparison argument
We should only be attempting such overloads for
nil literal args.

Resolves SR-12426.
2020-03-28 17:03:42 -07:00
Hamish Knight
b517aa13ef [CS] Explore additional bindings for fixes
Previously we could skip default literal or
supertype bindings if we had already found a solution
with fixes, which could lead us to miss bindings
that produce better diagnostics.

Tweak the logic such that we continue exploring if
we're in diagnostic mode.

Resolves SR-12399.
2020-03-28 17:03:41 -07:00
Pavel Yaskevich
0cd44a83a7 [ConstraintSystem] Don't record general contextual mismatch if there are restrictions present
If there are any conversion restrictions present while trying to repair
failures related to contextual type, let's give `simplifyRestrictedConstraintImpl`
a chance to run and fix the problem.

Resolves: rdar://problem/59773317
2020-03-02 11:07:31 -08:00
Owen Voorhees
166555c34f [Diagnostics] Better diagnostic for integer used as a boolean condition 2020-02-03 21:20:41 -08:00
Owen Voorhees
4aca39e18e [Diagnostics] Provide a better fix-it when trying to boolean-negate an optional 2020-02-03 17:40:03 -08:00
Pavel Yaskevich
595f85fcb3 [Diagnostics] Properly diagnose missing optional unwrap(s) related to closure result 2019-11-19 15:15:30 -08:00
Doug Gregor
c63076e3a1 [Constraint system] Apply fixes without relying on a root expression.
When applying the set of fixes introduced by a solution, don't rely on
a walk from the "root" expression of the constraint system to
attribute the fixes to expressions. Rather, collect the fixes and emit
diagnostics in source order of the expressions that pertain to.
2019-11-15 20:33:57 -08:00
Hamish Knight
176969ddde [CS] Allow simplification of key path subscript arg locators
This allows a few fixes to properly emit
diagnostics for key path subscript argument
contextual failures.

Resolves SR-11476.
2019-09-15 21:39:32 +01:00
Pavel Yaskevich
c54913f786 [TypeChecker] NFC: Fix some diagnostics improved by porting contextual mismatches to new framework 2019-08-13 11:55:08 -07:00
Pavel Yaskevich
5c82b57096 [CSDiagnostics] Teach missing explicit call fix to account for defaults
Currently we only produce a fix if function type doesn't have any
parameters, but it should also account for function having defaults
for all of its parameters which would still allow for nullary call.
2019-07-31 17:21:49 -07:00
Hamish Knight
49bdc45dc9 [AST] Properly recurse when reconstituting sugar
Currently even when `reconstituteSugar`'s `Recursive` parameter is set
to `true`, we stop rebuilding sugar upon hitting a desugared type. For
example `Optional<Optional<Int>>` will only be re-sugared to
`Optional<Int>?`. This commit changes the behaviour so we continue
recursing into the generic argument.
2019-07-02 17:17:21 +01:00
Pavel Yaskevich
cb3252e055 [ConstraintSystem] Extend use of missing explicit call fix
Now covers following new areas (alongside simple assignments):

- Contextual type coercions:
  - In assignment e.g. `let _: X = foo`
  - In return type positions e.g. `func foo() -> A { return bar }`

- Argument-to-parameter applications (including @autoclosure)
2019-05-07 16:41:19 -07:00
Pavel Yaskevich
b82a8c544d [ConstraintSystem] Diagnose missing explicit calls in assignment
If the source of the assignment is a function type which has
a result that could be converted to expected destination type,
let's diagnose that as missing call if such function doesn't
have any parameters.
2019-05-01 01:40:11 -07:00
Daniel Williams
1d88c47aaf [Sema] SR-9851 - Add parens when needed for nil coalescing fixits
https://bugs.swift.org/browse/SR-9851
2019-02-21 21:03:29 -08:00
Pavel Yaskevich
1c79380a12 [CSFix] Couple of small cleanups related to ForceOptional
* Make sure that base and unwrapped types aren't null
* Don't allocate `ForceOptional` fix if nothing has been unwrapped
  in `simplifyApplicableFnConstraint`
* Add sugar reconstitution support to `FailureDiagnostic::resolveType`
* Format diagnostics a bit better
2019-01-26 00:48:01 -08:00
Suyash Srijan
614f72f85d [cs] use simplifyLocatorToAnchor and revert changes to some test diagnostic messages 2019-01-26 00:29:46 +00:00
Suyash Srijan
18d4da14b7 [test] update diagnostics in more tests 2019-01-25 22:43:36 +00:00
Suyash Srijan
6a0a1dec05 [cs] use anchor instead of locator, etc 2019-01-25 21:36:07 +00:00
Suyash Srijan
5b7fd8cc97 [test] Updates diagnostic messages for existing tests 2019-01-25 17:27:09 +00:00
Suyash Srijan
f5264b9779 [diag] fix incorrect diagnostic when unwrapping double optional 2019-01-22 22:03:40 +00:00
Pavel Yaskevich
9818b55266 [CSDiagnostics] Add MissingCall failure
It's used to diagnose cases when function/method are used as
a property instead of being called.
2018-12-11 18:44:41 -08:00
gregomni
36cf24fb9e When we diagnose an unwrap, if the expression being unwrapped is a sole reference to a local let/var, and the local's type is inferred, offer fixits on the initializer as well. In this position we can also reasonably offer 'guard let'. Since we're identifying the implicitly typed initializer now, we can give a specific explanation of how IUOs get turned into optional types with the new IUO implementation.
Pass constraint system down into offering force unwrap fixits so that we can identify the type of the last member chosen for an optional chain. If there's a chain and the last member's return type isn't optional, then it's cleaner to offer to change that last '?' into a '!' to perform the force, rather than parenthesize the whole expression and force the result.
2018-08-12 12:57:20 -07:00
Slava Pestov
b581c63e6b AST: Remove TypeBase::getRValueObjectType()
This would look through one-element tuples, which is no longer necessary.
2018-08-08 10:18:52 -07:00
gregomni
ecdfb5d8fb Something about the rebase changed the order of emission of notes here, perhaps? 2018-07-27 14:30:30 -07:00
gregomni
5faa8bf4d1 Don't offer force-unwrap of the base as a possible fixit for optional
member access if optional chaining is sure to be valid.
2018-07-27 13:56:24 -07:00
Doug Gregor
e7eac0af22 [Type checker] Extend the diagnostics for unwrapping the base of a member access.
Introduce a new fix kind into the constraint solver to cover unwrapping the base
of a member access so we can refer to the a member of the unwrapped base.
Wire this fix kind to the just-added diagnostic that suggests either the
chaining ‘?’ or the force-unwrap ‘!’ via separate, descriptive Fix-Its.

Example:

error: value of optional type 'X?' must be unwrapped to refer to member 'f' of wrapped base type 'X'
  let _: Int = x.f()
               ^
note: chain the optional using '?' to access member 'f' only for non-'nil' base values
  let _: Int = x.f()
               ^
                ?
note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
  let _: Int = x.f()
               ^
                !

Before this, we would sometimes get a Fix-It for just ‘?’ and sometimes get a Fix-It for the
coalescing ‘??’, neither of which is likely to be right.

More work on rdar://problem/42081852.
2018-07-13 16:26:03 -07:00
Doug Gregor
9ec3b00ea4 [Type Checker] Improve diagnostic when referencing a member of an optional base.
Improve diagnostics when referencing a member of an optional base, where the
Optional type does not have the member but the wrapped type does. Specifically,
suggest both the chaining ‘?’ and the force-unwrapping ‘!’ Fix-Its via explanatory
notes, e.g.:

  error: value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
    return foo.array[0]
               ^
  note: chain the optional using '?' to access member 'subscript' only for non-'nil' base values
    return foo.array[0]
               ^
                    ?
  note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
    return foo.array[0]
               ^
                    !

More of rdar://problem/42081852.
2018-07-13 15:22:56 -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
Mark Lacey
f08823757a IUO: Generate Optional<T> rather than ImplicitlyUnwrappedOptional<T>.
Stop creating ImplicitlyUnwrappedOptional<T> so that we can remove it
from the type system.

Enable the code that generates disjunctions for Optional<T> and
rewrites expressions based on the original declared type being 'T!'.

Most of the changes supporting this were previously merged to master,
but some things were difficult to merge to master without actually
removing IUOs from the type system:
- Dynamic member lookup and dynamic subscripting
- Changes to ensure the bridging peephole still works

Past commits have attempted to retain as much fidelity with how we
were printing things as possible. There are some cases where we still
are not printing things the same way:
- In diagnostics we will print '?' rather than '!'
- Some SourceKit and Code Completion output where we print a Type
  rather than Decl.

Things like module printing via swift-ide-test attempt to print '!'
any place that we now have Optional types that were declared as IUOs.

There are some diagnostics regressions related to the fact that we can
no longer "look through" IUOs. For the same reason some output and
functionality changes in Code Completion. I have an idea of how we can
restore these, and have opened a bug to investigate doing so.

There are some small source compatibility breaks that result from
this change:
- Results of dynamic lookup that are themselves declared IUO can in
  rare circumstances be inferred differently. This shows up in
  test/ClangImporter/objc_parse.swift, where we have
    var optStr = obj.nsstringProperty
  Rather than inferring optStr to be 'String!?', we now infer this to
  be 'String??', which is in line with the expectations of SE-0054.
  The fact that we were only inferring the outermost IUO to be an
  Optional in Swift 4 was a result of the incomplete implementation of
  SE-0054 as opposed to a particular design. This should rarely cause
  problems since in the common-case of actually using the property rather
  than just assigning it to a value with inferred type, we will behave
  the same way.
- Overloading functions with inout parameters strictly by a difference
  in optionality (i.e. Optional<T> vs. ImplicitlyUnwrappedOptional<T>)
  will result in an error rather than the diagnostic that was added
  in Swift 4.1.
- Any place where '!' was being used where it wasn't supposed to be
  allowed by SE-0054 will now treat the '!' as if it were '?'.
  Swift 4.1 generates warnings for these saying that putting '!'
  in that location is deprecated. These locations include for example
  typealiases or any place where '!' is nested in another type like
  `Int!?` or `[Int!]`.

This commit effectively means ImplicitlyUnwrappedOptional<T> is no
longer part of the type system, although I haven't actually removed
all of the code dealing with it yet.

ImplicitlyUnwrappedOptional<T> is is dead, long live implicitly
unwrapped Optional<T>!

Resolves rdar://problem/33272674.
2018-01-31 12:15:58 -08: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
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
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
Chris Lattner
a0d34852bb Revert "Fix the build."
This reverts commit 932fe9d6b9.
2016-07-17 12:35:42 -07:00
Michael Gottesman
932fe9d6b9 Fix the build.
This reverts commit 4242af7503.
This reverts commit 76cf339694.
This reverts commit e97ed133a8.
This reverts commit 66961fcda8.
2016-07-17 01:02:48 -07:00
Chris Lattner
76cf339694 Implement the first half of SE-0109: Remove the Boolean protocol
This removes conformance of DarwinBool and ObjCBool to the Boolean protocol,
and makes the &&/||/! operators be concrete w.r.t. Bool instead of abstract
on Boolean.

This fixes some outstanding bugs w.r.t diagnostics, but exposes some cases
where an existing diagnostic is not great.  I'll fix that in a later patch
(tracked by rdar://27391581).
2016-07-16 23:23:45 -07:00
Harlan
cca7dcab52 Added fixit to remove empty argument for non-function calls (#3196) 2016-06-26 17:06:26 -07:00
Chris Lattner
2c81c8a114 add some parens to the testsuite, NFC. 2016-05-05 23:19:08 -07:00
Dave Abrahams
debde16e2c Merge set-api branch into swift-3-indexing-model 2016-04-26 15:56:42 -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