Skip to content
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

Add support for lexical context #31

Merged
merged 2 commits into from
Aug 28, 2024
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
4 changes: 3 additions & 1 deletion Sources/MacroTesting/AssertMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,9 @@ public func assertMacro(
#if canImport(SwiftSyntax600)
var expandedSourceFile = origSourceFile.expand(
macros: macros,
contextGenerator: { _ in context },
contextGenerator: { syntax in
BasicMacroExpansionContext(sharingWith: context, lexicalContext: syntax.allMacroLexicalContexts())
},
indentationWidth: indentationWidth
)
#else
Expand Down
52 changes: 52 additions & 0 deletions Tests/MacroTestingTests/EntryMacroTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import MacroTesting
import XCTest

final class EntryMacroTests: BaseTestCase {
override func invokeTest() {
withMacroTesting(
macros: [
EntryMacro.self,
]
) {
super.invokeTest()
}
}

func testWithinEnvironmentValues() {
assertMacro {
"""
extension EnvironmentValues {
@Entry var x: String = ""
}
"""
} expansion: {
"""
extension EnvironmentValues {
var x: String {
get {
fatalError()
}
}
}
"""
}
}

func testNotWithinEnvironmentValues() {
assertMacro {
"""
extension String {
@Entry var x: String = ""
}
"""
} diagnostics: {
"""
extension String {
@Entry var x: String = ""
┬─────
╰─ 🛑 '@Entry' macro can only attach to var declarations inside extensions of EnvironmentValues
}
"""
}
}
}
25 changes: 25 additions & 0 deletions Tests/MacroTestingTests/MacroExamples/EntryMacro.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import SwiftSyntax
import SwiftSyntaxMacros

// Not complete, just enough to unit test lexical context.
public struct EntryMacro: AccessorMacro {
public static func expansion(
of node: AttributeSyntax,
providingAccessorsOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [AccessorDeclSyntax] {
let isInEnvironmentValues = context.lexicalContext.contains { lexicalContext in
lexicalContext.as(ExtensionDeclSyntax.self)?.extendedType.trimmedDescription == "EnvironmentValues"
}

guard isInEnvironmentValues else {
throw MacroExpansionErrorMessage("'@Entry' macro can only attach to var declarations inside extensions of EnvironmentValues")
}

return [
AccessorDeclSyntax(accessorSpecifier: .keyword(.get)) {
"fatalError()"
},
]
}
}
Loading