Skip to content

Commit 760c3e5

Browse files
committed
Start field
1 parent fff9483 commit 760c3e5

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Sources/JavaKitMacros/JavaFieldMacro.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ extension JavaFieldMacro: AccessorMacro {
3333
return []
3434
}
3535

36+
let isStatic = node.attributeName.trimmedDescription == "JavaStaticMethod"
37+
guard !isStatic || isInStaticContext(context: context) else {
38+
throw MacroExpansionErrorMessage("Cannot use @JavaStaticMethod outside of a JavaClass instance")
39+
}
40+
3641
// Dig out the Java field name, if provided. Otherwise, use the name as written.
3742
let fieldName =
3843
if case .argumentList(let arguments) = node.arguments,
@@ -79,4 +84,18 @@ extension JavaFieldMacro: AccessorMacro {
7984

8085
return accessors
8186
}
87+
88+
private static func isInStaticContext(context: some MacroExpansionContext) -> Bool {
89+
for lexicalContext in context.lexicalContext {
90+
if let classSyntax = lexicalContext.as(StructDeclSyntax.self) {
91+
if classSyntax.name.trimmedDescription.starts(with: "JavaClass") {
92+
return true
93+
} else {
94+
return false
95+
}
96+
}
97+
}
98+
99+
return false
100+
}
82101
}

Tests/JavaKitMacroTests/JavaClassMacroTests.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,25 @@ class JavaKitMacroTests: XCTestCase {
2626
"JavaField": JavaFieldMacro.self
2727
]
2828

29+
func testJavaStaticMethodFailure() throws {
30+
assertMacroExpansion(
31+
"""
32+
@JavaClass("org.swift.example.HelloWorld")
33+
public struct HelloWorld {
34+
@JavaStaticMethod
35+
public init(environment: JNIEnvironment? = nil)
36+
}
37+
""",
38+
expandedSource: """
39+
40+
public struct HelloWorld {
41+
}
42+
""",
43+
diagnostics: [DiagnosticSpec(message: "", line: 0, column: 0)],
44+
macros: Self.javaKitMacros
45+
)
46+
}
47+
2948
func testJavaClass() throws {
3049
assertMacroExpansion("""
3150
@JavaClass("org.swift.example.HelloWorld")

0 commit comments

Comments
 (0)