Commit Graph

179 Commits

Author SHA1 Message Date
Nate Cook
85208293c9 Allow inout parameters in expression macros (#82370)
Sema seems to be flagging inout expressions (e.g. &foo) in expression
macros as invalid, setting up a catch 22 where Sema emits an error when
a parameter has the '&' sigil and type checking fails when it doesn't.

This resolves the issue by allowing inout expressions inside macro
expansion expressions.

Resolves https://github.com/swiftlang/swift/issues/82369.
2025-07-03 23:52:16 -07:00
Henrik G. Olsson
efd70b1f54 Prevent silgen for macro expansions with type errors (#81396)
Due to a bug in how macros on nodes imported from clang are evaluated,
their function body is not always type checked. This forces type
checking before silgen of a macro originating on a node imported from
clang, to prevent crashing in silgen.

rdar://150940383
2025-05-09 10:27:27 -07:00
Doug Gregor
2e34549236 [SE-0470] Prohibit inference of isolated conformances with nonisolated witnesses
If all of the witnesses to a conformance are nonisolated, then infer that
conformance as nonisolated rather than global-actor-isolated. This is
only relevant when InferIsolatedConformances is enabled, and prevents
that inference to help maintain source compatibility.
2025-05-05 11:08:52 -07:00
Hamish Knight
b8ab2c048b [ASTScope] Match parent scopes in lookupCatchNode for brace stmts
Rather than looking for a given BraceStmtScope child for a particular
catch node, check whether the given catch node is the parent of the
innermost BraceStmtScope we've found, looking through an intermediate
source file if needed. This ensures it works correctly when the
BraceStmtScope is in a macro expansion.

rdar://149036108
2025-04-19 21:11:22 +01:00
Hamish Knight
4676eaa110 [Sema] Requestify PatternBindingDecl capture computation
Introduce `PatternBindingCaptureInfoRequest`, and kick it after
contextualizing a property initializer. This ensures it gets run
for stored properties added by macro expansions.

rdar://143429551
2025-04-04 16:01:39 +01:00
Hamish Knight
aaeb38d7f4 [Macros] Expand extension macros at the top-level
Ensure we always expand extension macros after the top-level decl
for the given attached decl. This ensures correct unqualified lookup
behavior, and bans macro implementations from extending the
unqualified name (they're expected to use `providingExtensionsOf`
instead, which uses the qualified name).

rdar://148119538
2025-03-28 21:35:59 +00:00
Doug Gregor
d276006648 [Macros] Eliminate ordering dependency that suppressed conformingTo protocols
When a macro that has both 'member' and 'extension' roles is on a type,
and both list conforming protocols, the order in which those roles were
evaluated in the compiler could change the set of protocols passed to
the macro expansion function (via `conformingTo:`). Specifically, if
the extension macro was expanded first, the member macro would see the
extension providing the conformance to one of its protocols, and not
pass down that protocol to the member macro's `conformingTo:`.

Ensure that we account for already-expanded extension macros that
define conformances.

Fixes rdar://137080876.
2025-02-06 11:07:20 -08:00
Rintaro Ishizaki
f3329b3b5d [ASTGen/MacroEvaluation] Fix and adjust FixIt application
* Fix mismatch on 'FixIt.Change.replace' between several application
  implementations. Specifically '.replace' should includes the trivia.
* Ignore no-op 'FixIt.Change.replace{Leading|Trailing}Triviia'.
2025-01-16 10:04:08 -08:00
Doug Gregor
65a9bff5b0 Rework mangling of macro expansions in local contexts to not trigger type checking.
The mangling of macro expansions relies on having a type-checked AST
for its enclosing context. When that enclosing context is within a
local context (say, a local type), mangling would trigger type
checking of that local type, which could then involve assigning local
discriminators. However, if this happens before type checking of the
enclosing function body, we would end up failing to assign closure
discriminators to (e.g.) autoclosures within the body.

The fundamental problem here is the interaction between discriminator
assignment (which can only happen after type checking) and mangling of
macro expansion buffers (which can happen during that type checking).
Break this cycle by providing a different approach to mangling macro
expansions within local contexts as the innermost non-local context +
a name-based discriminator within that local context. These manglings
are not ABI and are not stable, so we can adjust them later if we come
up with a scheme we like better. However, by breaking this cycle, we
eliminate assertions and miscompiles that come from missing
discriminators in this case.

Fixes rdar://139734958.
2024-12-05 16:09:02 -08:00
Doug Gregor
11ed132614 [Clang importer + macros] Handle name lookup and type checking for expanded macros
Introduce a number of fixes to allow us to fully use declarations that
are produced by applying a peer macro to an imported declarations.
These changes include:
* Ensuring that we have the right set of imports in the source file
containing the macro expansion, because it depends only on the module
it comes from
* Ensuring that name lookup looks in that file even when the
DeclContext hierarchy doesn't contain the source file (because it's
based on the Clang module structure)

Expand testing to be sure that we're getting the right calls,
diagnostics, and generated IR symbols.
2024-11-13 21:21:56 -08:00
Doug Gregor
f64189043a Merge pull request #77517 from DougGregor/rtc-macro-expansion
Teach the TypeRefinementContext not to skip declarations within macro expansions
2024-11-10 16:43:15 -08:00
Doug Gregor
de4d4a4244 Teach the TypeRefinementContext not to skip declarations within macro expansions
The construction of type refinement contexts performs lazy expansion
for the contents of macro expansions, so that TRC creation doesn't
force all macros to be expanded. However, the logic that skips macro
expansions would *also* skip some declarations produced within a macro
expansion, even when building the TRC specifically for that macro
expansion buffer. This manifest as missing some availability
information within the TRC, rejecting some well-formed code.

Tune the logic for "don't visit macro expansions when building a TRC"
to recognize when we're building a TRC for that macro expansion.

Fixes rdar://128400301.
2024-11-10 07:32:00 -08:00
Alex Hoppen
fb0b3fa90c Merge pull request #77149 from Azoy/swift-syntax-integer-types
[ASTGen/Parse] Implement ASTGen changes for integer generics from Swift Syntax and restrict parsing integer types in certain contexts
2024-11-07 14:04:26 -08:00
Alejandro Alonso
63eca896b7 Update syntax_macro_definitions.swift 2024-11-06 13:55:01 -08:00
Doug Gregor
7b3dce195a [C++ parser] Make sure break out of a parser loop on ill-formed macro expansion of members
The condition to make sure that the parser makes progress when there is
an ill-formed macro expansion to members was incorrect, causing an
infinite loop if there was at least one well-formed declaration
followed by ill-formed code (in this case, a `}`). Fix the condition.

Fixes rdar://137828917.
2024-11-06 10:15:26 -08:00
Doug Gregor
cdcabd05bd Allow attached macros to be applied to imported C declarations
The Clang importer maps arbitrary attributes spelled with `swift_attr("...")`
over to Swift attributes, using the Swift parser to process those attributes.
Extend this mechanism to allow `swift_attr` to refer to an attached macro,
expanding that macro as needed.

When a macro is applied to an imported declaration, that declaration is
pretty-printed (from the C++ AST) to provide to the macro implementation.
There are a few games we need to place to resolve the macro, and a few more
to lazily perform pretty-printing and adjust source locations to get the
right information to the macro, but this demonstrates that we could
take this path.

As an example, we use this mechanism to add an `async` version of a C
function that delivers its result via completion handler, using the
`@AddAsync` example macro implementation from the swift-syntax
repository.
2024-10-08 11:12:50 -07:00
Doug Gregor
7e4acfaa02 [Macros] Put the insertion location for freestanding macros at the beginning
When building the ASTScope tree, we set the insertion location for the
macro expansion just before the end of the macro use. This is the right
approach for attached macros, because we need to put the entities
after the macro.

However, for freestanding macros, which can have trailing closures,
this location is a problem, because the scope for the macro
expansion ends up inside the scope for the trailing closure. Use the
start location of the freestanding macro instead.

Fixes rdar://130923190.
2024-07-02 20:47:40 -07:00
Hamish Knight
6c930f7aaa [Coverage] Also walk MacroExpansionDecls
Make sure we walk macro expansion decls to handle
cases where e.g a binding introduces control flow.
This should be a pretty uncommon case since bindings
introduced by macros aren't actually usable when
expanded in local contexts, but handle it all the
same.
2024-06-03 12:14:56 +01:00
Hamish Knight
95cbced7a0 [Coverage] Avoid profiling functions with body macros
These replace the body of the function, and as such
shouldn't be profiled.
2024-06-03 12:14:56 +01:00
Hamish Knight
98f0200f64 [Coverage] Avoid recording regions from macro expansions
Ignore any regions recorded while inside a macro
expansion, but account for any control flow that
may have happened such that the exit count is
correctly adjusted. This allows e.g throwing function
calls to behave correctly within the expansion.

rdar://129081384
2024-06-03 12:14:56 +01:00
Holly Borla
3c6918a2c4 [Macros] Don't allow macros to add accessors to let variables. 2024-05-23 22:22:07 -07:00
cui fliter
127077b3aa chore: fix some comments
Signed-off-by: cui fliter <imcusg@gmail.com>
2024-03-05 17:23:22 +08:00
Konrad `ktoso` Malawski
f03ddf728b [Macros] Reproduce issue with peer+extension macro extension's methods not being checked as witnesses (#71717)
Co-authored-by: Pavel Yaskevich <pyaskevich@apple.com>
2024-02-20 00:50:29 -08:00
Apollo Zhu
f003c49fdf [WIP] Disallow macro default argument with argument
Need to use variable from caller side context
2024-02-06 15:02:12 -08:00
Apollo Zhu
249a369bd0 Arguments are weird 2024-02-06 15:02:12 -08:00
Apollo Zhu
b09a22a9a0 Somewhat working
Test shadowed variable of same type

Fully type check caller side macro expansion

Skip macro default arg caller side expr at decl primary

Test macro expand more complex expressions

Set synthesized expression as implicit

Add test case for with argument, not compiling currently

Test with swiftinterface

Always use the string representation of the default argument

Now works across module boundary

Check works for multiple files

Make default argument expression work in single file

Use expected-error

Disallow expression macro as default argument

Using as a sub expression in default argument still allowed as expression macros behave the same as built-in magic literals
2024-02-06 15:02:11 -08:00
Konrad `ktoso` Malawski
5acd366c98 [macros] allow forwarding generic arguments through macro declarations (#71271)
* [macros] allow forwarding generic arguments through macro declarations

[macros] add more tests for generic argument forwarding in macro declarations

* [macros] correct replacement picking logic
2024-02-06 03:56:20 -08:00
Holly Borla
1707e76ba8 [Macros] Expand nested macros in qualified name lookup. (#71407) 2024-02-06 15:45:24 +09:00
Doug Gregor
e7be8f32f1 Provide the lexical context to macro expansions 2024-02-02 16:03:29 -08:00
Doug Gregor
292df02e8c Ensure that member macros can introduce subscripts and deinits
The only fix needed here was to the new Swift parser, but add some
tests to ensure everything else works. rdar://121687968
2024-01-30 10:40:57 -08:00
Erik Eckstein
c89df9ec98 Mandatory optimizations: constant fold boolean literals before the DefiniteInitialization pass
Add a new mandatory BooleanLiteralFolding pass which constant folds conditional branches with boolean literals as operands.

```
  %1 = integer_literal -1
  %2 = apply %bool_init(%1)   // Bool.init(_builtinBooleanLiteral:)
  %3 = struct_extract %2, #Bool._value
  cond_br %3, bb1, bb2
```
->
```
  ...
  br bb1
```

This pass is intended to run before DefiniteInitialization, where mandatory inlining and constant folding didn't run, yet (which would perform this kind of optimization).
This optimization is required to let DefiniteInitialization handle boolean literals correctly.
For example in infinite loops:

```
   init() {
     while true {           // DI need to know that there is no loop exit from this while-statement
       if some_condition {
         member_field = init_value
         break
       }
     }
   }
```
2024-01-10 16:15:57 +01:00
Doug Gregor
bcf2371d31 Insert member-attribute macros right before modifiers
The insertion position of member-attribute macros was right before the
first attribute. However, ASTScope would visit the as-written attributes
first, so the scope tree entries would be out of order, causing name
lookup to fail.

Move the insertion position to where a new modifier would go, i.e.,
after the explicitly-written attributes. Fixes rdar://120496864.
2024-01-05 18:02:03 -08:00
Doug Gregor
3f518a3b79 [Macros] Don't apply member attribute macros to accessors
Accessors are conceptually nested within their property or subscript
declarations, so member-attribute macros should only apply to the
property or subscript declarations. This eliminates what appears to be
redundant macro expansion.

Fixes rdar://118956800.
2023-12-13 09:26:52 -08:00
Zhiyu Zhu/朱智语
5767e8f6d1 [Macros] Support module-qualified attached macro lookup (#69457)
Allow attached macro expansion syntax to have a module qualifier, `@Foo.Bar`.

rdar: //108621205
2023-12-08 15:57:51 -08:00
Holly Borla
8d22e48442 Merge pull request #70185 from hborla/sendable-extension-macro
[Concurrency] Check the outermost parent source file when diagnosing `Sendable` conformances outside the defining source file.
2023-12-02 15:03:37 -08:00
Holly Borla
4f68514f0a [Concurrency] Check the outermost parent source file when diagnosing
Sendable conformances outside the defining source file.

This allows macros to add a Sendable conformance when the macro is applied
in the same source file as the primary declaration.
2023-12-02 09:58:11 -08:00
Doug Gregor
1c158b5ac4 Allow preamble macros to introduce declarations with documented names
Preamble macros introduce code at the beginning of a function body.
Allow them to introduce declarations as well, so long as the macro
declaration properly declares the names it introduces. This allows all
sorts of exciting macros that introduce (e.g.) new local variables
that one can use.
2023-11-30 11:30:12 -08:00
Doug Gregor
380bad4e07 Implement preamble macros to augment a function body
Implement type checking support for preamble macros, which expands the
preamble macros and introduces them at the beginning of the function
body prior to type checking. Ensure that the resulting function bodies
type-check properly, including when composing multiple preamble macros
and with a preamble macro applied to the body of a function that
itself came from a body macro.
2023-11-27 17:05:52 -08:00
Doug Gregor
36a2dcd927 Implement function body macros
Function body macros allow one to introduce a function body for a
particular function, either providing a body for a function that
doesn't have one, or wholesale replacing the body of a function that
was written with a new one.
2023-11-27 17:04:55 -08:00
Doug Gregor
86863f4451 [Macros] Make sure we actually pass the conformance list to member macros
A bad test let this trivial bug through. Improve the test, fix the bug.
Fixes rdar://117227204.
2023-10-26 14:09:29 -07:00
Alex Hoppen
be11dc6101 Merge pull request #69338 from ahoppen/ahoppen/macro-def-warnings
[test] Fix warnings in syntax_macro_definitions.swift
2023-10-24 08:14:41 -07:00
Rintaro Ishizaki
55144fb302 [Macros] Add test for macro expansion printing
* Macro expanded member decls in .swiftinterface (rdar://117374821)
* cursor-info on a decl with peer macro attribute (rdar://117374966)
2023-10-23 15:21:33 -07:00
Alex Hoppen
1178ae14d4 [test] Fix warnings in syntax_macro_definitions.swift 2023-10-23 11:12:19 -07:00
Rintaro Ishizaki
bdd4c005e5 [Macros] Diagnose how ExternalMacroDefinition request was failed
Return the failure reason as the result.
2023-10-12 16:08:48 -07:00
Holly Borla
1f07cbae2a [Macros] Diagnose attached and freestanding declaration macros that produce
something other than a declaration.

The validation code already diagnosed all sorts of invalid declarations, but
it was ignoring AST nodes that aren't declarations at all.
2023-10-09 22:50:12 -07:00
Doug Gregor
596da3121d [SE-0407] Provide member macros with information about "missing" conformances
Provide member macros with similar information about conformances to
what extension macros receive, allowing member macros to document
which conformances they care about (e.g., Decodable) and then
receiving the list of conformances that aren't already available for
the type in question. For example, a macro such as

    @attached(member, conformances: Decodable, Encodable, names:
named(init(from:), encode(to:)))
    macro Codable() = ...

Expanded on a type that is not already Decodable/Encodable would be
provided with Decodable and Encodable (via the new
`missingConformancesTo:` argument to the macro implementation) when
the type itself does not conform to those types.

Member macros still cannot produce conformances, so this is likely to
be used in conjunction with extension macros most of the time. The
extension macro declares the conformance, and can also declare any
members that shouldn't be part of the primary type definition---such
as initializers that shouldn't suppress the memberwise initializer. On
the other hand, the member macro will need to define any members that
must be in the primary definition, such as required initializers,
members that must be overridable by subclasses, and stored properties.

Codable synthesis is an example that benefits from member macros with
conformances, because for classes it wants to introduce a required
initializer for decoding and an overridable encode operation, and
these must be members of the nominal type itself. Specifically, the
`Codable` macro above is likely to have two attached member roles:

    @attached(member, conformances: Decodable, Encodable, names:
named(init(from:), encode(to:)))
    @attached(extension, conformances: Decodable, Encodable, names:
named(init(from:), encode(to:)))
    macro Codable() = ...

where the "extension" role is responsible for defining the conformance
(always), and the "member" creates the appropriate members for classes
(`init` vs. `required init`).

Tracked by rdar://112532829.
2023-09-07 08:20:46 -07:00
Hamish Knight
94cf5620d5 [Sema] Catch invalid if/switch exprs in more places
Move out-of-place SingleValueStmtExpr checking into
`performSyntacticExprDiagnostics`, to ensure we
catch all expressions. Previously we did the walk
as a part of Decl-based MiscDiagnostics, but it
turns out that can miss expressions in property
initializers, subscript default arguments, and
custom attrs.

This does mean that we'll now no longer diagnose
out-of-place if/switch exprs if the expression
didn't type-check, but that's consistent with the
rest of MiscDiagnostics, and I don't think it will
be a major issue in practice. We probably ought to
consider moving this checking into PreCheckExpr,
but that would require first separating out
SequenceExpr folding, which has other consequences,
and so I'm leaving as future work for now.
2023-08-30 12:57:29 +01:00
Doug Gregor
8371d3b517 [Macros] Ensure that we find operators in any macro-expanded context.
In any nominal declaration or extension thereof that is produced by a
macro expansion, make sure we perform qualified name lookup when
resolving operators so that we're guaranteed to find the
macro-introduced operators. Otherwise, expanding a macro that defines
a new type with conformances involving operators doesn't work.

Fixes rdar://114257019,
2023-08-23 04:54:56 -07:00
Doug Gregor
221e0e0627 Merge pull request #68059 from DougGregor/module-interface-print-freestanding-macro-expansion
[Swift interface] Print declarations produced by declaration macro expansion
2023-08-22 13:42:00 -07:00
Doug Gregor
8e4484660a [Macros] Add test case for #67989 / rdar://114105615.
The bug described by this report has been fixed on main. Add a test case
to ensure that it doesn't regress.
2023-08-21 23:31:47 -07:00