Commit Graph

974 Commits

Author SHA1 Message Date
John McCall
5eecc6ac07 Only warn about self capture in nested closures until Swift 6.
Swift has diagnosed implicit uses of class-reference `self` in
escaping closures for a long time as potentially leading to reference
cycles.  PR #35898 fixed a bug where we failed to diagnose this
condition in nested closures.  Unfortunately, treating this as an
error has proven problematic because there's a lot of code doing
it.  Requiring that code to be thoroughly stamped out before we
ship a compiler is just too much to ask.  Stage the fix in by
treating it as a warning in Swift versions prior to 6.

As with the non-nested case, this warning can be suppressed by
explicitly either capturing `self` or spelling out `self.` in the
access.

Fixes rdar://80847025.
2021-08-18 21:44:23 -04:00
Suyash Srijan
23c1d66eaf [NFC, Typechecker] Remove UnsupportedProtocolVisitor and checkUnsupportedProtocolType() 2021-08-16 18:30:26 +03:00
willtunnels
319b3e64aa Add support for opaque result types in structural positions (#38392)
* [TypeResolver][TypeChecker] Add support for structural opaque result types

* [TypeResolver][TypeChecker] Clean up changes that add structural opaque result types
2021-08-03 23:45:02 -04:00
Ben Barham
7e7b521abd [Diagnostics] Allow matching accessors and functions for a renamed decl
A lookup on the name provided by `renamed` in `@available` returns the
VarDecl. If the name specified a getter or setter, make sure to grab the
corresponding accessor when comparing candidates.

We currently ignore the basename and parameters specified in the name
for accessors. Checking them would only cause a getter/setter not to
match, there can never be a conflict. Since this is a best effort match
anyway, this seems fine.
2021-08-03 08:46:44 +10:00
Hamish Knight
7d6dac6855 [Sema] Correct label fix-its for multiple trailing closures
Update the logic to account for multiple trailing
closures.

rdar://81278194
2021-08-02 12:59:43 +01:00
Pavel Yaskevich
66815f9d25 [MiscDiagnostics] Downgrade plain type use error to a warning for certain positions
In Swift < 6 warn about plain type name passed as an
argument to a subscript, dynamic subscript, or ObjC
literal since it used to be accepted.

Resolves: rdar://80270126
2021-07-07 14:36:29 -07:00
Pavel Yaskevich
333fdbcca4 [MiscDiagnostics] Store a reference to a call node together with its arguments 2021-07-07 12:22:17 -07:00
Pavel Yaskevich
9c54d7916a Merge pull request #37897 from mininny/control-flow-suggestion-for-optional
[Diagnostics] Offer 'is' replacement for unused 'if let' expression with optional operand
2021-06-22 10:24:59 -07:00
Minhyuk Kim
f85cb50af2 [Sema] Add diagnostics handling for nested expressions 2021-06-17 11:25:51 +09:00
Minhyuk Kim
c3ab99a405 [Sema] Offer 'is' replacement for unused 'if let' expression when the operand is optional 2021-06-14 00:40:03 +09:00
Pavel Yaskevich
299da73ec4 [MiscDiagnostics] NFC: Add an assert that arguments a valid to .nan comparison diagnostic
Make sure that both arguments are valid before checking conformance
to `FloatingPoint`. This helps us to debug reports of crashes in
`conformsToKnownProtocol` referencing arguments (rdar://78920375).

Since this diagnostic should only be run on type-checked AST,
it's unclear what caused one of the arguments to have null type.
2021-06-10 12:23:24 -07:00
Hamish Knight
cc62c116f8 [ASTWalker] Don't visit capture list vars twice
Previously we were walking them once when visiting
the capture list, and then again as a part of the
pattern binding decl. Change the logic to only
visit them as a part of their pattern binding decl.
2021-06-08 22:56:05 +01:00
Slava Pestov
5bdf189a5f Sema: Remove a usage of hasComputedGenericSignature() from expression checker diagnostics
Removing this exposed a re-entrant diagnostic emission, so let's fix that too.
2021-05-26 18:48:29 -04:00
Hamish Knight
46fa6e5721 [AST] Improve BinaryExpr
Abstract away the TupleExpr gunk and expose
`getLHS` and `getRHS` accessors. This is in
preparation for completely expunging the use
of TupleExpr as an argument list.
2021-05-19 14:48:01 +01:00
Slava Pestov
131d3f4bce Sema: Pass down a ModuleDecl instead of a DeclContext to conformsToProtocol()
... and a bunch of follow-up simplifications pushing ModuleDecls further
up, since I couldn't resist the yak shave.
2021-05-17 16:34:18 -04:00
Doug Gregor
abfc9bcdc4 Add @_implicitSelfCapture attribute to disable "self." requirement.
Add a new parameter attribute `@_implicitSelfCapture` that disables the
requirement to explicitly use `self.` to refer to a member of `self`
in an escaping closure.

Part of rdar://76927008.
2021-04-20 17:26:07 -07:00
Azoy
9ed732f0ab Introduce isDecl and getDeclType
fix enum logic issue

fix tests

guard against null types
2021-04-20 02:22:16 -04:00
Ben Barham
3de83aca66 [ClangImporter] Add @completionHandlerAsync for imported decls
Implicitly add the @completionHandlerAsync attribute for ObjCMethodDecl
that have a completion handler. Adds a link from the non-async to the
async function for use in diagnostics and refactorings.

Resolves rdar://74665226
2021-03-31 08:39:12 +10:00
Kavon Farvardin
efbb0f1a14 implement typechecking for effects specifiers on 'get' accessors
The basic rule is that the protocol requirement
describes the maximal set of effects that the
property is allowed to have. Thus, witnesses
must have the same or fewer effects specifiers
on the getter.

For class inheritance overrides, you can remove
effects freely, as long as you stay within
the bounds of the normal override restrictions.
But, you cannot override with more effects than
the base member has. Same goes for protocol
member overrides.

Furthermore, we disallow key paths to effectful
properties/subscripts, which also cannot be @objc.
2021-03-26 07:54:53 -07:00
Evan Wilde
8516c0c5aa Fix crash with failed typecheck
The walker was crashing if something failed to typecheck since the type
wasn't available. I've added a little test to ensure that not only do we
not crash, but continue checking within the closure.
2021-03-24 22:54:15 -07:00
Evan Wilde
0fbbd896e6 Migrate checker to MiscDiagnostics 2021-03-24 17:51:07 -07:00
Alex Hoppen
fa9f3f3337 [Sema] Correctly diagnose passing tuple as only argument to function with multiple parameters
If a tuple is passed as the only argument to a function that takes two unnamed arguments, we try to diagnose the missing argument label. However, in the old diagnose code we didn’t distinguish between non-existing arguments and arguments without labels; both behaved the same.

Thus, the missing second argument in the function call would line up with the empty second argument label, not producing a diagnostic, but hitting an assertion later on.

Distinguish between the two to fix the issue.

Fixes rdar://64319340
2021-03-19 12:58:17 +01:00
Doug Gregor
85611dbf25 Allow marker protocols as existentials (but still ban casts)
There is no problem with having an existential value that involves a
marker protocol. However, since there is no runtime checking for
marker protocols, ban "as?" and "is" casts to them.
2021-02-18 23:44:39 -08:00
Erik Eckstein
a17f8c2f3f SILOptimizer: add a diagnostics pass to warn about lifetime issues with weak references.
The DiagnoseLifetimeIssuesPass pass prints a warning if an object is stored to a weak property (or is weakly captured) and destroyed before the property (or captured reference) is ever used again.
This can happen if the programmer relies on the lexical scope to keep an object alive, but copy-propagation can shrink the object's lifetime to its last use.
For example:

  func test() {
    let k = Klass()
      // k is deallocated immediately after the closure capture (a store_weak).
      functionWithClosure({ [weak k] in
                            // crash!
                            k!.foo()
                          })
    }

Unfortunately this pass can only catch simple cases, but it's better than nothing.

rdar://73910632
2021-02-15 11:11:35 +01:00
John McCall
3918fb0e42 Merge pull request #35898 from rjmccall/diagnose-implicit-nested-self
Diagnose the implicit use of self in nested closures
2021-02-12 18:06:50 -05:00
John McCall
f29074d8b6 Diagnose the implicit use of self in nested closures.
Fixes SE-14120.
2021-02-10 18:44:42 -05:00
Becca Royal-Gordon
899d1a47e5 [NFC] Centralize ObjCSelector helper 2021-02-09 14:17:35 -08:00
Slava Pestov
e675bee26c AST: Split off DependencyCollector.h from EvaluatorDependencies.h
Also remove some unnecessary #includes from DependencyCollector.h,
which necessitated adding #includes in various other files.
2020-12-23 00:00:25 -05:00
Richard Wei
de2dbe57ed [AutoDiff] Bump-pointer allocate pullback structs in loops. (#34886)
In derivatives of loops, no longer allocate boxes for indirect case payloads. Instead, use a custom pullback context in the runtime which contains a bump-pointer allocator.

When a function contains a differentiated loop, the closure context is a `Builtin.NativeObject`, which contains a `swift::AutoDiffLinearMapContext` and a tail-allocated top-level linear map struct (which represents the linear map struct that was previously directly partial-applied into the pullback). In branching trace enums, the payloads of previously indirect cases will be allocated by `swift::AutoDiffLinearMapContext::allocate` and stored as a `Builtin.RawPointer`.
2020-11-30 15:49:38 -08:00
Doug Gregor
810f1cdec0 [Sema] Perform actor isolation checking across the whole function at once.
Rather than performing actor isolation checking as part of
"miscellaneous" diagnostics on an expression, do it on the whole
function at once. This should not change behavior by itself.
2020-11-16 21:58:39 -08:00
Doug Gregor
33cfbbdd72 [Concurrency] Don't diagnose missing "self." in async let autoclosures. 2020-11-04 23:18:51 -08:00
Slava Pestov
a072655599 Sema: Rename some availability checking entry points 2020-10-28 00:30:07 -04:00
Doug Gregor
16104d8045 [Concurrency] Don't lose name information from completion-handler arguments.
When a completion handler parameter has a selector piece that ends with
"WithCompletion(Handler)", prepend the text before that suffix to the
base name or previous argument label, as appropriate. This ensures that
we don't lose information from the name, particularly with delegate names.
2020-10-22 13:32:03 -07:00
Doug Gregor
24ea8becc8 [Concurrency] Move removal of leading "get" for async imports.
Name adjustments should be performed by omitNeedlessWords(), not the
early classifcation of async imports.
2020-10-21 21:48:52 -07:00
Slava Pestov
94e999a1b5 Sema: Pull availability checking out of resolveType()
We used to diagnose references to unavailable declarations in
two places:

- inside Exprs, right after type checking the expression
- inside TypeReprs, from resolveType()

In broad terms, resolveType() is called with TypeReprs
stored inside both Stmts and Decls.

To handle the first case, I added a new overload of
diagAvailability() that takes a Stmt, to be called from
typeCheckStmt(). This doesn't actually walk into any Exprs
stored inside the statement; this means it only walks
Patterns and such.

For the second case, a new DeclAvailabilityChecker is
now defined in TypeCheckAccess.cpp. It's structure is
analogous to the other three walkers there:

- AccessControlChecker
- UsableFromInlineChecker
- ExportabilityChecker

The new implementation of availability checking for types
introduces a lot more code than the old online logic
it replaces. However, I hope to consolidate some of the
code duplication among the four checkers that are defined
in TypeCheckAccess.cpp, and do some other cleanups that
will make the benefit of the new approach apparent.
2020-10-14 23:42:02 -04:00
Pavel Yaskevich
461eafff54 [ConstraintSystem] NFC: Move ConstraintSystem.h to include/swift/Sema 2020-10-08 10:45:47 -07:00
Slava Pestov
fe9d1ed595 Sema: Use ASTScope::lookupSingleLocalDecl() in VarDeclUsageChecker::handleIfConfig() 2020-09-28 17:50:52 -04:00
Robert Widmann
ee35a4fe18 Remove NameLookupFlags::KnownPrivate 2020-09-21 10:37:41 -06:00
Robert Widmann
259e1a94c9 Remove UnqualifiedLookupFlags::KnownPrivate 2020-09-21 10:37:41 -06:00
Slava Pestov
d7f4b1a1bd AST: Capture list bindings now point back to their parent CaptureListExpr
We'll need this to get the right 'selfDC' when name lookup
finds a 'self' declaration in a capture list, eg

class C {
  func bar() {}
  func foo() {
    _ = { [self] in bar() }
  }
}
2020-09-18 02:59:15 -04:00
Doug Gregor
cb6429530c [Concurrency] Actor-isolated members cannot satisfy protocol requirements.
Enforce the actor-isolation constraint that an actor-isolated member
(e.g., a non-async instance method or an instance property) cannot be
used to conform to a protocol requirement.
2020-09-17 13:36:57 -07:00
Doug Gregor
3c49e46f4f Merge pull request #33906 from DougGregor/concurrency-actors
[Concurrency] Basic support for actor classes and actor isolation
2020-09-11 15:10:45 -07:00
Doug Gregor
e00ba43b9a [Concurrency] Implement basic actor isolation rules.
Implement a basic set of isolation rules for actors, which includes:

* Asynchronous actor methods can be invoked on any actor instance.
* All mutable instance properties and synchronous instance methods are
only accessible via "self" or "super" within the context of the actor.
* Closures defined within an actor method are considered to be a
context distinct from the actor itself, are therefore are subject to
the same restrictions as above.

Together with a scheduler that ensures that asynchronous invocations
for a particular actor are serialized (at least up until they hit a
suspension point or return), this serves to isolate the actor's
instance state in a shallow manner: references to shared mutable state
can still be passed among actors, code can access global variables,
and one can still form and pass around unsafe pointers.

Pair this with some basic checking within actor contexts that
identifies a few obvious potential kinds of race conditions:

* References to captured mutable local variables from within closures.
* References to mutable global and static/class variables.

The latter are warnings, for which we currently don't have a great
suppression mechanism. That, and a lot of tuning, are still to come.
2020-09-10 21:22:00 -07:00
Suyash Srijan
49e7c6126c [Diagnostics] Diagnose comparisons with '.nan' and suggest using '.isNan' instead (#33860)
* [AST] Add 'FloatingPoint' known protocol kind

* [Sema] Emit a diagnostic for comparisons with '.nan' instead of using '.isNan'

* [Sema] Update '.nan' comparison diagnostic wording

* [Sema] Explicitly check for either arguments to be '.nan' and tweak a comment

* [Test] Tweak some comments

* [Diagnostic] Change 'isNan' to 'isNaN'

* [Sema] Fix a bug where firstArg was checked twice for FloatingPoint conformance and update some comments

* [Test] Fix comments in test file

* [NFC] Add a new 'isStandardComparisonOperator' method to 'Identifier' and use it in ConstraintSystem

* [NFC] Reuse argument decl extraction code and switch over to the new 'isStandardComparisonOperator' method

* [NFC] Update conformsToKnownProtocol to accept DeclContext and use it to check for FloatingPoint conformance
2020-09-09 22:08:42 +01:00
Anthony Latsis
492156c10f Remove SubscriptDecl::getBodyResultTypeLoc 2020-08-19 00:09:10 +03:00
Anthony Latsis
21faa48298 Remove FuncDecl::getBodyResultTypeLoc 2020-08-19 00:09:10 +03:00
Slava Pestov
397e36a6f0 Sema: Remove TypeChecker::lookupConstructor() 2020-08-18 02:00:20 -04:00
Slava Pestov
45fc0bc4db Sema: Replace some calls to getDeclaredType() with getDeclaredInterfaceType() 2020-07-31 13:39:02 -04:00
Rintaro Ishizaki
59196975b7 Merge pull request #32696 from rintaro/ide-completion-typecheckatloc
[CodeCompletion] Only type check target statement and related decls in function body
2020-07-28 19:12:31 -07:00
Doug Gregor
73f07a6f0f Merge pull request #33092 from DougGregor/forward-trailing-closure-matching-sourcecompat-backward-bias
[SE-0286] Forward matching of trailing closure arguments
2020-07-28 14:11:15 -07:00