# SE-0382: Expression Macros

**URL:** <https://forums.swift.org/t/se-0382-expression-macros/62090>\
**Category:** Proposal Reviews\
**Created:** [December 16, 2022, 7:05pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090 "2022-12-16T19:05:14Z")\
**Posts on this page:** 20\
**Page:** 3

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [January 6, 2023, 6:39pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/43 "2023-01-06T18:39:00Z")

</div>

> [@esummers](#):
>
> I personally think this still fits in with progressive disclosure. Particularly since I don't see macro writing as something one will generally need to learn. They are in the domain of DSL writers where it is natural to work with syntax nodes. I'd rather see this then some sort of macro sub-language which I think is the only other alternative.

I agree that writing them will be rare (thankfully more rare than in C) but using them is also difficult since _every_ macro will have different rules. At least with result builders the basic syntax within the builder is the same whether or no the builder has implemented supported for all of the `build*` methods.

The magic of `Codable` and `Equatable` synthesis is slight, as you can hand write that logic (and we do) quite easily. Not really possible with generalized macros.

> [@esummers](#):
>
> I think debugging for a macro creator will be reasonable, but I think it would be nice if IDEs like Xcode could somehow preview the syntax node transformation to make it easier to peek behind the curtain.

What can you possibly be basing that on? Swift's current debugging experience is unreliable at best and macros would need a new type of compile time debugging as well as runtime support (writer and user debugging). Personally, I've run out of patience with Swift's tooling.

---

<div class="post-metadata">

**Author:** ![esummers](https://avatars.discourse-cdn.com/v4/letter/e/f04885/32.png) [@esummers](https://forums.swift.org/u/esummers)\
**Post date:** [January 6, 2023, 9:48pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/44 "2023-01-06T21:48:47Z")

</div>

> [@Jon\_Shier](#):
>
> The magic of `Codable` and `Equatable` synthesis is slight, as you can hand write that logic (and we do) quite easily. Not really possible with generalized macros.

I think this is a good point, but probably one that makes more sense for declaration macros or some sort of auto-protocol conformance macro. I hope it will be best practice to look for a user implementation of any auto-generated code and allow that to override what the macro would have written. I think there is a strong need to establish good best practices for cases like this.

> [@Jon\_Shier](#):
>
> Swift's current debugging experience is unreliable at best and macros would need a new type of compile time debugging as well as runtime support

I guess I'm not clear on what form of debugging this refers to. If talking about lldb, I hope it will be able to step through the output of `-dump-macro-expansions`.

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [January 6, 2023, 9:52pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/45 "2023-01-06T21:52:34Z")

</div>

> [@esummers](#):
>
> I guess I'm not clear on what form of debugging this refers to. If talking about lldb, I hope it will be able to step through the output of `-dump-macro-expansions`.

Macro writers need to be able to set breakpoints in a macro during the build process when it's invoked so we can actually investigate the context and help build the macro. Macro users, if they have access to the macro source, may need to be able to do the same thing at runtime. I'm not sure how useful that is and it may already be possible, but the macro writer case seems impossible right now. In that way writing and debugging macros seems even more difficult than result builders.

---

<div class="post-metadata">

**Author:** ![esummers](https://avatars.discourse-cdn.com/v4/letter/e/f04885/32.png) [@esummers](https://forums.swift.org/u/esummers)\
**Post date:** [January 6, 2023, 10:14pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/46 "2023-01-06T22:14:04Z")

</div>

> [@Jon\_Shier](#):
>
> Macro writers need to be able to set breakpoints in a macro during the build process when it's invoked so we can actually investigate the context and help build the macro. Macro users, if they have access to the macro source, may need to be able to do the same thing at runtime. I'm not sure how useful that is and it may already be possible, but the macro writer case seems impossible right now. In that way writing and debugging macros seems even more difficult than result builders.

Ok. That seems easily solvable with advances to tooling though. I get that it might take awhile for tooling to improve if it isn't prioritized, but I don't see anything that would prevent creation of better tooling. Hopefully it would be implemented as a way to debug expansions regardless of if macro source is present, but that might be considered private API... It would be nice to see more about debugging in the proposal even if just as a future direction.

There may be some workarounds–admittedly tedious–like passing in a closure to hold a breakpoint during development.

Overall, I see a need for macros in some contexts and either manipulating syntax trees or using templates is what every modern macro system does. I personally prefer the former. I agree that good tooling should be part of the picture, but I still think the proposal is a step in the right direction.

EDIT: Small correction

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [January 6, 2023, 10:16pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/47 "2023-01-06T22:16:16Z")

</div>

My point is that I've lost faith that Apple will properly prioritize such tooling, so proposals that require it are automatic no votes unless the tooling is already being built in some way. Even then, the longevity of such tooling is questionable, so I'm generally negative on anything that needs it at all.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [January 6, 2023, 11:21pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/48 "2023-01-06T23:21:56Z")

</div>

While no doubt it is valid to want an excellent tooling experience, as part of the Swift Evolution process we consider the _implementability_ of proposals but do not evaluate either the quality of any actual implementation nor review any engineering roadmap.

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [January 6, 2023, 11:27pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/49 "2023-01-06T23:27:47Z")

</div>

I'm aware. Personally, _implementability_ should include tooling and the ecosystem as a whole, since no one uses a feature in a vacuum. Apple has especially lost my trust over the last two years, from implementation to tooling to maintenance. The language workgroup can consider what they want here, but this is how I'll vote from now on, at least for proposals like this.

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [January 7, 2023, 12:29am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/50 "2023-01-07T00:29:13Z")

</div>

> [@Douglas\_Gregor](#):
>
> In the final implementation, the version of SwiftSyntax you're coding against is whatever your package depends on. In today's prototype (where the macro implementations are built against the shared libraries in the toolchain), there's no good answer.

having worked with SwiftSyntax extensively over the summer, i’ve learned that the version of SwiftSyntax you are using is quite important, and getting it right is _more_, not _less_ difficult than getting normal build dependency resolution right. especially if you are distributing libraries and therefore (likely) targeting multiple toolchain versions per release.

i won’t comment on the pros or cons of macros themselves, but i really do not think it is a good idea to start exposing this feature until the SwiftSyntax versioning story is more fleshed out.

---

<div class="post-metadata">

**Author:** ![tgoyne](https://avatars.discourse-cdn.com/v4/letter/t/5e9695/32.png) [@tgoyne](https://forums.swift.org/u/tgoyne)\
**Post date:** [January 7, 2023, 1:27am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/51 "2023-01-07T01:27:41Z")

</div>

I strongly dislike Codable and Result Builders, and part of that dislike is that they remind me of early-2000s boost libraries that found "clever" ways to do things which seemed like they should be impossible which resulted in utterly alien code. They're even worse than those libraries, though, because they didn't actually find a clever way to make things like CodingKeys work, and instead had compiler magic added specifically to enable their weird misuse of the language. My assumption is that the unstated context behind the macro vision document is that other SDK teams at Apple want to do similar things for their APIs, and macros are a way to address that demand without a steady stream of niche special compiler magic. If those are indeed the two options, I would certainly pick a macro system every day.

I share many of the concerns around tooling. This proposal is implicitly promoting SwiftSyntex to being part of the language, and that's a very big deal for a library which is currently unstable, undocumented, and not really realistically usable by third-parties. I don't think it makes sense to send SwiftSyntax through the evolution process (I really can't imagine it getting much in the way of productive feedback), but there does need to be some sort of story for how SwiftSyntax is going to get to a state where it's reasonable for a language feature to depend on it.

Similarly, the question of if macros will be debuggable is very relevant to the question of if macros are a good idea or not. Macros which can be stepped through in a debugger and macros which can't be are categorically different in what sorts of problems they can cause, and it's very important to design a macro system which falls into the first category. "That's an implementation question" suggests that this macro system _hasn't_ been designed to ensure that it's debuggable, and that's a pretty big problem.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [January 7, 2023, 6:57am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/52 "2023-01-07T06:57:28Z")

</div>

> [@tgoyne](#):
>
> Similarly, the question of if macros will be debuggable is very relevant to the question of if macros are a good idea or not. Macros which can be stepped through in a debugger and macros which can't be are categorically different in what sorts of problems they can cause, and it's very important to design a macro system which falls into the first category. "That's an implementation question" suggests that this macro system _hasn't_ been designed to ensure that it's debuggable, and that's a pretty big problem.

To clarify, whether the design of a feature is conducive to or inhibits debugging is in scope for review, and any suggestions as to changes to the design which would improve the user debugging experience would be welcome.

“I’m only in favor of this feature if it _can_ be implemented well”—in scope for Swift Evolution.

“I’m only in favor of this feature if it _will_ be implemented well”—not up to us.

---

<div class="post-metadata">

**Author:** ![ensan-hcl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ensan-hcl/32/15186_2.png) [@ensan-hcl](https://forums.swift.org/u/ensan-hcl)\
**Post date:** [January 7, 2023, 7:52am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/53 "2023-01-07T07:52:21Z")

</div>

Does the dependence on SwiftSyntax mean that SwiftSyntax is now a part of official language specification?

---

<div class="post-metadata">

**Author:** ![benrimmington](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/benrimmington/32/695_2.png) [@benrimmington](https://forums.swift.org/u/benrimmington)\
**Post date:** [January 8, 2023, 12:41am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/54 "2023-01-08T00:41:38Z")

</div>

[`MacroExpansionContext`](https://github.com/apple/swift-evolution/blob/main/proposals/0382-expression-macros.md#macroexpansioncontext):

- What are the `moduleName` and `fileName` properties for?

- Does the public `init(moduleName:fileName:)` exist only for testing?

> <https://github.com/DougGregor/swift-macro-examples/blob/f00f2ec2a3c7e8be4668ea88079b30c315e90ed1/MacroExamplesPluginTest/MacroExamplesPluginTest.swift#L18-L21>

---

<div class="post-metadata">

**Author:** ![s-k](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/s-k/32/6796_2.png) [@s-k](https://forums.swift.org/u/s-k)\
**Post date:** [January 9, 2023, 2:49pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/55 "2023-01-09T14:49:07Z")

</div>

I finally came around to working some more on the result builder macro. Here are the results:

As I see it, there are two types of result builders:

- Type-erasing ones that always return the same type
- Ones that derive the result type from the code structure such as `SwiftUI`'s `ViewBuilder`

The feasibility of creating a macro that takes a type-erasing result builder type and a closure and produces a transformed closure has already been proven in [this](https://forums.swift.org/t/se-0382-expression-macros/62090/16) and [this](https://forums.swift.org/t/se-0382-expression-macros/62090/24) post. It is pretty simple and works as expected.

Doing the same for `ViewBuilder`-style result builders is more challenging. However, I have managed to implement a very rough proof-of-concept that does exactly this and works pretty well:

```swift
let very = true
let long = true

let viewClosure = #apply(resultBuilder: ViewBuilder.self) {
    Text("This")
    Text("is")
    Text("a")
    if very {
        Text("very")
    }
    if long {
        Label("long", systemImage: "arrow.left.and.right")
        Text("(really long)")
    } else {
        let shortWord = "short"
        Text(shortWord)
    }
    let lastWord = "sentence"
    Text(lastWord)
}

print(type(of: viewClosure()))
// prints TupleView<(Text, Text, Text, Optional<Text>, _ConditionalContent<TupleView<(Label<Text, Image>, Text)>, Text>, Text)>

```

The macro does not depend on nor is it specialized for `SwiftUI` or `ViewBuilder` (with one little caveat I will come to later). This means it should work for other result builder types. As far as I know, the macro produces the same function calls as the built-in feature.

> **Full implementation**
>
> In MacroExamplesLib:
> 
> ```swift
> @expression public macro apply<R>(resultBuilder: R.Type, to closure: () -> Void) -> (() -> any View) = #externalMacro(module: "MacroExamplesPlugin", type: "ResultBuilderMacro")
> 
> ```
> 
> In MacroExamplesPlugin:
> 
> ```swift
> public struct ResultBuilderMacro: ExpressionMacro {
> public static func expansion(
> of node: MacroExpansionExprSyntax, in context: inout MacroExpansionContext
> ) throws -> ExprSyntax {
> guard
> let resultBuilderSelfExpr = node.argumentList.first?.expression.as(MemberAccessExprSyntax.self),
> let resultBuilderName = resultBuilderSelfExpr.base?.withoutTrivia().description,
> let originalClosure = node.argumentList.dropFirst().first?.expression.as(ClosureExprSyntax.self) ?? node.trailingClosure
> else {
> throw SomeError()
> }
>         
> let originalStatements: [CodeBlockItemSyntax] = originalClosure.statements.map { $0.withoutTrivia() }
> return "{ () -> any View in\n\(raw: rewrittenStatements(forOriginalStatments: originalStatements, finalCallPrefix: "return ", resultBuilderName: resultBuilderName, context: &context))\n}"
> }
>     
> private static func rewrittenStatements(forOriginalStatments originalStatements: [CodeBlockItemSyntax], finalCallPrefix: String, finalCallSuffix: String = "", resultBuilderName: String, context: inout MacroExpansionContext) -> String {
> var localNames: [String] = []
> var newStatements: [String] = []
>         
> for statement in originalStatements {
> switch statement.item {
> case .expr(let expr):
> let localName = context.createUniqueLocalName().description
> newStatements.append("let \(localName) = \(expr);")
> localNames.append(localName)
> case .stmt(let stmt):
> let localName = context.createUniqueLocalName().description
> if let ifStmt = stmt.as(IfStmtSyntax.self) {
> if case .codeBlock(let elseBody) = ifStmt.elseBody {
> let tempIfName = context.createUniqueLocalName()
> let tempElseName = context.createUniqueLocalName()
> newStatements.append("""
> let \(localName) = {
> if false {
> \(rewrittenStatements(forOriginalStatments: ifStmt.body.statements.map { $0.withoutTrivia() }, finalCallPrefix: "let \(tempIfName) = ", resultBuilderName: resultBuilderName, context: &context))
> \(rewrittenStatements(forOriginalStatments: elseBody.statements.map { $0.withoutTrivia() }, finalCallPrefix: "let \(tempElseName) = ", resultBuilderName: resultBuilderName, context: &context))
> return true ? \(resultBuilderName).buildEither(first: \(tempIfName)) : \(resultBuilderName).buildEither(second: \(tempElseName))
> }
> if \(ifStmt.conditions) {
> \(rewrittenStatements(forOriginalStatments: ifStmt.body.statements.map { $0.withoutTrivia() }, finalCallPrefix: "return \(resultBuilderName).buildEither(first: ", finalCallSuffix: ")", resultBuilderName: resultBuilderName, context: &context))
> } else {
> \(rewrittenStatements(forOriginalStatments: elseBody.statements.map { $0.withoutTrivia() }, finalCallPrefix: "return \(resultBuilderName).buildEither(second: ", finalCallSuffix: ")", resultBuilderName: resultBuilderName, context: &context))
> }
> }()
> """)
> localNames.append(localName)
>                         
> } else {
> newStatements.append("""
> let \(localName) = {
> if \(ifStmt.conditions) {
> \(rewrittenStatements(forOriginalStatments: ifStmt.body.statements.map { $0.withoutTrivia() }, finalCallPrefix: "return \(resultBuilderName).buildIf(", finalCallSuffix: ")", resultBuilderName: resultBuilderName, context: &context))
> }
> return \(resultBuilderName).buildIf(nil)
> }()
> """)
> localNames.append(localName)
> }
> } else {
> newStatements.append(stmt.description)
> }
> default:
> newStatements.append(statement.description)
> }
> }
>         
> newStatements.append("\(finalCallPrefix)\(resultBuilderName).buildBlock(\(localNames.joined(separator: ", ")))\(finalCallSuffix)")
>         
> let joinedStatements = newStatements.joined(separator: "\n")
> return joinedStatements
> }
> }
> 
> ```

Here are the things I have learned along the way:

- With the built-in result builders feature, closures are able to return an opaque result type, i.e. `some View`. With the current implementation, macros are not allowed to return opaque result types so the macro is forced to return a closure producing `any View`. I suppose this is due to the fact that the macro is type-checked before being expanded. @Douglas_Gregor: Is there any chance that macros could return an opaque result type? I think this feature would be very valuable.

- The biggest problem in the macro implementation was to satisfy the type checker when transforming `if` statements. This is because a macro has no way of getting the type of subexpressions of the expression passed to the macro. I work around this by putting the generated `if` statement into a closure to use the automatic return type inference. I am not sure if putting the code into a closure can be a problem in some situations.

- If a user of the macro makes a mistake, the error produced is not so great. One example would be the error `Static method 'buildBlock' requires that 'Int' conform to 'View'`. The message can be helpful if the user knows a little about result builders. However, with the current implementation the error does not point to any code location. So the user must look through every line of code to find the error. I think the compiler could be improved to point to the location of the macro. However, it could not know, which subexpression is at fault.

- Currently, writing code using the result builder macro generates warnings such as `Result of 'Text' initializer is unused`, because in the original closure, the expression results are unused. I think the compiler should generate such warnings only _after_ macro expansion.

- This is the caveat I was alluding to earlier: The current implementation produces an error if a macro wants to return a closure whose return type depends on a generic argument:

- Overloading macros does not seem to work in this case:

All in all, I think the general directions laid out in this proposal is great and I am surprised that I came this far with the proposed feature. What I missed where (a) type information about subexpressions and (b) static reflection. I fear that without these features users of macros (macro users, not macro implementors) could face a very rough user experience because the macro often cannot anticipate errors. It must leave it up to the compiler to generate an error message that might or might not be helpful to the user.

* * *

> [@Douglas\_Gregor](#):
>
> So what if we kept the "spine" on the parent nodes in tact, but removed all child nodes that could be independent?

I think it's a good first step. It doesn't bring us the whole way, but it bridges the gap until macros gain an introspection API, wich is inevitable in my opinion.

---

<div class="post-metadata">

**Author:** ![tgoyne](https://avatars.discourse-cdn.com/v4/letter/t/5e9695/32.png) [@tgoyne](https://forums.swift.org/u/tgoyne)\
**Post date:** [January 9, 2023, 8:44pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/56 "2023-01-09T20:44:51Z")

</div>

> [@xwu](#):
>
> To clarify, whether the design of a feature is conducive to or inhibits debugging is in scope for review, and any suggestions as to changes to the design which would improve the user debugging experience would be welcome.
> 
> “I’m only in favor of this feature if it _can_ be implemented well”—in scope for Swift Evolution.
> 
> “I’m only in favor of this feature if it _will_ be implemented well”—not up to us.

Yeah, that's fair. It would be silly to insist that the proposal only be accepted if the implementation will be bug-free after all.

The scenario I'm thinking of that I think it currently not well-handled is when you're using a library which provides a macro, your use of the macro is not expanding to what you expect it to be, and you want to step through the expansion in a debugger to figure out what you're doing wrong. The proposed workflow of invoking the macro executable on just the macro to expand and debugging that is a very natural way to go about developing the macro, but seems quite clunky to set up for a _user_ of the macro.

The ideal experience here is what DrRacket does, where debugging macro expansion is identical to debugging ordinary code. That is largely made possible by the fact that in Racket macro expansion is just one of the phases of execution rather than a "compile time" thing, but it's theoretically possible that Xcode could do something sufficiently clever to fake this. If Xcode isn't planning to do something clever, then what's the best we can do? One idea would be to attach by name to the macro executable and then hit build in Xcode. This probably works well if you have exactly one use of the macro, but doesn't if you want to debug the second one. Maybe there could be a way to tell Swift to perform expansion on a specific use of a macro first?

---

<div class="post-metadata">

**Author:** ![Brad\_Hilton](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/brad_hilton/32/5169_2.png) [@Brad\_Hilton](https://forums.swift.org/u/Brad_Hilton)\
**Post date:** [January 9, 2023, 9:12pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/57 "2023-01-09T21:12:48Z")

</div>

Hmm, this seems to add a lot of new syntax. Perhaps we could reuse some idioms we already have, like importing macros from modules instead of having to do separate declarations for them. And I think they would be better suited as functions or callable structs. Just my two cents.

---

<div class="post-metadata">

**Author:** ![soumyamahunt](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/soumyamahunt/32/23427_2.png) [@soumyamahunt](https://forums.swift.org/u/soumyamahunt)\
**Post date:** [January 10, 2023, 1:52pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/58 "2023-01-10T13:52:53Z")

</div>

One concern I have is as macro authors how can we write test cases for macro?  
I would like this to be addressed by this proposal as well.

---

<div class="post-metadata">

**Author:** ![Douglas\_Gregor](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/douglas_gregor/32/1362_2.png) [@Douglas\_Gregor](https://forums.swift.org/u/Douglas_Gregor)\
**Post date:** [January 11, 2023, 12:29am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/59 "2023-01-11T00:29:55Z")

</div>

> [@soumyamahunt](#):
>
> One concern I have is as macro authors how can we write test cases for macro?  
> I would like this to be addressed by this proposal as well.

Generally, you write test cases for the syntactic transforms. The [sample repository](https://github.com/DougGregor/swift-macro-examples/blob/main/MacroExamplesPluginTest/MacroExamplesPluginTest.swift) has just the one simple one, and there's a whole lot more interesting ones [here in the swift-syntax repository](https://github.com/apple/swift-syntax/blob/main/Tests/SwiftSyntaxMacrosTest/MacroSystemTests.swift#L386-L521).

Doug

---

<div class="post-metadata">

**Author:** ![s-k](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/s-k/32/6796_2.png) [@s-k](https://forums.swift.org/u/s-k)\
**Post date:** [January 12, 2023, 6:54am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/60 "2023-01-12T06:54:56Z")

</div>

@Douglas_Gregor I would appreciate it if you could respond to the questions in my [previous post](https://forums.swift.org/t/se-0382-expression-macros/62090/55) before the review deadline. I would especially want to know if the problems I encountered where bugs or features. Then we will be able to discuss the implications of that. Thank you.

* * *

And there is one more concern I want to mention: Up until recently, if you wanted to use SwiftSyntax in a library (e.g. for code generation in a swift package plugin), you had to fulfill one of these requirements:

1. Depend on the exact SwiftSyntax version matching the toolchain of the library user. This is not feasible because different users use different versions of Xcode, etc.
2. Supply a dylib for every toolchain-platform combination with the library.

Is this still a requirement? The [SwiftSyntax changelog](https://github.com/apple/swift-syntax/blob/main/Changelog.md) seems to suggest, it isn't and I didn't have time to check. If this is still a requirement, it will be very problematic for libraries vending macros.

---

<div class="post-metadata">

**Author:** ![Douglas\_Gregor](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/douglas_gregor/32/1362_2.png) [@Douglas\_Gregor](https://forums.swift.org/u/Douglas_Gregor)\
**Post date:** [January 12, 2023, 6:00pm UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/61 "2023-01-12T18:00:11Z")

</div>

> [@s-k](#):
>
> I finally came around to working some more on the result builder macro.

Very cool!

> [@s-k](#):
>
> Is there any chance that macros could return an opaque result type? I think this feature would be very valuable.

I can certainly see how it would be valuable. Opaque result types as they exist today for functions/properties/subscripts have a notion of identity that is tied to the function/property/subscript returning them, where the identity of the opaque type is determined by that function/property/subscript and any generic arguments to it. That notion of identity doesn't work for macros, because macros get the source code of the arguments and everything that you can access via the macro expansion context, so there's no way to establish identity. That's the logic I followed in banning opaque result types for macros.

However, we could say that every use of a macro that has an opaque result type produces a completely unique opaque type, similar to what happens when we [open an existential](https://github.com/apple/swift-evolution/blob/main/proposals/0352-implicit-open-existentials.md). From a compiler perspective, we know the opaque result type after macro expansion.

That's all a very long-winded way to say that I think we can lift the restriction, and allow opaque result types for macros. @Joe_Groff does the above seem plausible to you?

> [@s-k](#):
>
> 1. Making type inference smart enough to infer the return type of the closure if the `if false { ... }` is dropped.

I think this is my preferred solution, which we've talked about at various times as being a "join" of the types of each of the returns.

> [@s-k](#):
>
> If a user of the macro makes a mistake, the error produced is not so great. One example would be the error `Static method 'buildBlock' requires that 'Int' conform to 'View'`. The message can be helpful if the user knows a little about result builders. However, with the current implementation the error does not point to any code location. So the user must look through every line of code to find the error. I think the compiler could be improved to point to the location of the macro. However, it could not know, which subexpression is at fault.

The compiler model here does have some of this information, but it's not being surfaced well to users. When a macro is expanded, the compiler creates an internal buffer containing the source code produced by the macro implementation. If something goes wrong when type-checking that code, the compiler will print an error message pointing into that buffer, with a follow-up note showing the location where the macro expansion was triggered. The result looks something like this (extracted from a compiler test case):

```swift
macro:addBlocker:/swift/test/Macros/macro_expand.swift:81:7-81:27:1:4: error: binary operator '-' cannot be applied to two 'OnlyAdds' operands
oa - oa
~~^~~
/swift/test/Macros/macro_expand.swift:81:7: note: in expansion of macro 'addBlocker' here
  _ = #addBlocker(oa + oa)
      ^ ~~~~~~~~~~~~~~~~~~~

```

The `addBlocker` macro is my silly example which replaces `+` with `-`, so the `oa - oa` code is the result of macro expansion of `#addBlocker(oa + oa)`. That weird `macro:addBlocker:` file name is the name of the internal buffer, showing that the macro-expanded source code is there in a compiler, but it's only showing one line of it. We can do better here, for example by leveraging the [nifty formatter in swift-syntax](https://github.com/apple/swift-syntax/pull/874) to show more of the macro expansion buffer in the compiler's output. (This idea just came to me; I haven't tried it yet)

If you're using Xcode, you'll have to look into the build log to see the compiler output. Clang and Swift use a different serialized format for diagnostics when talking to IDEs, so all of this information is lost right now. I have an [RFC on the LLVM Discourse](https://discourse.llvm.org/t/extending-clangs-serialized-diagnostics-with-source-file-contents/67523) to extend that serialized format to include macro-expansion buffers. Swift's compiler already implements it, but IDEs would need to pick up the new APIs to provide a good experience here.

> [@s-k](#):
>
> The current implementation produces an error if a macro wants to return a closure whose return type depends on a generic argument:

That looks like a bug in the compiler implementation, rather than a limitation of the design.

> [@s-k](#):
>
> Is this the expected behavior or just a limitation of the current implementation? I would expect overloading macros to work just like overloading functions.

It's a limitation of the current implementation, thanks!

> [@s-k](#):
>
> All in all, I think the general directions laid out in this proposal is great and I am surprised that I came this far with the proposed feature.

Thank you for diving deep into result builders-via-macros! It's great to see what can be achieved with macros, what is still out of reach, and where the pain points are.

> [@s-k](#):
>
> @Douglas_Gregor I would appreciate it if you could respond to the questions in my [previous post](https://forums.swift.org/t/se-0382-expression-macros/62090/55) before the review deadline. I would especially want to know if the problems I encountered were bugs or features. Then we will be able to discuss the implications of that. Thank you.

Sorry 'bout the delay. Answers above.

> [@s-k](#):
>
> And there is one more concern I want to mention: Up until recently, if you wanted to use SwiftSyntax in a library (e.g. for code generation in a swift package plugin), you had to fulfill one of these requirements:
> 
> 1. Depend on the exact SwiftSyntax version matching the toolchain of the library user. This is not feasible because different users use different versions of Xcode, etc.
> 2. Supply a dylib for every toolchain-platform combination with the library.
> 
> Is this still a requirement?

Nope! With the advent of the [new Swift parser](https://forums.swift.org/t/a-new-swift-parser-for-swiftsyntax/59813), the swift-syntax package is all-Swift and fully standalone.

Doug

---

<div class="post-metadata">

**Author:** ![Douglas\_Gregor](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/douglas_gregor/32/1362_2.png) [@Douglas\_Gregor](https://forums.swift.org/u/Douglas_Gregor)\
**Post date:** [January 14, 2023, 6:59am UTC](https://forums.swift.org/t/se-0382-expression-macros/62090/62 "2023-01-14T06:59:07Z")

</div>

> [@benrimmington](#):
>
> [`MacroExpansionContext`](https://github.com/apple/swift-evolution/blob/main/proposals/0382-expression-macros.md#macroexpansioncontext):
> 
> - What are the `moduleName` and `fileName` properties for?
> - Does the public `init(moduleName:fileName:)` exist only for testing?

Sorry I missed your questions before, and you bring up a good point: given that we don't expose any other source location information, why these? Perhaps it would be better to remove them entirely and extend `MacroExpansionContext` later, with an eye toward a more complete approach to source-location information for source code that macros work with.

[**EDIT** : Yes, I'd like to remove `moduleName` and `fileName`. Your comment about the initializer made me realize that we should also switch `MacroExpansionContext` to a class-bound protocol so there can be separate macro expansion context implementations for e.g., testing vs. compilation. I put up a [pull request](https://github.com/apple/swift-evolution/pull/1912) with these changes.

Doug

[Previous page](https://forums.swift.org/t/se-0382-expression-macros/62090.md?page=2)

[Next page](https://forums.swift.org/t/se-0382-expression-macros/62090.md?page=4)
