Commit Graph

1076 Commits

Author SHA1 Message Date
Paul Passeron 425cd0ebd7 [experimental] Infrastructure for derived conformances via macros (#89419)
**Overview**:
This PR introduces the basic infrastructure needed to eventually migrate
derived macros generation from hand-crafted AST nodes to macros. No
conformance have been migrated yet.

**Motivation**:
Derived conformances (e.g. `Equatable`, `Hashable`, `Codable`, ...) are
currently implemented as a special case in the compiler, producing
synthetic AST nodes directly. Migrating this to macros will hopefully
unify the code path with the existing macro expansion infrastructure,
make conformance synthesis easier to extend and test as well as reducing
the amount of special cases in the compiler.

**Changes**:
- New experimental feature flag `DeriveConformancesViaMacros`:
Introduces the flag that will eventually gate the new derived
conformance code paths. It does not control any behaviour for the moment
as none have been migrated yet but this enables future changes to be
built incrementally.
- New GeneratedSourceInfo and SourceFile kinds `SyntheticMacro`:
Introduces new GSI and SourceFile kinds named `SyntheticMacro` to
represent macros synthesized by the compiler. Since macros need a real
buffer to expand, this is the kind of source file and GSI associated
with those buffers.
- Conformance derivation via macros API:
Introduces the `deriveRequirementViaMacro` function that produces the
required witness via macro expansion.

See https://github.com/swiftlang/llvm-project/pull/13124 for
llvm-related changes.

**Next steps**:
- Macros do not contain any semantic information, especially regarding
types. Therefore it is necessary to provide them with type information
as an argument so they can eventually derive the conformances. A
separate PR is being created to generate this type information as
strings containing swift-parsable code for easy parsing on the macro
end.
- Implement derived conformance synthesis for individual protocols using
the new infrastructure, like `Equatable` or `Hashable` for starters.
- Wire the experimental flag to gate the new path once an implementation
exists

---------

Co-authored-by: Hamish Knight <hamish_knight@apple.com>
2026-06-08 14:23:58 +01:00
Sam Pyankov 73852c2195 Merge pull request #89190 from sepy97/ipi-clang-modules
Sema: Enforce IPI library level for Clang modules
2026-05-27 17:50:33 -07:00
Sam Pyankov e292be9a1b Sema: Enforce IPI library level for Clang modules
Add -ipi-clang-module flag to enforce IPI library level for Clang modules.
Compiler stores names of those modules and checks them during typechecking.

rdar://177196788
2026-05-27 10:04:15 -07:00
Xi Ge 00897a0efb [Serialization] Add precomputed layout table for hidden types
Add the module-format machinery that lets a Swift library record the
physical layout of hidden types (currently limited to C types imported via internal bridging header).
into binary modules, so downstream consumers can pull the layouts of these hidden types without
loading the internal dependency.

To test this, this change also added a frontend action to print hidden types' layouts
from both the module under compilation and all the modules being imported.
2026-05-15 10:07:19 -07:00
Allan Shortlidge d4ffb7802c AST: Avoid including unnecessary headers in ASTContext.h.
Anything that can be forward declared in ASTContext.h should be because it is
included by nearly every implementation file in the compiler. Avoiding these
includes allows these various options types to be changed without a full
rebuild.

NFC.
2026-05-06 06:43:45 -07:00
Doug Gregor 8713c13bef Centralize computation of the "code generation model" for object code & SIL
For a given function, we might end up emitting it's definition as
object code, serialized SIL, or both. The @export, @inlinable, and
@inline(always) attributes provide control of this behavior at the
declaration level.

Centralize the query function that will look for each of these
attributes and map down to a specific "code generation model", whose 3
options follow the naming from SE-0497: interface, inlinable, and
implementation. Use this one computation to back the queries for
"always emit into client", "never emit into client", and "inlinable"
so we can't get inconsistent results from places that are doing
one-off checks for these attributes.
2026-04-15 13:03:55 -07:00
Sam Pyankov a09cf04718 Serialize library level into .swiftmodule binary format
Add a LIBRARY_LEVEL record to the .swiftmodule options block so the
declared -library-level value survives across compilations. Without
this, imported modules have to always fell back to a path heuristic
that could only distinguish API vs SPI and never returned IPI.

rdar://174255626
2026-04-08 12:17:32 -07:00
Arnold Schwaighofer 72bd56de5b [cmo] [aggresive] Don't attach the usableFromInline attribute
in the CMO pass in aggressive mode

Changing the AST mid-pipeline is probably not a good idea.

rdar://173172456
2026-03-23 14:11:02 -07:00
Steven Wu 34d52cfe1a [DependencyScan] Propagate module library level through dependency scanner for CAS builds
Compute and propagate the library level (api/spi/ipi) of each module
dependency through the dependency scanner so that the compiler can
correctly enforce private module import diagnostics in CAS mode, where
path-based SPI detection fails because CAS abstracts file paths to
content IDs.

Swift modules:
- Detect library level from the module interface path using
  libraryLevelFromPath() during scanning, for both textual (.swiftinterface)
  and binary (.swiftmodule) Swift modules.

Clang modules:
- Expose ModuleMapIsPrivate from clang::Module in ModuleDeps via the
  dependency scanning infrastructure.
- Set library level for clang modules in bridgeClangModuleDependency()
  using ModuleMapIsPrivate (catches module.private.modulemap in any
  SDK location) and libraryLevelFromPath() on the module map file
  (catches modules under PrivateFrameworks directories).

The library level is:
- Stored in ModuleDependencyInfo and serialized in the module dependency
  cache (format version bumped to v8).
- Exposed through the swiftscan C API via a new
  swiftscan_module_info_get_library_level() function (API minor version
  bumped to 3).
- Emitted in the dependency scanner JSON output as "libraryLevel" for
  all module kinds (Swift textual, Swift binary, Clang, and main module).
- Parsed from the explicit module map JSON by ExplicitModuleMapParser
  for both Swift (ExplicitSwiftModuleInputInfo) and Clang
  (ExplicitClangModuleInputInfo) modules.
- Looked up in ModuleLibraryLevelRequest via
  ASTContext::getExplicitModuleLibraryLevel(name, isClang), which
  consults the appropriate map (Swift or Clang) based on module kind.

rdar://172693314

Assisted-By: Claude
2026-03-17 11:04:18 -07:00
Henrik G. Olsson ba7b9b0d6b Revert "Sema: Prefer the submodule import for access-levels diagnostics"
This reverts commit ca8792ca37.

Revert "[ImportResolution] Gracefully handle importing broken clang module"

This reverts commit edb48dff8c.

Revert "[ImportResolution] Don't deduplicate scoped imports"

This reverts commit da96079eb0.

Revert "[ImportResolution] Deduplicate top-level clang modules from import list"

This reverts commit 0ea5677aa1.

Reverting due to namelookup errors.

rdar://164588082
2025-11-19 23:10:14 -08:00
Alexis Laferrière 5a49e34426 Serialization: Error on xref to implementation-only dependencies
Introduce a last resort check reporting references to
implementation-only dependencies that would appear in the generated
swiftmodule. This check is applied at serialization, long after
exportability checking applied at typechecking. It should act as a back
stop to references missed by typechecking or @_implementationOnly decls
that should have been skipped.

This check is gated behind CheckImplementationOnlyStrict and should be
used with embedded only.

rdar://160697599
2025-11-11 13:03:16 -08:00
Slava Pestov d4869193c8 IRGen: Only skip round-trip demangler check for types that involve C++ types
Previously this was disabled entirely if C++ interop was
enabled, which is too broad.
2025-11-03 13:59:06 -05:00
Becca Royal-Gordon ec92be4955 Support module selectors for cross-import overlays 2025-10-24 16:23:50 -07:00
Becca Royal-Gordon ffaa35810c Handle lookup into Builtin with module selector
Lookups like Builtin::Int64 were failing because BuiltinUnit rejected all unqualified lookups. Make it allow unqualified lookups with a module selector.
2025-10-24 16:23:48 -07:00
Alexis Laferrière ca8792ca37 Sema: Prefer the submodule import for access-levels diagnostics
Update logic finding the import to point in diagnostics to avoid relying
on the implicit import of the top-level module when importing a clang
submodule. A recent change avoids duplicating the implicit imports and
broke the old logic.

rdar://162151660
2025-10-14 16:25:49 -07:00
Becca Royal-Gordon 60b3b088d5 Merge pull request #84358 from beccadax/common-concurrency 2025-10-07 12:21:50 -07:00
Becca Royal-Gordon 3abbfaa9cb Introduce separately-imported stdlib overlays
The `_Concurrency` and `_StringProcessing` modules are implementation details of the standard library; to developers, their contents should behave as though they are declared directly within module `Swift`. This is the exact same behavior we expect of cross-import overlays, so treat these modules as though they are cross-import overlays with no bystanding module.

Because these modules don’t re-export the standard library, it’s also necessary to treat `Swift` as a separately imported overlay of itself; do so and make that actually work.
2025-10-02 12:05:12 -07:00
Doug Gregor 90a5a0f87d Merge pull request #84410 from DougGregor/internal-import-bridging-header 2025-09-22 23:09:07 -07:00
Henrik G. Olsson 7fcc72f108 Merge pull request #81859 from swiftlang/swiftify-inherit-imports
[MacrosOnImports][Swiftify] Copy module imports from clang node's module to its Swift macro SourceFile
2025-09-19 21:21:09 -07:00
Doug Gregor b13c2aeccd Treat internally-imported bridging headers as internally-imported
When using an internal import for a bridging header, semantically treat
the contents of the bridging header, and anything that it imports, as
if they were imported internally. This is the actual semantic behavior
we wanted from internally-imported bridging headers.

This is the main semantic checking bit for rdar://74011750.
2025-09-19 16:49:17 -07:00
Henrik G. Olsson 17c0e564e8 Add hidden --dump-source-file-imports flag
This flag dumps all imports for each SourceFile after it's gone through
import resolution. It is only intended for testing purposes.
There are other ways to print imports, but they don't correspond 1:1 to
the imports actually resolved, which is a bit problematic when testing
implicit clang module imports.
2025-09-16 21:09:59 -07:00
Allan Shortlidge 4841bcffa1 ModuleInterface: Print imports with @preconcurrency in swiftinterface files.
When a module has been imported `@preconcurrency` in source, when it is printed
in a `swiftinterface` file it should be printed along with the attribute to
ensure that type checking of the module's public declarations behaves
consistently.

This fix is a little unsatisfying because it adds another a linear scan over
all imports in the source for each printed import. This should be improved, but
it can be done later.

Resolves rdar://136857313.
2025-09-15 17:33:13 -07:00
Hamish Knight 5c334c5f21 Requestify the loading of access notes
Replace `loadAccessNotesIfNeeded` with a request that loads the access
notes on-demand.
2025-09-11 16:54:08 +01:00
Allan Shortlidge b047396246 AST: Use availability to control decl visibility in public swiftinterfaces.
Declarations that are unavailable at runtime because of an `@available`
attribute referencing a custom domain that was imported `@_spiOnly` should be
hidden from public swiftinterface files in `-library-level=api` modules. For
remaining declarations that do get printed in the public swiftinterface, skip
printing any `@available` attribute that refers to the domains from those
`@_spiOnly` dependencies. This allows API developers to control declaration
visibility using availability defined by another module.

Resolves rdar://156512028.
2025-09-04 12:32:19 -07:00
Doug Gregor ed93b46fa6 [Embedded] Introduce DeferredCodeGen feature.
Introduce an experimental feature DeferredCodeGen, that defers the
generation of LLVM IR (and therefore object code) for all entities
within an Embedded Swift module unless they have explicitly requested
to not be emitted into the client (e.g., with
`@_neverEmitIntoClient`).

This feature is meant to generalize and subsume
-emit-empty-object-file, relying on lazy emission of entities rather
than abruptly ending the compilation pipeline before emitting any IR.

Part of rdar://158363967.
2025-09-03 15:55:47 -07:00
Anthony Latsis fec049e5e4 Address llvm::PointerUnion::{is,get} deprecations
These were deprecated in
https://github.com/llvm/llvm-project/pull/122623.
2025-07-29 18:37:48 +01:00
John Hui a0d3ad7bd0 Merge pull request #82006 from j-hui/jump-to-def-for-macro-expanded-clang-imports
[SourceKit] Support location info for macro-expanded Clang imports
2025-06-19 02:01:40 -07:00
John Hui 44aba1382d [SourceKit] Support location info for macro-expanded Clang imports
Currently, when we jump-to-definition for decls that are macro-expanded
from Clang imported decls (e.g., safe overloads generated by
@_SwiftifyImport), setLocationInfo() emits a bongus location pointing to
a generated buffer, leading the IDE to try to jump to a file that does
not exist.

The root cause here is that setLocationInfo() calls getOriginalRange()
(earlier, getOriginalLocation()), which was not written to account for
such cases where a macro is generated from another generated buffer
whose kind is 'AttributeFromClang'.

This patch fixes setLocationInfo() with some refactoring:

-   getOriginalRange() is inlined into setLocationInfo(), so that the
    generated buffer-handling logic is localized to that function. This
    includes how it handles buffers generated for ReplacedFunctionBody.

-   getOriginalLocation() is used in a couple of other places that only
    care about macros expanded from the same buffer (so other generated
    buffers not not relevant). This "macro-chasing" logic is simplified
    and moved from ModuleDecl::getOriginalRange() to a free-standing
    function, getMacroUnexpandedRange() (there is no reason for it to be
    a method of ModuleDecl).

-   GeneratedSourceInfo now carries an extra ClangNode field, which is
    populated by getClangSwiftAttrSourceFile() when constructing
    a generated buffer for an 'AttributeFromClang'. This could probably
    be union'ed with one or more of the other fields in the future.

rdar://151020332
2025-06-12 18:22:06 -07:00
Meghana Gupta 0dfa1fc312 Update spelling for representing lifetime dependencies to @_lifetime 2025-06-07 12:49:07 -07:00
Pavel Yaskevich 36b77116bd [Concurrency] Add a request to retrieve default isolation of a file
The default isolation is computed based on `using` declaration
found in the file, if any.
2025-05-31 10:49:50 -07:00
Hamish Knight c287f53580 Merge pull request #81809 from hamishknight/range-expansion
[SourceKit] Properly handle cursor info range for macro expansions
2025-05-29 20:23:54 +01:00
Hamish Knight f6c73cd178 [SourceKit] Properly handle cursor info range for macro expansions
Make `getOriginalLocation` work with source ranges, and adjust the
cursor info logic to map the range into the original buffer. This
fixes the case where we were using bogus range lengths for macro
expansion decls.

rdar://151411756
2025-05-28 18:51:40 +01:00
Arnold Schwaighofer 13ff5abdb8 Introduce @specialized attribute
Implements SE-0460 -- the non-underscored version of @specialized.

It allows to specify "internal" (not abi affecting) specializations.

rdar://150033316
2025-05-23 13:12:47 -07:00
Michael Gottesman 9d59dbed17 [swift-settings] Now that we aren't using it immediately, remove it from tree.
We can always get it back from the git history.

rdar://150695113
2025-05-05 13:39:03 -07:00
Becca Royal-Gordon 9be9b6fad6 Inherit access control in @abi
ABI-only declarations now inherit access control modifiers like `public` or `private(set)`, as well as `@usableFromInline` and `@_spi`, from their API counterpart. This means these attributes and modifiers don’t need to be specified in an `@abi` attribute.

Very few tests because we aren’t yet enforcing the absence of these attributes.
2025-03-26 10:47:13 -07:00
Steven Wu df86e089c8 Merge pull request #80172 from cachemeifyoucan/eng/PR-147513165
Fix `.swiftdeps` file deterministic issues
2025-03-24 15:15:17 -07:00
Steven Wu b8879eef88 [AST] Get it a deterministic traverse order for classMembers
Make sure the traversal order for classMembers in deterministic in the
mdoule by sorting them first.

Also fix the comparsion function for `DeclName` to make sure there
aren't two DeclNames with different OpaquePointer can be evaluated to
equal.

rdar://147513165
2025-03-21 13:11:14 -07:00
Hamish Knight 2d7dbd3965 Remove IDEInspectionFileRequest
We now maintain a mapping of buffer IDs to SourceFiles on the
SourceManager we can use.
2025-03-20 12:53:34 +00:00
Michael Gottesman 0b2c160740 Merge pull request #80070 from gottesmm/swift-settings-only-once
[swift-settings] Only allow for a setting to be passed exactly once to #SwiftSettings.
2025-03-17 19:12:00 -07:00
Konrad `ktoso` Malawski 85fcd69833 [Concurrency] Implement detecting isIsolatingCurrentContext user impls (#79946)
* [Concurrency] Detect non-default impls of isIsolatingCurrentContext

* [Concurrency] No need for trailing info about isIsolating... in conformance

* Apply changes from review
2025-03-18 09:39:11 +09:00
Michael Gottesman 4b31382d67 [swift-settings] Only allow for a setting to be passed exactly once to #SwiftSettings.
This responds to some feedback on the forums. Most importantly this allows for
us to use variadic generics in the the type system to document whether we allow
for "appending" behavior or not. Previously, for some options we would take the
last behavior (and theoretically) for others would have silently had appending
behavior. This just makes the behavior simple and more explicit.
2025-03-17 14:03:52 -07:00
Michael Gottesman cd38b78466 [swift-settings] Provide a default nullptr for a variable.
Just noticed it as I was reading some code. Even though it cannot happen today,
with code being added, we could allow for undefined behavior. Better to program
defensively than aggressively.
2025-03-17 13:17:20 -07:00
Rintaro Ishizaki f3191c8068 [AST] Ignore UnvalidatedDeclsWithOpaqueReturnTypes in skipped functions 2025-03-16 17:41:21 -07:00
Allan Shortlidge 151c9dee39 AST: Consolidate abstract/contrete syntax decl lookup functions. 2025-03-15 23:47:29 -07:00
Allan Shortlidge 017dae382e ClangImporter: Look up availability domains defined in bridging headers.
This is very brittle in this first iteration. For now we require the
declaration representing the availability domain be deserialized before it can
be looked up by name since Clang does not have a lookup table for availabilty
domains in its module representation. As a result, it only works for bridging
headers that are not precompiled.

Part of rdar://138441266.
2025-03-15 07:44:37 -07:00
Tony Allevato 0844e274b0 Ensure that #fileID wraps raw identifier module names in backticks.
`#fileID` never accounted for the possibility that someone one have
a module alias _itself_, so it always generated the module's real
(physical) name. This _technically_ changes the behavior of `#fileID`
for self-aliased modules, but since nobody would have ever had a reason
to do that before raw identifiers, it's unlikely that this change would
affect anyone in practice.
2025-03-11 17:18:44 -04:00
Michael Gottesman f64dd5a8d5 [concurrency] Add initial support for SwiftSettings to control defaultIsolation at the file level.
We introduce a new macro called #SwiftSettings that can be used in conjunction
with a new stdlib type called SwiftSetting to control the default isolation at
the file level. It overrides the current default isolation whether it is the
current nonisolated state or main actor (when -enable-experimental-feature
UnspecifiedMeansMainActorIsolated is set).
2025-03-10 17:33:45 -07:00
John Hui bdf22948ce [cxx-interop] Allow Swift to access non-public C++ members (#79093)
This patch introduces an a C++ class annotation, SWIFT_PRIVATE_FILEID,
which will specify where Swift extensions of that class will be allowed
to access its non-public members, e.g.:

    class SWIFT_PRIVATE_FILEID("MyModule/MyFile.swift") Foo { ... };

The goal of this feature is to help C++ developers incrementally migrate
the implementation of their C++ classes to Swift, without breaking
encapsulation and indiscriminately exposing those classes' private and
protected fields.

As an implementation detail of this feature, this patch introduces an
abstraction for file ID strings, FileIDStr, which represent a parsed pair
of module name/file name.

rdar://137764620
2025-02-18 11:22:44 -08:00
Allan Shortlidge 770ddad742 AST/Sema: Look up custom availability domains by name.
Store the domain definitions defined on the command line on the `ModuleDecl` for
the main module.
2025-01-31 17:31:13 -08:00
Alexis Laferrière 63c2979e13 Merge pull request #78471 from xymus/fix-accessor-is-spi
Sema: Accessors's SPI are tied to the attributes on the storage
2025-01-31 08:59:43 -08:00