Commit Graph

979 Commits

Author SHA1 Message Date
practicalswift
fcd470c111 [gardening] Fix recently introduced typos. 2016-07-09 11:45:37 +02:00
Rintaro Ishizaki
4bf1c34f80 [Parse/Sema][SR-1672] Improve diagnostics for trailing closures in stmt-condition (#3184)
Fix-it suggests normal argument expression, instead of of enclosing whole
expression with parens.

* Moved diagnostic logic to Sema, because we have to add correct argument
  label for the closure.

    if arr.starts(with: IDs) { $0.id == $2 } { ... }
                           ~~^
                           , isEquivalent:  )

* We now accept trailing closures for each expressions and right before `where`
  clause, as well as closures right before the body.

    if let _ = maybeInt { 1 }, someOtherCondition { ... }
                       ~^
                       (     )

    for let x in arr.map { $0 * 4 } where x != 0 { ... }
                        ~^
                        (          )
2016-07-09 12:51:51 +09:00
Xi Ge
1e85e1bcd2 Revert "[Fixit] Add a fixit for converting non-trailing closures to trailing closures (#3317)"
This patch needs some polish to fix more false positives found by @rintaro and @lattner
2016-07-02 09:39:07 -07:00
Xi Ge
1886b4ab56 [Fixit] Add a fixit for converting non-trailing closures to trailing closures (#3317)
* [Fixit] Add a fixit for converting non-trailing closures to trailing closures.

* [test] Update test to reflect the added note about converting to trailing closures.
2016-07-02 08:11:58 -07:00
Michael Gottesman
95d4cbf962 Revert "[Fixit] Add a fixit for converting non-trailing closures to trailing closures."
This reverts commit b37330d3b7.

It broke the build.
2016-07-01 20:19:10 -07:00
Xi Ge
b37330d3b7 [Fixit] Add a fixit for converting non-trailing closures to trailing closures.
Reminded by Ben's last commit of code completion, I noticed that some users
do not use trailing closures when helping migrating their code. To enhance the discoverability
of this feature, this fix helps users to convert non-trailing closures to trailing
closures. To ensure disambiguity after conversion, we check name conflict before adding
the note.
2016-07-01 19:44:56 -07:00
Rintaro Ishizaki
ba2e4e144f [Fix-it] In fixItAvailableAttrRename, handle the case args is TupleShuffleExpr (#3040)
Also, handle the ParenExpr is trailing closure case.

Fix-it used to add `fn: ` label before trailing closure:

   // (tuple_shuffle_expr (paren_expr trailing-closure)) case:
   @available(*, unavailable, renamed: "bar(fn:)")
   func foo(closure: () -> Int) {}
   foo { 0 }

   // (paren_expr trailing-closure) case:
   @available(*, unavailable, renamed: "bar(fn:)")
   func foo(_: () -> Int) {}
   foo { 0 }

   // (tuple_shuffle_expr (tuple_expr trailing-closure)) case:
   @available(*, unavailable, renamed: "bar(x:fn:)")
   func oldFunc6(_ x: Int, y: @noescape () -> Int) { }
   foo(0) { 1 }
2016-07-01 12:58:34 +09:00
Ben Langmuir
ea848aeaae Rename C++ macro 'defer' -> 'SWIFT_DEFER'
In C++ we can't have nice things. The macro name 'defer' collided with
use of 'defer' in the Tokens.def file and we were already doing horrible
workarounds in a couple of places to allow them to be included into the
same file. So use a less awesome but more robust name (thanks to Joe for
suggesting SWIFT_DEFER).

Incidentally, sort a bunch of #inlcudes.
2016-06-29 14:57:58 -07:00
Xi Ge
c994a3b36c Specify the underlying type of enum class. 2016-06-21 10:48:04 -07:00
Xi Ge
286b18fb07 Address Jordan's code review comments. 2016-06-21 10:43:35 -07:00
Xi Ge
7beb451993 [fixit] Provide a fixit when c-style loop is counting down. 2016-06-20 17:38:05 -07:00
Doug Gregor
2807a17eb8 [Type checker SR-899] Warning on missing ".self" for single-parameter functions.
Due to a modeling error in the type checker's folding of type
references into type expressions, code such as "strideof(Int)" would
be accepted without the required ".self". Commit
4a60b6cbf4 fixes the modeling issue but
left the historical accepts-invalid; now, diagnose these cases with a
warning + Fix-It to ease the transition.

Fixes SR-899.
2016-06-12 22:31:59 -07:00
Doug Gregor
01682af23a Revert "[Type checker] Be more rigorous about extracting argument labels from calls."
This reverts commit 93dac8f759.
2016-06-03 16:29:31 -07:00
Doug Gregor
93dac8f759 [Type checker] Be more rigorous about extracting argument labels from calls.
Whenever we have a call, retrieve the argument labels from the
argument structurally and associate them with the callee. We were
previously doing this as a separate AST walk (which was unnecessary),
so fold that into constraint generation for a CallExpr.

This is a slightly-pared-back version of
3753d779bc that isn't so rigid in its
interpretation of ASTs. I'll tighten up the semantics over time.
2016-06-03 14:45:21 -07:00
Doug Gregor
4a60b6cbf4 [Type checker] Don't fold the parentheses around call arguments into a TypeExpr.
TypeExpr formation from expressions is eager, and was pulling in the
parentheses used to form a call argument, e.g.,

  strideof(Int)

would end up being a CallExpr whose argument was a TypeExpr containing
the type "(Int)". This had the side effect of not requiring ".self"
where it should (as reported in SR-899), e.g., the correct code for
the above would be:

  strideof(Int.self)

Don't pull the parentheses of a call argument into the TypeExpr, so we
get a more sane AST. This would fix SR-899, but because SE-0090 is in
limbo right now, we don't actually want to require the initial code to
be considered well-formed right now. Therefore, put a hack into the
checking for ".self" that ignores this specific case.
2016-06-03 13:44:09 -07:00
Doug Gregor
ee85891d11 Revert "[Type checker] Be more rigorous about extracting argument labels from calls."
This reverts commit 3753d779bc. It's
causing some type-inference problems I need to investigate.
2016-06-03 10:21:27 -07:00
Doug Gregor
3753d779bc [Type checker] Be more rigorous about extracting argument labels from calls.
Whenever we have a call, retrieve the argument labels from the
argument structurally and associate them with the callee. We were
previously doing this as a separate AST walk (which was unnecessary),
so fold that into constraint generation for a CallExpr. We were also
allowing weird ASTs to effectively disable this information: tighten
that up and require that CallExprs always have a ParenExpr, TupleExpr,
or (as a temporary hack) a TypeExpr whose representation is a
TupleTypeRepr as their argument prior to type checking. This gives us
a more sane AST to work with, and guarantees that we aren't losing
label information.

From the user perspective, this should be NFC, because it's mostly AST
cleanup and staging.
2016-06-02 17:15:51 -07:00
Slava Pestov
609b2440aa Sema: Clean up availability code a bit, NFC 2016-06-01 23:12:48 -07:00
Jordan Rose
ceefc13db4 Remove debugging code from 258e2bb4.
Thanks, Robert!
2016-06-01 19:11:06 -07:00
Jordan Rose
258e2bb45c Provide fix-its when implementing a protocol method with bridged types. (#2799)
This is the protocol version of 7bfdd4a2: if a protocol requirement
has a newly-bridged type (say, 'URL' instead of 'NSURL'), then any
conforming types will need to update their implementations of the
requirement. Reuse the override-checking mechanism to do so when
we're reasonably confident about it.

This slots the checking into the existing protocol diagnostics, which
doesn't result in the best user experience.

    note: protocol requires property 'prop' with type 'Refrigerator?'
      var prop: Refrigerator? { get }
          ^
    note: candidate has non-matching type 'APPRefrigerator?'
      var prop: APPRefrigerator? {
          ^     ~~~~~~~~~~~~~~~~
                Refrigerator?

But we can come back and improve that later; right now this is better
than nothing.

rdar://problem/26237030
2016-06-01 14:03:21 -07:00
Doug Gregor
d66f724f3c [Type checker] Make sure that the omit-needless-words logic validates decls.
With the introduction of near-miss checking for optional @objc
protocol requirements, the omit-needless-words logic within the type
checker started being applied to arbitrary declarations that might not
have been type-checked, leading to crashes in various multi-file
scenarios that I wasn't able to reduce down to a sensible test
case. Make sure these declarations get type-checked, fixing
rdar://problem/26413181.
2016-05-24 16:47:08 -07:00
Jordan Rose
5343b594de Don't try to apply fix-its for renamed operators.
...or renaming to operators, unless we're sure the original thing was
an operator expression. There are just a lot of ways this can be
screwed up.

(Some cases of this can certainly be implemented. I may file a
StarterBug later.)
2016-05-20 16:58:50 -07:00
Jordan Rose
ced32f5714 Fix renaming fix-it when trailing closures are present.
Not crashing isn't good enough; we need to actually replace the
right text!

rdar://problem/26305887
2016-05-20 16:58:50 -07:00
Jordan Rose
41894742b0 Handle trailing closures when renaming argument labels.
Fixes 797260939 to not crash when all argument labels match except
for the missing label of a trailing closure. (This is specifically
for the fix-it generated for calling an unavailable-and-renamed API,
not for just getting the argument labels wrong in a normal call.)

rdar://problem/26234493
2016-05-12 14:13:15 -07:00
Doug Gregor
3650ce8ecd SE-0064 / SR-1239: Fix-Its for string-literal selectors naming property accessors.
When we see a string literal used to initializer a Selector, and that
string literal names the selector for the getter or setter of an
Objective-C property, suggest #selector(getter: ...) or

This completes SE-0064. Big thanks for Alex Hoppen (@ahoppen) for his
contributions here.
2016-05-11 23:03:37 -07:00
Slava Pestov
3bc64f37b8 Sema: Re-purpose unavailable override checking code for protocol conformances
This was easy with a bit of refactoring, but eventually I'd love to
converge override checking and witness checking logic a bit more.

Fixes <rdar://26183366>.
2016-05-11 22:51:32 -07:00
Jordan Rose
f952d2ee3a Provide fix-its when overriding something that's been renamed.
This is the second half of the previous commit. The most common case
of this will be due to the new rules for imported Objective-C API,
but it will also catch things like "I forgot to make the first
parameter not have an argument label".
2016-05-09 16:02:35 -07:00
Jordan Rose
e67fe08a26 Improve message when trying to override an unavailable member. 2016-05-09 16:02:35 -07:00
Doug Gregor
55a3f5398c [Clang importer] Import Swift 2 "stubs" to improve errors in "Swift 2" code.
When attempting to compile Swift 2 code (or any Swift code using the
Swift 2 names) in Swift 3, the compiler diagnostics are often entirely
useless because the names have changed radically enough that one
generally gets "no member named 'foo'" errors rather than a helpful
"'foo' was renamed to 'bar'" error. This makes for a very poor user
experience when (e.g.) trying to move Swift 2 code forward to Swift 3.

To improve the experience, when the Swift 2 and Swift 3 names of an
API differ, the Clang importer will produce a "stub" declaration that
matches the Swift 2 API. That stub will be marked with a synthesized
attribute

  @available(unavailable, renamed: "the-swift-3-name")

that enables better diagnostics (e.g., "'foo' is unavailable: renamed
to 'bar') along with Fix-Its (courtesy of @jrose-apple's recent work)
that fix the Swift 2 code to compile in Swift 3.

This change addresses much of rdar://problem/25309323 (concerning QoI
of Swift 2 code compiled with a Swift 3 compiler), but some cleanup
remains.
2016-05-06 21:12:20 -07:00
Jordan Rose
e09be3bdc9 Continue improving initializers in @available(renamed:).
Refinement of d858cc96. Handle members renamed to initializers as well
as free functions renamed to initializers.
2016-05-06 14:56:19 -07:00
Jordan Rose
d858cc96c7 Improve handling of initializers in @available(renamed:).
If we know the renamed thing is being called, we can just use
"Foo(...)" in the resulting expression (rather than "Foo.init(...)").
2016-05-06 13:22:58 -07:00
Jordan Rose
2fa1626579 Improve diagnostic text for @available(renamed:).
We don't want to show the funny "getter:Foo.bar(self:)" syntax to
developers, so whenever possible be a little more explicit.

    'foo' has been replaced by 'X.newFoo'
    'bar(x:)' has been replaced by property 'X.bar'
    'baz(x:y:)' has been replaced by instance method 'X.baz(y:)'

(We do run up against the limitation of a string -- this diagnostic
does not do any lookup to find out if the resulting decl actually exists.)
2016-05-05 18:07:39 -07:00
Jordan Rose
2c25d85cdf Handle "setter:" in @available(renamed:).
Example:

    @available(*, unavailable, renamed: "setter:CGRect.diagonal(self:_:)")
    func scale(_ rect: inout CGRect, toDiagonalLength length: CGFloat)

(My examples are getting more and more contrived, but there you go.)

This is pretty much the same as the getter handling, except that we also
want to strip off the '&' at the call site.
2016-05-05 14:46:34 -07:00
Jordan Rose
52caa75c11 Fix fix-it ranges for instance method @available(renamed:).
While I'm at it, prefer deleting trailing commas and space to leading
commas and space when removing an argument. That's a little more
aesthetically pleasing. We still have to delete a preceding comma if
it's the last argument that's being removed.
2016-05-05 14:46:34 -07:00
Jordan Rose
272e938876 Handle "getter:" in @available(renamed:).
Example:

    @available(*, unavailable, renamed: "getter:UIColor.CIColor(self:)")
    func convertToCIColor(_ color: UIColor) -> CIColor

This syntax looks weird, but it's the same as what's used by
NS_SWIFT_NAME. I intend to improve the diagnostic text once I have
all the fix-its working.

Next up: setters!
2016-05-05 14:46:34 -07:00
Jordan Rose
894318cfe0 Allow instance member syntax in @available(renamed:).
Example:

    @available(*, unavailable, renamed: "Sequence.enumerated(self:)")
    func enumerate<Seq: SequenceType>(_ sequence: Seq) ->
        EnumerateSequence<Seq>

This will allow us to reuse this logic to suggest fixes for APIs
turned into members by NS_SWIFT_NAME.
2016-05-04 14:17:15 -07:00
Jordan Rose
2966d99dbb Fix a use-after-delete in ec59bf9f caught by ASan. 2016-04-29 10:33:01 -07:00
Jordan Rose
797260939e Handle argument labels in @available(renamed:"...")
Fixes SR-1008 / rdar://problem/25276961
2016-04-28 20:21:30 -07:00
Jordan Rose
99a7b13dbd Move TypeChecker::diagnoseDeprecated into MiscDiagnostics.
It's going to share some helper functions with
TypeChecker::diagnoseExplicitUnavailability, which is already there.

Also, avoid unnecessarily putting some lambdas on the heap by using
llvm::function_ref.

No functionality change.
2016-04-28 20:21:30 -07:00
Jordan Rose
ec59bf9f18 Move helper function 'diagnoseArgumentLabelError' to MiscDiagnostics.
Groundwork for SR-1008. No functionality change.
2016-04-28 20:21:30 -07:00
Doug Gregor
4d59d71e12 [Conformance checking] Apply omit-needless-words for near-miss checking.
The differences between Swift 2 and Swift 3 names can be very
significant, when the Swift 2 names have a lot of restated type
information. These differences end up disabling the near-miss
heuristics because the magnitude of the change is so high. Therefore,
apply the omit-needless-words heuristics to the potential witness and
the requirement before scoring them.

Should finish up rdar://problem/25159872 for real.
2016-04-22 14:50:03 -07:00
Doug Gregor
8802d6d52a Improve diagnostics for selector collisions with @objc optional requirements.
When an optional requirement of an @objc protocol has a selector that
collides with an entity that has a different *Swift* name but produces
an Objective-C method with the same selector, we have an existing
diagnostic complaining about the conflict. In such cases, make a few
suggestions (with Fix-Its) to improve the experience:

* Change Swift name to match the requirement, adding or modifying the
  @objc as appropriate.
* Add "@nonobjc" to silence the diagnostic, explicitly opting out of
  matching an @objc requirement.

This is intended to help with migration of Swift 2 code into Swift
3. The Swift 2 code will produce selectors that match Objective-C
methods in the protocol from Swift names that don't match; this helps
fix up those Swift names so that we now match.

Fixes the rest of rdar://problem/25159872. In some sense, it's a
stop-gap for more detailed checking of near-misses for optional
requirements, but it's not clear how wide-reaching such changes would
be.
2016-04-19 10:22:23 -07:00
Greg Parker
125a146365 Revert "[Sema] Improve diagnostics for witness mismatches against @objc protocols." and "Improve diagnostics for selector collisions with @objc optional requirements."
This reverts commits 46269299cd
and 27279866ad
and c826a408dd.

The changes broke test bots, including
https://ci.swift.org/job/oss-swift-package-osx/1348/
2016-04-19 05:52:33 -07:00
Doug Gregor
27279866ad Improve diagnostics for selector collisions with @objc optional requirements.
When an optional requirement of an @objc protocol has a selector that
collides with an entity that has a different *Swift* name but produces
an Objective-C method with the same selector, we have an existing
diagnostic complaining about the conflict. In such cases, make a few
suggestions (with Fix-Its) to improve the experience:

* Change Swift name to match the requirement, adding or modifying the
  @objc as appropriate.
* Add "@nonobjc" to silence the diagnostic, explicitly opting out of
  matching an @objc requirement.

This is intended to help with migration of Swift 2 code into Swift
3. The Swift 2 code will produce selectors that match Objective-C
methods in the protocol from Swift names that don't match; this helps
fix up those Swift names so that we now match.

Fixes the rest of rdar://problem/25159872. In some sense, it's a
stop-gap for more detailed checking of near-misses for optional
requirements, but it's not clear how wide-reaching such changes would
be.
2016-04-18 17:08:06 -07:00
Chris Lattner
183ae24249 Upgrade deprecation warnings about snake case identifiers, C style for loops,
and : vs = in attributes to errors.
2016-04-17 10:20:12 -07:00
Chris Lattner
8e12008d2b Mark tuple splat and ++/-- as errors instead of warnings. This
wraps up SE-0004 and SE-0029.

I consider the diagnostic changes in Constraints/lvalues.swift to be
indicative of a QoI regression, but I'll deal with that separately.
2016-04-16 23:44:22 -07:00
Chris Lattner
ab14e6706f Progress towards implementing SE-0049 - Allow autoclosure in parameter types
as well as on parameter decls.  Also, tighten up the type checker to look at
parameter types instead of decl attributes in some cases (exposing a type
checker bug).

Still TODO:
 - Reject autoclosure/noescape on non-parameter types.
 - Move stdlib and other code to use noescape and autoclosure in the right
   spot.
 - Warn about autoclosure/noescape on parameters decls, with a fixit to move it.
 - Upgrade the warning to an error.
2016-04-14 23:13:43 -07:00
Jordan Rose
bc83940301 Make pointer nullability explicit using Optional.
Implements SE-0055: https://github.com/apple/swift-evolution/blob/master/proposals/0055-optional-unsafe-pointers.md

- Add NULL as an extra inhabitant of Builtin.RawPointer (currently
  hardcoded to 0 rather than being target-dependent).
- Import non-object pointers as Optional/IUO when nullable/null_unspecified
  (like everything else).
- Change the type checker's *-to-pointer conversions to handle a layer of
  optional.
- Use 'AutoreleasingUnsafeMutablePointer<NSError?>?' as the type of error
  parameters exported to Objective-C.
- Drop NilLiteralConvertible conformance for all pointer types.
- Update the standard library and then all the tests.

I've decided to leave this commit only updating existing tests; any new
tests will come in the following commits. (That may mean some additional
implementation work to follow.)

The other major piece that's missing here is migration. I'm hoping we get
a lot of that with Swift 1.1's work for optional object references, but
I still need to investigate.
2016-04-11 20:06:38 -07:00
Michael Gottesman
7361e35bb9 Revert "Putting white spaces in between if/while clauses and braces." 2016-04-01 22:00:25 -07:00
Ge Sen
7dd61bdfa9 [gardening] Put white spaces in between if/while clauses and braces where it is missing.
For instance:

'if (foo){' => 'if (foo) {'
2016-04-02 08:22:23 +08:00