Commit Graph

1278 Commits

Author SHA1 Message Date
Doug Gregor
1b7707d2cc Remove the now-unused @safe(unchecked) 2025-01-10 10:39:16 -08:00
Doug Gregor
8bb5bbedbc Implement an unsafe expression to cover uses of unsafe constructs
Introduce an `unsafe` expression akin to `try` and `await` that notes
that there are unsafe constructs in the expression to the right-hand
side. Extend the effects checker to also check for unsafety along with
throwing and async operations. This will result in diagnostics like
the following:

    10 |   func sum() -> Int {
    11 |     withUnsafeBufferPointer { buffer in
    12 |       let value = buffer[0]
       |                   |     `- note: reference to unsafe subscript 'subscript(_:)'
       |                   |- warning: expression uses unsafe constructs but is not marked with 'unsafe'
       |                   `- note: reference to parameter 'buffer' involves unsafe type 'UnsafeBufferPointer<Int>'
    13 |       tryWithP(X())
    14 |       return fastAdd(buffer.baseAddress, buffer.count)

These will come with a Fix-It that inserts `unsafe` into the proper
place. There's also a warning that appears when `unsafe` doesn't cover
any unsafe code, making it easier to clean up extraneous `unsafe`.

This approach requires that `@unsafe` be present on any declaration
that involves unsafe constructs within its signature. Outside of the
signature, the `unsafe` expression is used to identify unsafe code.
2025-01-10 10:39:14 -08:00
Alejandro Alonso
b9487d132a Cache the value type of a generic param when cloning 2025-01-08 10:37:15 -08:00
Slava Pestov
2d17294d73 Merge pull request #78301 from slavapestov/remove-one-way-constraints
Sema: Remove ConstraintKind::OneWayBindParam and ConstraintKind::OneWayEqual
2025-01-05 10:38:14 -05: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
Michael Gottesman
5d4239af57 [concurrency] Add new isolation kind CallerIsolationInheriting.
Right now it is basically a version of nonisolated beyond a few simple cases
like constructors/destructors where we are pretty sure we want to not support
this.

This is part of my bringup strategy for changing nonisolated/unspecified to be
caller isolation inheriting.
2025-01-02 13:18:30 -08:00
Slava Pestov
74f8960bd8 Sema: Remove OneWayExpr and Builtin.one_way 2024-12-21 00:42:13 -08:00
Becca Royal-Gordon
08e2a4ddae Type check ABI decls
Sema now type-checks the alternate ABI-providing decls inside of @abi attributes.

Making this work—particularly, making redeclaration checking work—required making name lookup aware of ABI decls. Name lookup now evaluates both API-providing and ABI-providing declarations. In most cases, it will filter ABI-only decls out unless a specific flag is passed, in which case it will filter API-only decls out instead. Calls that simply retrieve a list of declarations, like `IterableDeclContext::getMembers()` and friends, typically only return API-providing decls; you have to access the ABI-providing ones through those.

As part of that work, I have also added some basic compiler interfaces for working with the API-providing and ABI-providing variants. `ABIRole` encodes whether a declaration provides only API, only ABI, or both, and `ABIRoleInfo` combines that with a pointer to the counterpart providing the other role (for a declaration that provides both, that’ll just be a pointer to `this`).

Decl checking of behavior specific to @abi will come in a future commit.

Note that this probably doesn’t properly exercise some of the new code (ASTScope::lookupEnclosingABIAttributeScope(), for instance); I expect that to happen only once we can rename types using an @abi attribute, since that will create distinguishable behavior differences when resolving TypeReprs in other @abi attributes.
2024-12-19 15:49:34 -08:00
Becca Royal-Gordon
94ff062edd Parse and serialize @abi attribute
This attribute will allow you to specify an alternate version of the declaration used for mangling. It will allow minor adjustments to be made to declarations so long as they’re still compatible at the calling convention level, such as refining isolation or sendability, renaming without breaking ABI, etc.

The attribute is behind the experimental feature flag `ABIAttribute`.
2024-12-19 15:48:54 -08:00
Becca Royal-Gordon
73377fe6b4 [NFC-ish] Fix some crashes from early Decl::dump()
Changes dump output used in one test; otherwise NFC.
2024-12-19 15:47:07 -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
e260d65f71 Add @safe(unchecked) to allow unsafe code within a declaration.
Introduce an attribute to allow unsafe code within the annotated
declaration without presenting an unsafe interface to users. This is,
by its nature, and unsafe construct, and is used to document where
unsafe behavior is encapsulated in safe constructs.

There is an optional message that can be used as part of an audit
trail.
2024-12-13 11:36:40 -08:00
Pavel Yaskevich
1a5f00b205 [AST] Add a new implicit conversion to model unsafe casts
`UnsafeCastExpr` - A special kind of conversion that performs an unsafe
bitcast from one type to the other.

Note that this is an unsafe operation and type-checker is allowed to
use this only in a limited number of cases like: `any Sendable` -> `Any`
conversions in some positions, covariant conversions of function and
function result types.
2024-12-11 11:40:28 -08:00
Anthony Latsis
18669a0fcc Merge pull request #78044 from AnthonyLatsis/nelumbo-nucifera
ASTDumper: Do not escape Unicode chars in quoted fields
2024-12-10 19:12:47 +00:00
Anthony Latsis
1001c46e4c ASTDumper: Do not escape Unicode chars in quoted fields
Context: https://github.com/swiftlang/swift/pull/68438#discussion_r1449272860
2024-12-10 12:51:19 +00:00
Joe Groff
8436db3b9d Merge pull request #78021 from jckarter/addressable-params-2
Add an `@_addressableSelf` attribute to mark the self param of methods as addressable.
2024-12-09 08:42:49 -08:00
Doug Gregor
ee9c066050 Introduce a new Initializer subclass for the arguments of custom attributes
Since the introduction of custom attributes (as part of property
wrappers), we've modeled the context of expressions within these
attributes as PatternBindingInitializers. These
PatternBindingInitializers would get wired in to the variable
declarations they apply to, establishing the appropriate declaration
context hierarchy. This worked because property wrappers only every
applied to---you guessed it!---properties, so the
PatternBindingInitializer would always get filled in.

When custom attributes were extended to apply to anything for the
purposes of macros, the use of PatternBindingInitializer became less
appropriate. Specifically, the binding declaration would never get
filled in (it's always NULL), so any place in the compiler that
accesses the binding might have to deal with it being NULL, which is a
new requirement. Few did, crashes ensued.

Rather than continue to play whack-a-mole with the abused
PatternBindingInitializer, introduce a new CustomAttributeInitializer
to model the context of custom attribute arguments. When the
attributes are assigned to a declaration that has a
PatternBindingInitializer, we reparent this new initializer to the
PatternBindingInitializer. This helps separate out the logic for
custom attributes vs. actual initializers.

Fixes https://github.com/swiftlang/swift/issues/76409 / rdar://136997841
2024-12-06 17:40:32 -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
Rintaro Ishizaki
6d7b3d69d1 [ASTGen] Generate several attributes
* NonisolatedAttr
* SpecializeAttr
* UnavailableFromAsyncAttr
* DocumentationAttr
* StorageRestrictionsAttr
2024-12-05 15:12:00 -08:00
Rintaro Ishizaki
5945a89c0a Merge pull request #77937 from rintaro/ast-dump-attrs
[AST] Dump decl attributes
2024-12-04 11:19:56 -08:00
Rintaro Ishizaki
507e81633e [ASTDumper] Dump decl attributes
Previously only some random decl attributes were included in the dump
with the source spelling (e.g. @objc), or some affected how the decl is
dumped. But the full attribute list has not been dumped. Dumping
attributes are useful for debugging attribute handling.
2024-12-03 21:27:24 -08:00
Hamish Knight
0fdb038fc9 Merge pull request #77896 from hamishknight/functionref-split
[AST] Split out "is compound" bit on FunctionRefKind
2024-12-03 09:53:37 +00:00
Pavel Yaskevich
8a0a083a45 Merge pull request #77797 from xedin/locatable-types
[AST/Sema]  Introduce a new type that has associated location in source
2024-12-02 16:33:43 -08:00
Hamish Knight
73fb36f371 [AST] Split out "is compound" bit on FunctionRefInfo
FunctionRefKind was originally designed to represent
the handling needed for argument labels on function
references, in which the unapplied and compound cases
are effectively the same. However it has since been
adopted in a bunch of other places where the
spelling of the function reference is entirely
orthogonal to the application level.

Split out the application level from the
"is compound" bit. Should be NFC. I've left some
FIXMEs for non-NFC changes that I'll address in a
follow-up.
2024-12-02 14:11:33 +00:00
Hamish Knight
a4d51419ba [AST] NFC: Rename FunctionRefKind -> FunctionRefInfo 2024-12-02 14:11:32 +00:00
Pavel Yaskevich
0fe4cea7d7 [AST] Introduce a new type that has associated location in source
This type is intended to be used to wrap compiler synthesized nodes
(i.e. variables) to make it easier for diagnostic to diagnose precise
failure locations.

Consider the situation like:

```
protocol P {}

extension Array: P where Element: P {}

func test<T: P>() -> T {
  $_a = ...
  $_b = ...
  return [$_a, $_b]
}
```

This is a common pattern with result builders.

In this case if one of the elements don't conform to `P` the best
user experience would be to attach diagnostic to the element otherwise
the developers would have to figure out where in result expression
the error occured before attempting to fix it.
2024-11-21 11:01:13 -08:00
Pavel Yaskevich
7151a9751a [ASTDumper] Don't try to print opaque type decl substitutions
Attempting to dump opaque decl while type-checking a body of
the declaration it's associated with results in a request
cycle because underlying substitutions request would trigger
type-checking if the body isn't type-checked yet.
2024-11-21 09:37:59 -08:00
Hamish Knight
2d7500eda6 [AST] Remove ParenType
Today ParenType is used:

1. As the type of ParenExpr
2. As the payload type of an unlabeled single
   associated value enum case (and the type of
   ParenPattern).
3. As the type for an `(X)` TypeRepr

For 1, this leads to some odd behavior, e.g the
type of `(5.0 * 5).squareRoot()` is `(Double)`. For
2, we should be checking the arity of the enum case
constructor parameters and the presence of
ParenPattern respectively. Eventually we ought to
consider replacing Paren/TuplePattern with a
PatternList node, similar to ArgumentList.

3 is one case where it could be argued that there's
some utility in preserving the sugar of the type
that the user wrote. However it's really not clear
to me that this is particularly desirable since a
bunch of diagnostic logic is already stripping
ParenTypes. In cases where we care about how the
type was written in source, we really ought to be
consulting the TypeRepr.
2024-10-31 11:32:40 +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
Hamish Knight
6a435960b7 Requestify regex pattern parsing
Instead of doing the pattern parsing in both the
C++ parser and ASTGen, factor out the parsing into
a request that returns the pattern to emit, regex
type, and version. This can then be lazily run
during type-checking.
2024-10-11 19:25:58 +01:00
Meghana Gupta
31c1dc7eb5 Add support for specifying target in @lifetime
@lifetime(target: source1, source2...) where target can be any
parameter or 'self'. We cannot have @lifetime attributes with duplicate targets.

Also, update the internal data structures. Previously LifetimeEntry stored
pairwise (target, source) dependencies. Now, LifetimeEntry will store an optional
target descriptor and an array of source descriptors.
2024-10-08 15:10:48 -07:00
Nate Chandler
091368ba21 [CoroutineAccessors] Added read.
The name is a placeholder for the mutating single-yield coroutine
accessor.
2024-09-26 18:10:39 -07:00
Nate Chandler
98a2e6a7df [CoroutineAccessors] Added modify.
The name is a placeholder for the mutating single-yield coroutine
accessor.
2024-09-26 18:10:39 -07:00
Doug Gregor
5b2520e379 Remove IfConfigDecl from the AST
The swift-syntax tree retains information about the parsed #if
regions. Drop it from the semantic AST.
2024-09-18 20:51:54 -07:00
Meghana Gupta
2b011b0a3a [NFC] Rename/reorg LifetimeDependence utils 2024-09-09 22:02:44 -07:00
Alejandro Alonso
e0f2b812e8 Add serialization and parser tests for SIL 2024-09-04 15:13:47 -07:00
Slava Pestov
1ff1b9479a AST: Pick off some usages of GenericTypeParamType::getDecl() 2024-09-04 15:13:46 -07:00
Alejandro Alonso
f4f60f4344 Remove Value requirement Add GenericTypeParamKind 2024-09-04 15:13:43 -07:00
Alejandro Alonso
0df42e9841 Lower UDRE to TypeValue if it references a value generic 2024-09-04 15:13:29 -07:00
Alejandro Alonso
75c2cbf593 Implement value generics
Some requirement machine work

Rename requirement to Value

Rename more things to Value

Fix integer checking for requirement

some docs and parser changes

Minor fixes
2024-09-04 15:13:25 -07:00
Slava Pestov
1778a9f595 AST: Print opened existential substitutions in ASTPrinter/ASTDumper 2024-09-04 10:42:18 -04:00
Greg Titus
d87e049cde Improve diagnoses of generic specializations
Always add constraints, find fixes during simplify.
New separate fix for allow generic function specialization.
Improve parse heuristic for isGenericTypeDisambiguatingToken.
Degrade concrete type specialization fix to warning for macros.
2024-07-30 18:51:34 -07:00
Michael Gottesman
b20251eaec [gardening] Print out nonisolated(unsafe) on var decls when printing VarDecl.
Just noticed this was missing when doing some other work.
2024-07-13 14:44:14 -07:00
Andrew Trick
12acde2215 Merge pull request #75096 from meg-gupta/lifetimedeparg
Add support for lifetime dependence in parameter position
2024-07-10 22:56:23 -07:00
Meghana Gupta
2b28da6dd7 Update ASTPrinting of lifetime dependence 2024-07-10 14:48:34 -07:00
Meghana Gupta
8137aed238 Rename LifetimeDependentReturnTypeRepr -> LifetimeDependentTypeRepr 2024-07-10 14:20:03 -07:00
Slava Pestov
26fffae30a AST: Simplify SubstitutionMap representation
There was a bunch of logic to lazily populate replacement types
corresponding to reducible generic parameters. This didn't seem
to have a clear purpose so let's remove it.
2024-07-10 13:28:26 -04:00
Michael Gottesman
112071e57d [sending] Remove transferring.
Out of an abundance of caution, we:

1. Left in parsing support for transferring but internally made it rely on the
internals of sending.

2. Added a warning to tell people that transferring was going to
be removed very soon.

Now that we have given people some time, remove support for parsing
transferring.

rdar://130253724
2024-06-21 16:03:21 -07:00
Tim Kientzle
598e5104ef Merge pull request #74184 from tbkka/tbkka-assertions2
Add `#include "swift/Basic/Assertions.h"` to a lot of source files
2024-06-20 12:13:28 -07:00
Hamish Knight
82cc2403d9 [ASTDumper] Respect function body skipping
Avoid parsing a body for e.g
`-experimental-skip-all-function-bodies`.
2024-06-19 15:22:20 +01:00