Skip to content

Fold operators using the standard operator table in MacroSystem #2132

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class SourceManager {
case .attribute:
node = Syntax(AttributeSyntax.parse(from: &parser))
}
if let operatorTable = operatorTable {
if let operatorTable {
node = operatorTable.foldAll(node, errorHandler: { _ in /*ignore*/ })
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
//===----------------------------------------------------------------------===//

import SwiftDiagnostics
import SwiftOperators
import SwiftSyntax
import SwiftSyntaxMacros

Expand Down Expand Up @@ -77,6 +78,20 @@ extension BasicMacroExpansionContext {
detachedNodes[Syntax(detached)] = Syntax(node)
return detached
}

/// Fold all operators in `node` and associated the ``KnownSourceFile``
/// information of `node` with the original new, folded tree.
func foldAllOperators(of node: some SyntaxProtocol, with operatorTable: OperatorTable) -> Syntax {
let folded = operatorTable.foldAll(node, errorHandler: { _ in /*ignore*/ })
if let originalSourceFile = node.root.as(SourceFileSyntax.self),
let newSourceFile = folded.root.as(SourceFileSyntax.self)
{
// Folding operators doesn't change the source file and its associated locations
// Record the `KnownSourceFile` information for the folded tree.
sourceFiles[newSourceFile] = sourceFiles[originalSourceFile]
}
return folded
}
}

extension String {
Expand Down
64 changes: 54 additions & 10 deletions Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
//===----------------------------------------------------------------------===//

import SwiftDiagnostics
import SwiftOperators
@_spi(MacroExpansion) import SwiftParser
import SwiftSyntax
import SwiftSyntaxBuilder
Expand Down Expand Up @@ -55,7 +56,7 @@ private func expandFreestandingMemberDeclList(
let expanded = try expandFreestandingMacro(
definition: definition,
macroRole: inferFreestandingMacroRole(definition: definition),
node: node.detach(in: context),
node: node.detach(in: context, foldingWith: .standardOperators),
in: context,
indentationWidth: indentationWidth
)
Expand All @@ -80,7 +81,7 @@ private func expandFreestandingCodeItemList(
let expanded = try expandFreestandingMacro(
definition: definition,
macroRole: inferFreestandingMacroRole(definition: definition),
node: node.detach(in: context),
node: node.detach(in: context, foldingWith: .standardOperators),
in: context,
indentationWidth: indentationWidth
)
Expand Down Expand Up @@ -108,7 +109,7 @@ private func expandFreestandingExpr(
let expanded = expandFreestandingMacro(
definition: definition,
macroRole: .expression,
node: node.detach(in: context),
node: node.detach(in: context, foldingWith: .standardOperators),
in: context,
indentationWidth: indentationWidth
)
Expand All @@ -134,7 +135,7 @@ private func expandMemberMacro(
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .member,
attributeNode: attributeNode.detach(in: context),
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
Expand Down Expand Up @@ -163,7 +164,7 @@ private func expandMemberAttributeMacro(
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .memberAttribute,
attributeNode: attributeNode.detach(in: context),
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: member.detach(in: context),
parentDeclNode: declaration.detach(in: context),
extendedType: nil,
Expand Down Expand Up @@ -191,7 +192,7 @@ private func expandPeerMacroMember(
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .peer,
attributeNode: attributeNode.detach(in: context),
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
Expand Down Expand Up @@ -219,7 +220,7 @@ private func expandPeerMacroCodeItem(
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .peer,
attributeNode: attributeNode.detach(in: context),
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
Expand Down Expand Up @@ -251,7 +252,7 @@ private func expandAccessorMacroWithoutExistingAccessors(
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .accessor,
attributeNode: attributeNode.detach(in: context),
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
Expand Down Expand Up @@ -285,7 +286,7 @@ private func expandAccessorMacroWithExistingAccessors(
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .accessor,
attributeNode: attributeNode.detach(in: context),
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: nil,
Expand Down Expand Up @@ -322,7 +323,7 @@ private func expandExtensionMacro(
let expanded = expandAttachedMacro(
definition: definition,
macroRole: .extension,
attributeNode: attributeNode.detach(in: context),
attributeNode: attributeNode.detach(in: context, foldingWith: .standardOperators),
declarationNode: attachedTo.detach(in: context),
parentDeclNode: nil,
extendedType: extendedType.detach(in: context),
Expand Down Expand Up @@ -1011,4 +1012,47 @@ private extension SyntaxProtocol {

return self.detached
}

/// Fold operators in this node using the given operator table, detach the
/// node and inform the macro expansion context, if it needs to know.
func detach(
in context: MacroExpansionContext,
foldingWith operatorTable: OperatorTable?
) -> Syntax {
let folded: Syntax
if let operatorTable {
if let basicContext = context as? BasicMacroExpansionContext {
folded = basicContext.foldAllOperators(of: self, with: operatorTable)
} else {
folded = operatorTable.foldAll(self, errorHandler: { _ in /*ignore*/ })
}
} else {
folded = Syntax(self)
}
return folded.detach(in: context)
}
}

private extension FreestandingMacroExpansionSyntax {
/// Same as `SyntaxProtocol.detach(in:foldingWith:)` but returns a node of type
/// `Self` since we know that operator folding doesn't change the type of any
/// `FreestandingMacroExpansionSyntax`.
func detach(
in context: MacroExpansionContext,
foldingWith operatorTable: OperatorTable?
) -> Self {
return (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self)
return (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self)

What's the as needed for here? Doesn't this already return a Syntax?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It’s to disambiguate the version of detach that is being called. Without as Syntax we would have an infinite recursion here.

}
}

private extension AttributeSyntax {
/// Same as `SyntaxProtocol.detach(in:foldingWith:)` but returns a node of type
/// `Self` since we know that operator folding doesn't change the type of any
/// `AttributeSyntax`.
func detach(
in context: MacroExpansionContext,
foldingWith operatorTable: OperatorTable?
) -> Self {
return (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self)
}
}
58 changes: 58 additions & 0 deletions Tests/SwiftSyntaxMacroExpansionTest/ExpressionMacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -234,4 +234,62 @@ final class ExpressionMacroTests: XCTestCase {
)
}

func testFoldOperators() {
struct ForceSubtractMacro: ExpressionMacro {
static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> ExprSyntax {
guard let argument = node.argumentList.first?.expression else {
fatalError("Must receive an argument")
}
guard var node = argument.as(InfixOperatorExprSyntax.self) else {
return argument
}
node.operator = ExprSyntax(BinaryOperatorExprSyntax(text: "-"))
return ExprSyntax(node)
}
}
assertMacroExpansion(
"#test(1 + 2)",
expandedSource: "1 - 2",
macros: ["test": ForceSubtractMacro.self]
)
}

func testDiagnosticFromFoldedOperators() {
struct MyError: Error {}

struct DiagnoseFirstArgument: ExpressionMacro {
static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> ExprSyntax {
guard let argument = node.argumentList.first?.expression else {
fatalError("Must receive an argument")
}
context.addDiagnostics(from: MyError(), node: argument)
return argument
}
}

assertMacroExpansion(
"""
/// Test
func test() {
#test(1 + 2)
}
""",
expandedSource: """
/// Test
func test() {
1 + 2
}
""",
diagnostics: [
DiagnosticSpec(message: "MyError()", line: 3, column: 9, severity: .error)
],
macros: ["test": DiagnoseFirstArgument.self]
)
}
}
83 changes: 83 additions & 0 deletions Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,87 @@ final class MemberMacroTests: XCTestCase {
indentationWidth: indentationWidth
)
}

func testFoldOperators() {
struct ForceSubtractMacro: MemberMacro {
static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard case .argumentList(let arguments) = node.arguments, let argument = arguments.first?.expression else {
fatalError("Must receive an argument")
}
guard var node = argument.as(InfixOperatorExprSyntax.self) else {
return []
}
node.operator = ExprSyntax(BinaryOperatorExprSyntax(text: "- "))
return [
DeclSyntax(
"""
var x: Int { \(node.trimmed) }
"""
)
]
}
}
assertMacroExpansion(
"""
/// Test
/// And another line
@Test(1 + 2)
struct Foo {
}
""",
expandedSource: """
/// Test
/// And another line
struct Foo {

var x: Int {
1 - 2
}
}
""",
macros: ["Test": ForceSubtractMacro.self],
indentationWidth: indentationWidth
)
}

func testDiagnosticFromFoldedOperators() {
struct MyError: Error {}

struct DiagnoseFirstArgument: MemberMacro {
static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard case .argumentList(let arguments) = node.arguments, let argument = arguments.first?.expression else {
fatalError("Must receive an argument")
}
context.addDiagnostics(from: MyError(), node: argument)
return []
}
}

assertMacroExpansion(
"""
/// Test
/// And another line
@Test(1 + 2)
struct Foo {}
""",
expandedSource: """
/// Test
/// And another line
struct Foo {}
""",
diagnostics: [
DiagnosticSpec(message: "MyError()", line: 3, column: 7, severity: .error)
],
macros: ["Test": DiagnoseFirstArgument.self]
)
}

}