Commit Graph

41 Commits

Author SHA1 Message Date
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
a0d132582e [Diagnostics] Improve diagnostic message for extraneous &
Resolves: https://github.com/apple/swift/issues/58389
2022-04-25 15:08:04 -07:00
Pavel Yaskevich
66fbdce2f8 [ConstraintSystem] Don't increase a score for conditional requirement failures
Let's consider conditional requirement failure to mean that parent
conformance requirement wasn't satisfied and nothing more, that helps
to disambiguate certain situations and avoid filtering out conditional
failures.

Resolves: rdar://problem/64844584
2020-11-06 12:06:00 -08:00
Luciano Almeida
59add19684 Merge pull request #32056 from LucianoPAlmeida/minor-typos
[NFC][test] Minor typo corrections on test messages
2020-06-17 07:14:27 -03:00
Pavel Yaskevich
ac2305e7f1 [ConstraintSystem] Increase impact of fixes for some conditional requirements
If there is a conditional requirement failure associated with
member/function reference used in a call let's increase a score
of a fix for such failure because it renders member/function
unreachable in current context or with a given set of arguments.
2020-06-12 11:47:04 -07:00
Luciano Almeida
6d3f53a417 [NFC][test] Minor corrections on test messages 2020-06-05 06:36:09 -03:00
Pavel Yaskevich
a1643d94f7 [Diagnostics] NFC: Update all of the improved test-cases 2019-09-13 22:35:52 -07:00
Pavel Yaskevich
e9aa04a91a [ConstraintSystem] Extend generic argument mismatch fix to all pointer conversions
This makes it possible to diagnose all implicit pointer
conversions in argument positions with a better error
message which preserves enclosing types, and allows to
share base type matching logic across all pointer conversions.
2019-09-02 19:08:00 -07:00
Pavel Yaskevich
7ac754acc4 [Diagnostics] Transform incorrect generic arguments into a contexual mismatch
Since this kind of failure is really a conversion failure, let's
inherit from `Contextual{Mismatch, Failure}` which also helps with
storage for from/to types and their resolution.

Also let's use original types involved in conversion to form
this fix, which helps to perserve all of the original sugar.
2019-08-19 09:56:48 -07:00
Pavel Yaskevich
8ac2ef8611 [Diagnostics] Extend generic argument mismatch to cover [T] to Unsafe*Pointer<T> conversions
Example:

```swift
func foo(_ x: UnsafePointer<Int>) {}
var arr: [Float] = [0, 1, 2]
foo(&arr) // Cannot convert [Float] to UnsafePointer<Int> because of Float vs. Int
```
2019-08-07 13:16:20 -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
63b802ca88 [AST/Printing] Don't omit empty labels in special names
This makes diagnostics more verbose and accurate, because
it's possible to distinguish how many parameters there are
based on the message itself.

Also there are multiple diagnostic messages in a format of
`<descriptive-kind> <decl-name> ...` that get printed as
e.g. `subscript 'subscript'` if empty labels are omitted.
2018-09-24 18:36:53 -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
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
David Zarzycki
67710606e6 [Parse] Move tok::amp_prefix closer to parameter list logic
The amp_prefix token is currently tolerated in any unary expression
context and then diagnosed later by Sema. This patch changes parsing to
only accept tok::amp_prefix in its allowed position: parameter lists.

This also fixes two "compiler crasher" tests.
2018-03-30 17:56:36 -04: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
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
Ben Cohen
c4f0b5fe94 [stdlib] Adopt conditional conformance for Indices, Slice, ReversedCollection (#12913)
* Refactor Indices and Slice to use conditional conformance

* Replace ReversedRandomAccessCollection with a conditional extension

* Refactor some types into struct+extensions

* Revise Slice documentation

* Fix test cases for adoption of conditional conformances.

* [RangeReplaceableCollection] Eliminate unnecessary slicing subscript operator.

* Add -enable-experimental-conditional-conformances to test.

* Gruesome workaround for crasher in MutableSlice tests
2017-11-30 09:10:22 -08:00
Doug Gregor
ba6f605d47 Fix some tests due to Equatable Optional/Array/Dictionary change. 2017-11-27 21:09:50 -08:00
Pavel Yaskevich
7b121de1a0 [CSRanking] Change ranking to weight overload choices in evaluation order
Consider different overload choices for the same location in evaluation
order, this makes overload resolution more predictable because it's going
to follow expression bottom-up, that prevents situations when some
expressions are considered ambigious because choices taken further up
equate the score, instead each level is given distinct weight
based on evaluation order.

Resolves: rdar://problem/31888810
2017-11-16 13:38:24 -08:00
Greg Parker
e8475cc130 Revert "Use conditional conformances to implement Equatable for Optional, Array and Dictionary" 2017-11-15 14:17:22 -08:00
Doug Gregor
1f9b28a117 [Type checker diags] Check generic arguments for any generic function.
This includes functions without type parameters that are generic
because they are members of a generic context. This addresses a
diagnostics regression because the '==' operators for Optional, Array,
and Dictionary were made into members.

The resulting error message is a little ugly, but is more informative
(and much shorter) than what we had before.
2017-11-14 16:23:20 -08:00
Pavel Yaskevich
e8744af283 [QoI] Improve diagnostics for assignment expression
Currently `visitAssignExpr` always attempts to use type
derived from destination as a contextual type for assignment
source type-checking, which doesn't always lead to better
results.

Resolves: SR-5081
2017-08-02 18:17:49 -07:00
David Zarzycki
1504c2ede7 [QoI] Ignore implicit conversions during mutation diagnostics
This change helps diagnoseSubElementFailure() avoid the unknown error
path in more scenarios.
2017-07-21 10:09:47 +01:00
Dmitri Gribenko
486cab447d tests: replace 'rm -rf %t && mkdir -p %t' with '%empty-directory(%t)'
These changes were made using a script.
2017-06-04 11:08:39 -07:00
Jordan Rose
4b87bd93f9 Tweak DiagnosticEngine's 'aka' logic to only kick in for typealiases. (#9010)
Previously we had more ad hoc logic that tried to decide if it was
worth desugaring a type based on its structure. Now we instead look
for a typealias that might actually benefit from desugaring, and if
we don't find one we won't show the 'aka' note.
2017-04-25 19:37:22 -07:00
Andrew Trick
c12740a8a2 Add UnsafeRawBuffer(rebasing:) initializers.
Allows converting a raw slice into a zero-based raw buffer,
which is a common operation on flat memory.

Add and update UnsafeRawBufferPointer unit tests.
2017-04-06 17:12:18 -07:00
Andrew Trick
849421799a Revert "SE-0138: Proposed amendment to SE-0138: Normalize UnsafeRawBufferPointer Slices (#8222)"
This reverts commit 1d32586d28.
2017-04-06 10:38:52 -07:00
Andrew Trick
1d32586d28 SE-0138: Proposed amendment to SE-0138: Normalize UnsafeRawBufferPointer Slices (#8222)
* Add sliceability tests for Unsafe(Raw)BufferPointer.

Improve the generic sliceability tests to verify that SubSequence indices are
compatible with their parents indices.

* Fix and enable testing stdlib Collection instances.

Top-level entry points fully testing a collection instance:
check${Traversal}Collection

One level of recursion into all slices of the collection instance
O(n^2). (Not combinatorial).

Previously, checkCollection() did nothing. So much of the testing infrastructure was inactive. Now it runs all forward collection tests.

Fixes a bug in subscriptRangeTests.

The UnsafeRawBufferPointer and Data collection testing is disabled and
will be fixed in the following commit.

* Give UnsafeRawBufferPointer a distinct slice type.

SubSequence = RandomAccessSlice<Self>

* Fix raw buffer pointer tests after changing the API

* Add UnsafeRawBuffer(rebasing:) initializers.

Allows converting a raw slice into a zero-based raw buffer,
which is a common operation on flat memory.

Add and update UnsafeRawBufferPointer unit tests.

* Do not run recursive O(n^2) collection slice testing on large collections.

Now, even with collection unit testing wired up, the validation tests
take the same amount of time to execute.

* Add init(rebasing:) to UnsafeBufferPointer.

This is required for consistency with UnsafeRawBufferPointer.

* Update CHANGELOG.md for SE-0138 amendment: UnsafeRawBufferPointer slice type.
2017-04-06 10:08:09 -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
Doug Gregor
d0733750cc [Constraint solver] Try ‘defaultable’ bindings even if there are other possibilities.
Fixes rdar://problem/17444930.
2016-08-04 13:45:07 -07:00
Andrew Trick
0b75ee975e Remove "illegal" UnsafePointer casts from the stdlib.
Update for SE-0107: UnsafeRawPointer

This adds a "mutating" initialize to UnsafePointer to make
Immutable -> Mutable conversions explicit.

These are quick fixes to stdlib, overlays, and test cases that are necessary
in order to remove arbitrary UnsafePointer conversions.

Many cases can be expressed better up by reworking the surrounding
code, but we first need a working starting point.
2016-07-28 20:42:23 -07:00
Andrew Trick
a18d490d6a Migrate from UnsafePointer<Void> to UnsafeRawPointer. (#3773)
* Migrate from `UnsafePointer<Void>` to `UnsafeRawPointer`.

As proposed in SE-0107: UnsafeRawPointer.

`void*` imports as `UnsafeMutableRawPointer`.
`const void*` imports as `UnsafeRawPointer`.

Occurrences of `UnsafePointer<Void>` are replaced with UnsafeRawPointer.

* Migrate overlays from UnsafePointer<Void> to UnsafeRawPointer.

This requires explicit memory binding in several places,
particularly in NSData and CoreAudio.

* Fix a bunch of test cases for Void->Raw migration.

* qsort takes IUO values

* Bridge `Unsafe[Mutable]RawPointer as `void [const] *`.

* Parse #dsohandle as UnsafeMutableRawPointer

* Update a bunch of test cases for Void->Raw migration.

* Trivial fix for the SceneKit test case.

* Add an UnsafeRawPointer self initializer.

This is unfortunately necessary for assignment between types imported from C.

* Tiny simplification of the initializer.
2016-07-26 14:21:15 -07:00
Andrew Trick
0ed9ee8dee Revert "Migrate from UnsafePointer<Void> to UnsafeRawPointer. (#3724)"
This reverts commit ece0951924.

This results in lldb failues on linux that I can't readily debug.
Backing out until they can be resolved.
2016-07-26 02:50:57 -07:00
Andrew Trick
ece0951924 Migrate from UnsafePointer<Void> to UnsafeRawPointer. (#3724)
* Migrate from `UnsafePointer<Void>` to `UnsafeRawPointer`.

As proposed in SE-0107: UnsafeRawPointer.

`void*` imports as `UnsafeMutableRawPointer`.
`const void*` imports as `UnsafeRawPointer`.

Occurrences of `UnsafePointer<Void>` are replaced with UnsafeRawPointer.

* Migrate overlays from UnsafePointer<Void> to UnsafeRawPointer.

This requires explicit memory binding in several places,
particularly in NSData and CoreAudio.

* Fix a bunch of test cases for Void->Raw migration.

* qsort takes IUO values

* Bridge `Unsafe[Mutable]RawPointer as `void [const] *`.

* Parse #dsohandle as UnsafeMutableRawPointer

* Update a bunch of test cases for Void->Raw migration.

* Trivial fix for the SceneKit test case.

* Add an UnsafeRawPointer self initializer.

This is unfortunately necessary for assignment between types imported from C.

* Tiny simplification of the initializer.
2016-07-26 02:18:21 -07:00
Andrew Trick
ecc6bd51ad Type system support for raw pointer conversion. (#3685)
* [Type System] Handle raw pointer conversion.

As proposed in SE-0107: UnsafeRawPointer.
https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md#implicit-argument-conversion

UnsafeMutablePointer<T> -> UnsafeMutableRawPointer
UnsafeMutablePointer<T> -> UnsafeRawPointer
UnsafePointer<T> -> UnsafeRawPointer
UnsafeMutableRawPointer -> UnsafeRawPointer

inout:
&anyVar -> UnsafeMutableRawPointer
&anyVar -> UnsafeRawPointer

array -> UnsafeRawPointer
string -> UnsafeRawPointer

varArray -> UnsafeMutableRawPointer

* Rename expectEqual(_, _, sameValue:) to expectEqualTest to workaround a type system bug.

<rdar://26058520> Generic type constraints incorrectly applied to functions with the same name

This is exposed by additions to the type system for UnsafeRawPointer.

Warning: unit tests fail very confusingly without this fix.
2016-07-23 11:30:49 -07:00
Andrew Trick
73106dd7c3 Rename initialize(with:count:) to initialize(to:count:). (#3601)
As proposed in SE-0107: UnsafeRawPointer.

"with" is considered a vacuous preposition. "to" implies direction.
2016-07-18 23:37:45 -07:00
Rintaro Ishizaki
1bdce7ced6 [lit] Add substitutions: %utils and %line-directive
%utils => ${SWIFT_SOURCE_DIR}/utils
%line-directive => ${SWIFT_SOURCE_DIR}/utils/line-directive
2016-06-11 02:41:15 +09:00
Trent Nadeau
0cc851568a Updated tests to use @discardableResult and _ = . 2016-05-11 22:53:38 -04:00
Chris Lattner
2c81c8a114 add some parens to the testsuite, NFC. 2016-05-05 23:19:08 -07:00
Jordan Rose
a79a893f9a [test] Add new tests for pointers with explicit nullability. 2016-04-11 20:06:40 -07:00