Commit Graph

4105 Commits

Author SHA1 Message Date
Doug Gregor
6855dc474f Uses of @exclusivity(unsafe) variables are unsafe 2025-01-08 07:03:04 -08:00
elsh
c03abed00d Package optimization allows bypassing resilience, but that assumes the memory layout of the
decl being accessed is correct. When this assumption fails due to a deserialization error
of its members, the use site accesses the layout with a wrong field offset, resulting in
UB or a crash. The deserialization error is currently not caught at compile time due to
LangOpts.EnableDeserializationRecovery being enabled by default to allow for recovery of some
of the deserialization errors at a later time. In case of member deserialization, however,
it's not necessarily recovered later on.

This PR tracks whether member deserialization had an error by recursively loading members and
checking for deserialization error, and fails and emits a diagnostic. It provides a way to
prevent resilience bypassing when the deserialized decl's layout is incorrect.

Resolves rdar://132411524
2025-01-07 21:51:49 -08:00
Anthony Latsis
9ae3cf1034 AST: Delete the DeclarationUnavailableFromAsynchronousContext diagnostic group
This group has not shipped yet and was added mainly to support test
coverage for d56b7df8a9. Now that we have
unit tests for this, delete the group, pending discussion.
2025-01-07 20:29:07 +00:00
Allan Shortlidge
2c52f057df Merge pull request #78414 from tshortli/back-deployed-without-body-redux
Sema: Diagnose `@backDeployed` functions with missing bodies in swiftinterfaces
2025-01-03 15:16:44 -08:00
Allan Shortlidge
7ea778f3a0 Sema: Diagnose @backDeployed functions with missing bodies in swiftinterfaces.
A `@backDeployed` function printed in a `.swiftinterface` must have a function
body so that SILGen can emit a fallback copy to call when the back deployed
function is unavailable. Previously, the compiler would crash in SILGen when
compiling an interface containing a back deployed function without a body.

Resolves rdar://141593108.
2025-01-03 09:15:12 -08:00
Joe Groff
5c4406b5e8 Add an @_addressableForDependencies type attribute.
This attribute makes it so that a parameter of the annotated type, as well as
any type structurally containing that type as a field, becomes passed as
if `@_addressable` if the return value of the function has a dependency on
the parameter. This allows nonescapable values to take interior pointers into
such types.
2025-01-02 21:33:51 -08:00
Doug Gregor
7d6e3776ba Merge pull request #78332 from DougGregor/strict-safety-improvements
Strict safety improvements
2025-01-02 08:25:02 -08:00
Doug Gregor
ba23f36f3e Diagnose the use of a typealias that involves unsafe types
As we do when referencing other kinds of declarations, if a
typealias isn't `@unsafe`, but it involves unsafe types,
diagnose the non-safety at the point of reference.
Fixes https://github.com/swiftlang/swift/issues/78220
2024-12-24 08:36:24 -08:00
Doug Gregor
aab36f63f2 Revert "Sema: Diagnose @backDeployed functions with missing bodies in swiftinterfaces" 2024-12-21 21:53:46 -08:00
Doug Gregor
419c47757c Don't diagnose uses of @unchecked Sendable conformances
The `@unchecked` conformance is effectively the same as
`@safe(unchecked)`, in that it asserts memory safety in a place where
it cannot be automatically checked. But once that has been asserted,
there is no reason to diagnose anywhere else.

While here, drop the "unsafe declaration here" note, which isn't
adding value but did add noise.

Thanks, Alex!
2024-12-20 23:16:27 -08:00
Doug Gregor
5b90b8851a Generalize protocol conformance options spelled via attribute and incorporate @unsafe
Protocol conformances have a handful attributes that can apply to them
directly, including @unchecked (for Sendable), @preconcurrency, and
@retroactive. Generalize this into an option set that we carry around,
so it's a bit easier to add them, as well as reworking the
serialization logic to deal with an arbitrary number of such options.

Use this generality to add support for @unsafe conformances, which are
needed when unsafe witnesses are used to conform to safe requirements.
Implement general support for @unsafe conformances, including
producing a single diagnostic per missing @unsafe that provides a
Fix-It and collects together all of the unsafe witnesses as notes.
2024-12-20 23:16:23 -08:00
Doug Gregor
1230045c9d Diagnose @preconcurrency imports as a strict safety issue
@preconcurrency imports disable Sendable checking, which can lead to
data races that undermine memory safety. Diagnose such imports, and
require `@safe(unchecked)` to suppress the diagnostic.
2024-12-20 23:15:41 -08:00
Doug Gregor
a86d942e5b Migrate "@unchecked Sendable" strict safety diagnostic to become a note associated with its type 2024-12-20 23:15:39 -08:00
Allan Shortlidge
bfd7752cdd Merge pull request #78327 from tshortli/back-deployed-without-body
Sema: Diagnose `@backDeployed` functions with missing bodies in swiftinterfaces
2024-12-20 18:00:03 -08:00
Doug Gregor
f57217f8dd Merge pull request #78307 from DougGregor/strict-safety-diags
Improve and collate diagnostics for uses of unsafe constructs in declarations
2024-12-20 14:53:59 -08:00
Allan Shortlidge
ebda3e2d44 Sema: Diagnose @backDeployed functions with missing bodies in swiftinterfaces.
A `@backDeployed` function printed in a `.swiftinterface` must have a function
body so that SILGen can emit a fallback copy to call when the back deployed
function is unavailable. Previously, the compiler would crash in SILGen when
compiling an interface containing a back deployed function without a body.

Resolves rdar://141593108.
2024-12-20 12:02:04 -08:00
Doug Gregor
02d7357a73 Diagnose references to unowned(unsafe) variables as unsafe uses 2024-12-20 07:35:33 -08:00
Doug Gregor
0ef32ac5b5 Diagnose references to nonisolated(unsafe) declarations in strict-concurrency code
A nonisolated(unsafe) declaration clearly indicates that the
declaration itself is unsafe, so it doesn't need to be diagnosted.
Instead, diagnose any reference to such a declaration that occurs
when strict concurrency is enabled. Make this a collatable unsafe use.
2024-12-20 07:35:23 -08:00
Doug Gregor
29f23bb66a Improve diagnostics for uses of unsafe declarations in functions
Instead of producing a warning for each use of an unsafe entity,
collect all of the uses of unsafe constructs within a given function
and batch them together in a single diagnostic at the function level
that tells you what you can do (add `@unsafe` or `@safe(unchecked)`,
depending on whether all unsafe uses were in the definition), plus
notes identifying every unsafe use within that declaration. The new
diagnostic renderer nicely collects together in a single snippet, so
it's easier to reason about.

Here's an example from the embedded runtime that previously would have
been 6 separate warnings, each with 1-2 notes:

```
swift/stdlib/public/core/EmbeddedRuntime.swift:397:13: warning: global function 'swift_retainCount' involves unsafe code; use '@safe(unchecked)' to assert that the code is memory-safe
395 |
396 | @_cdecl("swift_retainCount")
397 | public func swift_retainCount(object: Builtin.RawPointer) -> Int {
    |             `- warning: global function 'swift_retainCount' involves unsafe code; use '@safe(unchecked)' to assert that the code is memory-safe
398 |   if !isValidPointerForNativeRetain(object: object) { return 0 }
399 |   let o = UnsafeMutablePointer<HeapObject>(object)
    |           |                              `- note: call to unsafe initializer 'init(_:)'
    |           `- note: reference to unsafe generic struct 'UnsafeMutablePointer'
400 |   let refcount = refcountPointer(for: o)
    |                  |                    `- note: reference to let 'o' involves unsafe type 'UnsafeMutablePointer<HeapObject>'
    |                  `- note: call to global function 'refcountPointer(for:)' involves unsafe type 'UnsafeMutablePointer<Int>'
401 |   return loadAcquire(refcount) & HeapObject.refcountMask
    |          |           `- note: reference to let 'refcount' involves unsafe type 'UnsafeMutablePointer<Int>'
    |          `- note: call to global function 'loadAcquire' involves unsafe type 'UnsafeMutablePointer<Int>'
402 | }
403 |
```

Note that we have lost a little bit of information, because we no
longer produce "unsafe declaration was here" notes pointing back at
things like `UnsafeMutablePointer` or `recountPointer(for:)`. However,
strict memory safety tends to be noisy to turn on, so it's worth
losing a little bit of easily-recovered information to gain some
brevity.
2024-12-20 07:34:51 -08:00
Becca Royal-Gordon
443bd5d4ad Diagnose use of @_silgen_name and @abi together 2024-12-19 15:49:35 -08:00
Becca Royal-Gordon
c91cf69f2f Add some basic validation of vars and funcs
Check for:

• Matching decl kinds
• Matching PBD shapes (does every VarDecl on both sides have a counterpart?)
• Matching function effects
• Matching function arity (roughly)
2024-12-19 15:49:34 -08:00
Pavel Yaskevich
636525ebd9 Merge pull request #78171 from xedin/rdar-140300022
[TypeChecker/SILGen] Allow `any Sendable` to match `Any` while matching generic arguments
2024-12-17 20:24:34 -08:00
Doug Gregor
bd4a477cbd Suggest @safe(unchecked) when only the body of a declaration uses unsafe constructs
Also clean up some diagnostic text for the @unsafe/@safe(unchecked) suggestions.
2024-12-14 08:40:28 -08:00
Konrad `ktoso` Malawski
3ea940e304 Merge pull request #77730 from nickolas-pohilets/mpokhylets/isolated-deinit-version 2024-12-14 11:00:31 +09:00
Pavel Yaskevich
c8f3524961 [CSDiagnostics/Tests] Add tests for any Sendable vs. Any interaction in non-strict concurrency contexts 2024-12-13 09:35:34 -08:00
Doug Gregor
268d5ccbde Suppress strict safety diagnostics in @unsafe declarations
When a declaration is `@unsafe`, don't emit strict safety diagnostics
for uses of unsafe entities, constructs, or types within it. This
allows one to account for all unsafe behavior in a module using strict
memory safety by marking the appropriate declarations `@unsafe`.

Enhance the strict-safety diagnostics to suggest the addition of
`@unsafe` where it is needed to suppress them, with a Fix-It. Ensure
that all such diagnostics can be suppressed via `@unsafe` so it's
possible to get to the above state.

Also includes a drive-by bug fix where we weren't diagnosing unsafe
methods overriding safe ones in some cases.

Fixes rdar://139467327.
2024-12-12 21:22:41 -08:00
Mykola Pokhylets
5ac1cba8d1 Handle versioning of the IsolatedDeinit feature 2024-12-12 16:41:02 +09:00
Mykola Pokhylets
bc80529d02 Revert "Merge pull request #77438 from swiftlang/revert-77364-mpokhylets/non-experimental-isolated-deinit"
This reverts commit 11781a5fd1, reversing
changes made to 2ee2f1eb2c.
2024-12-12 16:41:02 +09:00
Pavel Yaskevich
93a8675e49 Merge pull request #76946 from pwongxy/diag-warn-on-for-var-loop
[Diagnostics] Improve warning suggestion for `var` in for loop
2024-12-10 18:01:25 -08:00
Peter Wong
c1473e84f9 [Diagnostics] Improve warning suggestion for var in for loop
When iterator consists of tuple of variable and iteration only mutates
the tuple partially, improve the warning message from "changing to 'let"
to "changing the pattern to '(..., case let, ...)"
2024-12-10 22:51:08 +08:00
Joe Groff
ac7a61679d Add an @_addressableSelf attribute to mark the self param of methods as addressable. 2024-12-06 16:54:01 -08:00
Joe Groff
a045d665bb Merge pull request #75282 from jckarter/addressable-params-1
[WIP] Prototype an `@_addressable` attribute that puts an argument at a stable address.
2024-12-05 09:17:26 -08:00
Joe Groff
3c0b08dbcb Prototype an @_addressable attribute that puts an argument at a stable address.
Many APIs using nonescapable types would like to vend interior pointers to their
parameter bindings, but this isn't normally always possible because of representation
changes the caller may do around the call, such as moving the value in or out of memory,
bridging or reabstracting it, etc. `@_addressable` forces the corresponding parameter
to be passed indirectly in memory, in its maximally-abstracted representation.
[TODO] If return values have a lifetime dependency on this parameter, the caller must
keep this in-memory representation alive for the duration of the dependent value's
lifetime.
2024-12-03 20:39:23 -08:00
Dmitrii Galimzianov
d56b7df8a9 Add DiagGroupID to Diagnostic
This change addresses the following issue: when an error is being wrapped in a warning, the diagnostic message will use the wrapper's `DiagGroupID` as the warning's name. However, we want to retain the original error's group for use. For example, in Swift 5, async_unavailable_decl is wrapped in error_in_future_swift_version. When we print a diagnostic of this kind, we want to keep the `DiagGroupID` of `async_unavailable_decl`, not that of `error_in_future_swift_version`.
To achieve this, we add `DiagGroupID` to the `Diagnostic` class. When an active diagnostic is wrapped in DiagnosticEngine, we retain the original `DiagGroupID`.

For illustration purposes, this change also introduces a new group: `DeclarationUnavailableFromAsynchronousContext`.

With this change, we produce errors and warnings of this kind with messages like the following:

```
global function 'fNoAsync' is unavailable from asynchronous contexts [DeclarationUnavailableFromAsynchronousContext]
global function 'fNoAsync' is unavailable from asynchronous contexts; this is an error in the Swift 6 language mode [DeclarationUnavailableFromAsynchronousContext]
```
2024-12-03 20:12:11 +01:00
Meghana Gupta
5b5acc64e0 Promote Nonescapable types to a language feature 2024-11-18 18:09:17 -08:00
Meghana Gupta
ae28d667ff Introduce LifetimeDependence experimental feature 2024-11-18 18:08:32 -08:00
Hamish Knight
b644cd87a9 [Sema] Ensure performStmtDiagnostics is called for CaseStmts
Previously we would check if we have a SwitchStmt,
and apply diagnostics such as `checkExistentialTypes`
to the CaseStmts individually. This however would
have been missed for `catch` statements. The change
to consistently call `performStmtDiagnostics` in
closures fixed this for `do-catch`'s in closures,
this commit fixes it for those outside of closures.
Because this is source breaking, the existential
diagnostic is downgraded to a warning until Swift
7 for catch statements specifically.

While here, also apply the ambiguous where clause
diagnostic to `catch` statements.
2024-11-12 18:26:54 +00:00
Doug Gregor
dd7ec7fc57 Merge pull request #77532 from DougGregor/experimental-flag-for-span-usage
Temporarily put uses of "Span" and "RawSpan" behind an experimental feature flag
2024-11-12 01:35:42 -08:00
Doug Gregor
7ffa5c324d Put warnings about unsafe constructs into a new diagnostic group Unsafe 2024-11-11 17:50:21 -08:00
Doug Gregor
531a1ab4c4 Temporarily put uses of "Span" and "RawSpan" behind an experimental feature flag
While Span is present, we don't yet have an official way to create Span
instances. Until then, put uses of Span and RawSpan behind an
experimental feature flag (`Span`) that must be set to use these.

Addresses rdar://139308307.
2024-11-11 16:18:33 -08:00
Konrad `ktoso` Malawski
aadc67ec0e Revert "Make IsolatedDeinit non-experimental" 2024-11-07 09:59:00 +09:00
Mykola Pokhylets
c139d1b1a7 Make IsolatedDeinit non-experimental 2024-11-05 12:19:01 +01:00
Meghana Gupta
c0a55e11d4 Merge pull request #77314 from meg-gupta/ossaflag
Remove -enable-ossa-modules for Synchronization and Distributed
2024-11-04 02:40:54 -08:00
Meghana Gupta
51090e4bc4 Diagnose when trying to import non-ossa module to ossa when implicit modules are disabled 2024-10-31 13:03:26 -07:00
Pavel Yaskevich
9dc1403a3c [CSDiagnostics] SE-0438: Add a tailored diagnostic for unsupported static member references
Libraries of modules built with older compilers (< 6.1) don't have
symbols required to enable staitc member support in key path context.
2024-10-30 10:53:42 -07:00
Hamish Knight
b4b99e9d28 Merge pull request #77248 from hamishknight/regex-avail-diag
[Sema] Add logic to diagnose regex feature availability
2024-10-29 09:45:00 +00:00
Gábor Horváth
708782d40b Merge pull request #77100 from swiftlang/gaborh/empty-value-type-diagnostic
[cxx-interop] Mark some zero-sized value types as unavailable
2024-10-28 18:08:40 +00:00
Hamish Knight
9d4a78678a [Sema] Add logic to diagnose regex feature availability
Add the necessary compiler-side logic to allow
the regex parsing library to hand back a set of
features for a regex literal, which can then be
diagnosed by ExprAvailabilityWalker if the
availability context isn't sufficient. No tests
as this only adds the necessary infrastructure,
we don't yet hand back the features from the regex
parsing library.
2024-10-28 17:09:47 +00:00
Gabor Horvath
22b46d3c9c [cxx-interop] Mark some zero-sized value types as unavailable
Currently, we do not support exporting zero-sized value types from Swift
to C++. It needs some work on our end as these types are not part of the
lowered signature. In the meantime, this PR makes sure that common (but
not all) zero sized types are properly marked as unavailable. This is
important as the proper diagnostic will give users a hint how to work
around this problem. Moreover, it is really easy to hit this when
someone is experimenting with interop, so it is important to not have a
cryptic failure mode.

rdar://138122545
2024-10-28 14:00:35 +00:00
Joe Groff
a184782a38 Introduce a Builtin.FixedArray type.
`Builtin.FixedArray<let N: Int, T: ~Copyable & ~Escapable>` has the layout of `N` elements of type `T` laid out
sequentially in memory (with the tail padding of every element occupied by the array). This provides a primitive
on which the standard library `Vector` type can be built.
2024-10-22 16:21:45 -07:00