Repository navigation
Expand file tree
/
Copy pathJavaClassMacro.swift
More file actions
177 lines (156 loc) · 5.75 KB
/
Copy pathJavaClassMacro.swift
File metadata and controls
177 lines (156 loc) · 5.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros
import Foundation // for e.g. replacingOccurrences
package enum JavaClassMacro {}
extension JavaClassMacro: MemberMacro {
package static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard let namedDecl = declaration.asProtocol(NamedDeclSyntax.self) else {
throw MacroErrors.javaClassNotOnType
}
let swiftName = namedDecl.name.text
// Dig out the Java class name.
guard case .argumentList(let arguments) = node.arguments,
let wrapperTypeNameExpr = arguments.first?.expression,
let stringLiteral = wrapperTypeNameExpr.as(StringLiteralExprSyntax.self),
stringLiteral.segments.count == 1,
case let .stringSegment(classNameSegment)? = stringLiteral.segments.first
else {
throw MacroErrors.classNameNotStringLiteral
}
// Determine whether we're exposing the Java class as a Swift class, which
// changes how we generate some of the members.
let isSwiftClass: Bool
let isJavaLangObject: Bool
let specifiedSuperclass: String?
if let classDecl = declaration.as(ClassDeclSyntax.self) {
isSwiftClass = true
isJavaLangObject = classDecl.isJavaLangObject
// Retrieve the superclass, if there is one.
specifiedSuperclass = classDecl.inheritanceClause?.inheritedTypes.first?.trimmedDescription
} else {
isSwiftClass = false
isJavaLangObject = false
// Dig out the "extends" argument from the attribute.
if let superclassArg = arguments.dropFirst().first,
let superclassArgLabel = superclassArg.label,
superclassArgLabel.text == "extends",
let superclassMemberAccess = superclassArg.expression.as(MemberAccessExprSyntax.self),
superclassMemberAccess.declName.trimmedDescription == "self",
let superclassMemberBase = superclassMemberAccess.base
{
specifiedSuperclass = superclassMemberBase.trimmedDescription
} else {
specifiedSuperclass = nil
}
}
let superclass = specifiedSuperclass ?? "JavaObject"
// Check that the class name is fully-qualified, as it should be.
let className = classNameSegment.content.text
if className.firstIndex(of: ".") == nil {
throw MacroErrors.classNameNotFullyQualified(className)
}
var members: [DeclSyntax] = []
// Determine the modifiers to use for the fullJavaClassName member.
let fullJavaClassNameMemberModifiers: String
switch (isSwiftClass, isJavaLangObject) {
case (false, _):
fullJavaClassNameMemberModifiers = "static"
case (true, false):
fullJavaClassNameMemberModifiers = "override class"
case (true, true):
fullJavaClassNameMemberModifiers = "class"
}
let classNameAccessSpecifier = isSwiftClass ? "open" : "public"
members.append("""
/// The full Java class name for this Swift type.
\(raw: classNameAccessSpecifier) \(raw: fullJavaClassNameMemberModifiers) var fullJavaClassName: String {
#if os(Android)
AndroidSupport.androidDesugarClassNameConversion(for: "\(raw: className)")
#else
"\(raw: className)"
#endif
}
"""
)
// struct wrappers need a JavaSuperclass type.
if !isSwiftClass {
members.append("""
public typealias JavaSuperclass = \(raw: superclass)
"""
)
}
// If this is for a struct or is the root java.lang.Object class, we need
// a javaHolder instance property.
if !isSwiftClass || isJavaLangObject {
members.append("""
public var javaHolder: JavaObjectHolder
"""
)
}
let requiredModifierOpt = isSwiftClass ? "required " : ""
let initBody: CodeBlockItemSyntax = isSwiftClass && !isJavaLangObject
? "super.init(javaHolder: javaHolder)"
: "self.javaHolder = javaHolder"
members.append("""
public \(raw: requiredModifierOpt)init(javaHolder: JavaObjectHolder) {
\(initBody)
}
"""
)
if !isSwiftClass {
members.append("""
/// Casting to ``\(raw: superclass)`` will never be nil because ``\(raw: swiftName)`` extends it.
public func `as`(_: \(raw: superclass).Type) -> \(raw: superclass) {
return \(raw: superclass)(javaHolder: javaHolder)
}
"""
)
}
return members
}
}
extension JavaClassMacro: ExtensionMacro {
package static func expansion(
of node: AttributeSyntax,
attachedTo declaration: some DeclGroupSyntax,
providingExtensionsOf type: some TypeSyntaxProtocol,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [ExtensionDeclSyntax] {
if protocols.isEmpty {
return []
}
let AnyJavaObjectConformance: DeclSyntax =
"""
extension \(type.trimmed): AnyJavaObject { }
"""
return [AnyJavaObjectConformance.as(ExtensionDeclSyntax.self)!]
}
}
extension ClassDeclSyntax {
/// Whether this class describes java.lang.Object
var isJavaLangObject: Bool {
// FIXME: This is somewhat of a hack; we could look for
// @JavaClass("java.lang.Object") instead.
return name.text == "JavaObject"
}
}