@expo/expo-modules-macros-plugin 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apple/ExpoModulesMacros-tool +0 -0
- package/apple/Sources/ExpoModulesMacros/DecorateFunctionBuilder.swift +27 -5
- package/apple/Sources/ExpoModulesMacros/JSMacro.swift +82 -18
- package/apple/Sources/ExpoModulesMacros/RecordMacro.swift +12 -0
- package/apple/Sources/ExpoModulesMacros/TypeConformanceAssertion.swift +105 -0
- package/package.json +1 -1
|
Binary file
|
|
@@ -112,17 +112,39 @@ internal struct JSFunction {
|
|
|
112
112
|
/// **strong** — the host-function closure is what keeps the native callable alive for as long as
|
|
113
113
|
/// JS can invoke it; its lifetime is bounded by the JS VM's garbage collection of the object.
|
|
114
114
|
/// `appContext` is captured **weak** (and guarded) so it doesn't form a real retain cycle through
|
|
115
|
-
/// the app context.
|
|
115
|
+
/// the app context. When no argument or return value goes through the dynamic-type converter the
|
|
116
|
+
/// body never references `appContext`, so the capture and guard are omitted to avoid the
|
|
117
|
+
/// unused-capture warning.
|
|
116
118
|
var decorateStatements: String {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
119
|
+
if usesAppContext {
|
|
120
|
+
return """
|
|
121
|
+
object.setProperty("\(jsName)") { [weak appContext, self] this, arguments in
|
|
122
|
+
guard let appContext else {
|
|
123
|
+
throw Exceptions.AppContextLost()
|
|
124
|
+
}
|
|
125
|
+
\(bodyStatements(indent: " "))
|
|
121
126
|
}
|
|
127
|
+
"""
|
|
128
|
+
}
|
|
129
|
+
return """
|
|
130
|
+
object.setProperty("\(jsName)") { [self] this, arguments in
|
|
122
131
|
\(bodyStatements(indent: " "))
|
|
123
132
|
}
|
|
124
133
|
"""
|
|
125
134
|
}
|
|
135
|
+
|
|
136
|
+
/// True when the host-function body references `appContext` — i.e. some parameter or the return
|
|
137
|
+
/// type lacks a fast accessor and decodes/encodes through `getDynamicType()`, which threads
|
|
138
|
+
/// `appContext` in.
|
|
139
|
+
private var usesAppContext: Bool {
|
|
140
|
+
if parameters.contains(where: { fastDecodeAccessor(for: $0.type.trimmedDescription) == nil }) {
|
|
141
|
+
return true
|
|
142
|
+
}
|
|
143
|
+
if let returnType, fastDecodeAccessor(for: returnType) == nil {
|
|
144
|
+
return true
|
|
145
|
+
}
|
|
146
|
+
return false
|
|
147
|
+
}
|
|
126
148
|
}
|
|
127
149
|
|
|
128
150
|
/**
|
|
@@ -1,29 +1,93 @@
|
|
|
1
1
|
import SwiftSyntax
|
|
2
2
|
import SwiftSyntaxMacros
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
4
|
+
/// Marker macro applied to module / shared-object members that should be exposed to JavaScript.
|
|
5
|
+
/// `@ExpoModule` and `@SharedObject` discover declarations carrying this attribute and generate the
|
|
6
|
+
/// corresponding `Function` / `AsyncFunction` / `Property` / `Constructor` registrations; that part
|
|
7
|
+
/// of the expansion lives in those macros.
|
|
8
|
+
///
|
|
9
|
+
/// On its own, `@JS` emits one thing: a never-called peer that asserts every type crossing the JS
|
|
10
|
+
/// boundary is JS-convertible. Because it's a **peer** of the marked member, a non-conforming type
|
|
11
|
+
/// produces a compile error located on the user's own `@JS` declaration rather than on the enclosing
|
|
12
|
+
/// `@ExpoModule`. The assertion mechanism itself is shared (see `typeConformanceAssertion`); `@JS`
|
|
13
|
+
/// only supplies the boundary types it reads off the declaration.
|
|
14
|
+
///
|
|
15
|
+
/// Usage:
|
|
16
|
+
///
|
|
17
|
+
/// @JS
|
|
18
|
+
/// func greet(name: String) -> String { ... }
|
|
19
|
+
///
|
|
20
|
+
/// @JS("doWork")
|
|
21
|
+
/// func performWork() async throws { ... }
|
|
22
|
+
///
|
|
23
|
+
/// @JS
|
|
24
|
+
/// var status: String { "ok" }
|
|
21
25
|
public struct JSMacro: PeerMacro {
|
|
22
26
|
public static func expansion(
|
|
23
27
|
of node: AttributeSyntax,
|
|
24
28
|
providingPeersOf declaration: some DeclSyntaxProtocol,
|
|
25
29
|
in context: some MacroExpansionContext
|
|
26
30
|
) throws -> [DeclSyntax] {
|
|
27
|
-
|
|
31
|
+
guard let member = boundaryMember(of: declaration),
|
|
32
|
+
let assertion = typeConformanceAssertion(
|
|
33
|
+
for: ConformanceAssertion(name: member.name, types: member.types),
|
|
34
|
+
isStatic: member.isStatic
|
|
35
|
+
) else {
|
|
36
|
+
return []
|
|
37
|
+
}
|
|
38
|
+
return [assertion]
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// What an assertion peer needs about the `@JS` member it sits beside: a name (to keep the peer
|
|
43
|
+
/// unique among siblings), the types crossing the JS boundary, and whether the member is type-level.
|
|
44
|
+
private struct BoundaryMember {
|
|
45
|
+
let name: String
|
|
46
|
+
/// Boundary types as written. Composed types (`[Int]`, `String?`, …) are kept verbatim — their
|
|
47
|
+
/// conditional conformances transitively constrain the elements.
|
|
48
|
+
let types: [String]
|
|
49
|
+
/// True for `static`/`class` members, so the peer is emitted in the same metatype context.
|
|
50
|
+
let isStatic: Bool
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// Reads the boundary member off a `@JS` declaration. A function contributes its parameter types
|
|
54
|
+
/// plus the return type (when non-Void); a property contributes its declared type. Returns `nil` for
|
|
55
|
+
/// declaration kinds `@JS` doesn't read types from, or a property whose type isn't spelled out (a
|
|
56
|
+
/// syntactic macro can't recover it), so no assertion is emitted there.
|
|
57
|
+
private func boundaryMember(of declaration: some DeclSyntaxProtocol) -> BoundaryMember? {
|
|
58
|
+
if let funcDecl = declaration.as(FunctionDeclSyntax.self) {
|
|
59
|
+
var types = funcDecl.signature.parameterClause.parameters.map { $0.type.trimmedDescription }
|
|
60
|
+
if let returnType = funcDecl.signature.returnClause?.type, !isVoidType(returnType) {
|
|
61
|
+
types.append(returnType.trimmedDescription)
|
|
62
|
+
}
|
|
63
|
+
return BoundaryMember(name: funcDecl.name.text, types: types, isStatic: isTypeLevel(funcDecl.modifiers))
|
|
28
64
|
}
|
|
65
|
+
|
|
66
|
+
if let varDecl = declaration.as(VariableDeclSyntax.self),
|
|
67
|
+
let binding = varDecl.bindings.first,
|
|
68
|
+
let identifier = binding.pattern.as(IdentifierPatternSyntax.self),
|
|
69
|
+
let type = binding.typeAnnotation?.type {
|
|
70
|
+
return BoundaryMember(
|
|
71
|
+
name: identifier.identifier.text,
|
|
72
|
+
types: [type.trimmedDescription],
|
|
73
|
+
isStatic: isTypeLevel(varDecl.modifiers)
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return nil
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/// True when the modifiers make the member type-level (`static` or `class`), so its assertion peer
|
|
81
|
+
/// must be emitted in the same metatype context rather than as an instance member.
|
|
82
|
+
private func isTypeLevel(_ modifiers: DeclModifierListSyntax) -> Bool {
|
|
83
|
+
return modifiers.contains {
|
|
84
|
+
$0.name.tokenKind == .keyword(.static) || $0.name.tokenKind == .keyword(.class)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// True when a return clause is written as `Void` / `()` — nothing crosses the boundary, so it needs
|
|
89
|
+
/// no conformance assertion. (A missing return clause never reaches here: `returnClause` is `nil`.)
|
|
90
|
+
private func isVoidType(_ type: TypeSyntax) -> Bool {
|
|
91
|
+
let text = type.trimmedDescription
|
|
92
|
+
return text == "Void" || text == "()"
|
|
29
93
|
}
|
|
@@ -59,6 +59,18 @@ public struct RecordMacro: MemberMacro, ExtensionMacro {
|
|
|
59
59
|
let existingInitLabels = initializerParameterLabels(of: declaration)
|
|
60
60
|
|
|
61
61
|
var members: [DeclSyntax] = []
|
|
62
|
+
|
|
63
|
+
// A single never-called member that makes the compiler verify each property type is
|
|
64
|
+
// JS-convertible (the conversions below go through its dynamic-type API). Each property keeps its
|
|
65
|
+
// own named assertion inside, so the compiler's conformance diagnostic names the offending
|
|
66
|
+
// property (see `typeConformanceAssertions`). Emitted first so that, for a non-conforming type,
|
|
67
|
+
// this clear "requires that '…' conform to '…'" error is reported ahead of the noisier
|
|
68
|
+
// "no member 'getDynamicType'" errors from the conversion code below.
|
|
69
|
+
let assertions = properties.map { ConformanceAssertion(name: $0.name, types: [$0.type]) }
|
|
70
|
+
if let assertionMember = typeConformanceAssertions(for: assertions) {
|
|
71
|
+
members.append(assertionMember)
|
|
72
|
+
}
|
|
73
|
+
|
|
62
74
|
if !existingInitLabels.contains([]) {
|
|
63
75
|
if let defaultInit = defaultInit(properties: properties, isClass: isClass) {
|
|
64
76
|
members.append(defaultInit)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import SwiftSyntax
|
|
2
|
+
|
|
3
|
+
/// The protocol that every type crossing the JS boundary must conform to. Centralized here so the
|
|
4
|
+
/// eventual rename (this is a placeholder name) is a single edit, and shared by every macro that
|
|
5
|
+
/// asserts the conformance (`@JS`, `@Record`, …).
|
|
6
|
+
internal let jsConvertibleProtocolName = "AnyArgument"
|
|
7
|
+
|
|
8
|
+
/// Types we never assert because they're statically known to conform and never reach the dynamic
|
|
9
|
+
/// converter: the JS primitives. Asserting them would only add noise to the expansion. Kept here
|
|
10
|
+
/// (rather than reusing the decode-path's `fastDecodeAccessor`) because "known-to-conform" is a
|
|
11
|
+
/// concept that belongs with the assertion logic, not with how a value is decoded.
|
|
12
|
+
private let knownConformingPrimitives: Set<String> = ["Bool", "Int", "Double", "String"]
|
|
13
|
+
|
|
14
|
+
/// One member's worth of conformance assertion: a name (the member it stands for) and the declared
|
|
15
|
+
/// types crossing the JS boundary for it. The name surfaces verbatim in the compiler's conformance
|
|
16
|
+
/// diagnostic ("local function '<name>' requires that '<Type>' conform to …"), so it identifies the
|
|
17
|
+
/// offending member in the error message on top of the location pointing at the user's declaration.
|
|
18
|
+
internal struct ConformanceAssertion {
|
|
19
|
+
let name: String
|
|
20
|
+
/// Declared types as written. Composed types (`[Int]`, `String?`, …) are kept verbatim — their
|
|
21
|
+
/// conditional conformances transitively constrain the elements.
|
|
22
|
+
let types: [String]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// A single conformance-assertion peer for a `@JS` member: a never-called `private func` whose body
|
|
26
|
+
/// statically asserts the member's boundary types conform. The assertion is compile-time only — the
|
|
27
|
+
/// function is never invoked, but Swift still type-checks its body, so a non-conforming type becomes
|
|
28
|
+
/// a compile error. Emitted as a **peer** of the user's declaration, so that error lands on the
|
|
29
|
+
/// user's own member rather than on the enclosing macro.
|
|
30
|
+
///
|
|
31
|
+
/// `isStatic` makes the peer `static`, mirroring a `static`/`class` member so it's emitted in the
|
|
32
|
+
/// right metatype context (a peer of a type-level member can't be an instance method). `class func`
|
|
33
|
+
/// members collapse to `static` here too: the peer is private and never called or overridden, so
|
|
34
|
+
/// `static` is always sufficient.
|
|
35
|
+
///
|
|
36
|
+
/// Returns `nil` when nothing is left to assert (every type was a known-conforming primitive, or the
|
|
37
|
+
/// list was empty), so the caller emits nothing in that case.
|
|
38
|
+
internal func typeConformanceAssertion(for assertion: ConformanceAssertion, isStatic: Bool) -> DeclSyntax? {
|
|
39
|
+
guard let body = conformanceAssertionBody(assertion) else {
|
|
40
|
+
return nil
|
|
41
|
+
}
|
|
42
|
+
let staticKeyword = isStatic ? "static " : ""
|
|
43
|
+
return """
|
|
44
|
+
private \(raw: staticKeyword)func _assertTypesConformance_\(raw: assertion.name)() {
|
|
45
|
+
\(raw: body)
|
|
46
|
+
}
|
|
47
|
+
"""
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// One conformance-assertion peer covering several members' assertions at once — used by `@Record`,
|
|
51
|
+
/// which folds every property into a single `_assertTypesConformance()` rather than emitting a peer
|
|
52
|
+
/// per property. Each assertion keeps its own named nested helper, so the per-member naming in the
|
|
53
|
+
/// diagnostic is preserved even though they share one peer.
|
|
54
|
+
///
|
|
55
|
+
/// Returns `nil` when no assertion has anything left to verify (all primitives / empty), so the
|
|
56
|
+
/// caller emits nothing.
|
|
57
|
+
internal func typeConformanceAssertions(for assertions: [ConformanceAssertion]) -> DeclSyntax? {
|
|
58
|
+
let bodies = assertions.compactMap(conformanceAssertionBody)
|
|
59
|
+
guard !bodies.isEmpty else {
|
|
60
|
+
return nil
|
|
61
|
+
}
|
|
62
|
+
return """
|
|
63
|
+
private func _assertTypesConformance() {
|
|
64
|
+
\(raw: bodies.joined(separator: "\n"))
|
|
65
|
+
}
|
|
66
|
+
"""
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// The assertion's body fragment: a nested generic helper named after the member, plus one call per
|
|
70
|
+
/// distinct non-primitive type. Nesting the helper keeps the constraint entirely local — no shared
|
|
71
|
+
/// symbol, nothing to collide, nothing left in the type's namespace — and naming it after the member
|
|
72
|
+
/// puts the member's name in the compiler's conformance diagnostic. Returns `nil` when every type was
|
|
73
|
+
/// a known-conforming primitive or the list was empty.
|
|
74
|
+
private func conformanceAssertionBody(_ assertion: ConformanceAssertion) -> String? {
|
|
75
|
+
// Unwrap top-level optionals to the core type, then dedup so each type is asserted once even when
|
|
76
|
+
// it appears more than once; skip known primitives.
|
|
77
|
+
var seen: Set<String> = []
|
|
78
|
+
var distinct: [String] = []
|
|
79
|
+
for type in assertion.types.map(unwrappedOptional)
|
|
80
|
+
where !knownConformingPrimitives.contains(type) && seen.insert(type).inserted {
|
|
81
|
+
distinct.append(type)
|
|
82
|
+
}
|
|
83
|
+
guard !distinct.isEmpty else {
|
|
84
|
+
return nil
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
var lines = ["func \(assertion.name)<T: \(jsConvertibleProtocolName)>(_: T.Type) {}"]
|
|
88
|
+
lines.append(contentsOf: distinct.map { "\(assertion.name)(\($0).self)" })
|
|
89
|
+
return lines.joined(separator: "\n")
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/// Strips every trailing optional marker (`?`/`!`) so the assertion targets the core wrapped type.
|
|
93
|
+
/// `Optional<W>: AnyArgument` holds exactly when `W: AnyArgument` (and `T!` is just `T?`), so each
|
|
94
|
+
/// layer is conformance-equivalent to its wrapped type. Asserting the core gives a cleaner diagnostic
|
|
95
|
+
/// (the direct `requires that '<type>' conform`, not the conditional-conformance phrasing through
|
|
96
|
+
/// `Optional`) and sidesteps that `T!.self` is invalid in metatype position. Only *trailing* markers
|
|
97
|
+
/// are stripped, so `[Int?]` keeps its inner `?`; a longhand `Optional<W>` isn't peeled but is still
|
|
98
|
+
/// asserted whole, which remains correct.
|
|
99
|
+
private func unwrappedOptional(_ type: String) -> String {
|
|
100
|
+
var result = Substring(type)
|
|
101
|
+
while result.hasSuffix("?") || result.hasSuffix("!") {
|
|
102
|
+
result = result.dropLast()
|
|
103
|
+
}
|
|
104
|
+
return String(result)
|
|
105
|
+
}
|