forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwiftSyntax+Extensions.swift
More file actions
245 lines (229 loc) · 7.16 KB
/
SwiftSyntax+Extensions.swift
File metadata and controls
245 lines (229 loc) · 7.16 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//===----------------------------------------------------------------------===//
//
// 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 SwiftDiagnostics
import SwiftSyntax
extension WithModifiersSyntax {
var accessControlModifiers: DeclModifierListSyntax {
modifiers.filter { modifier in
modifier.isAccessControl
}
}
}
extension ImplicitlyUnwrappedOptionalTypeSyntax {
var asOptionalTypeSyntax: any TypeSyntaxProtocol {
OptionalTypeSyntax(
leadingTrivia: leadingTrivia,
unexpectedBeforeWrappedType,
wrappedType: wrappedType,
self.unexpectedBetweenWrappedTypeAndExclamationMark,
self.unexpectedAfterExclamationMark,
trailingTrivia: self.trailingTrivia
)
}
}
extension DeclModifierSyntax {
var isAccessControl: Bool {
switch self.name.tokenKind {
case .keyword(.private), .keyword(.fileprivate), .keyword(.internal), .keyword(.package),
.keyword(.public), .keyword(.open):
return true
default:
return false
}
}
}
extension DeclModifierSyntax {
var isPublic: Bool {
switch self.name.tokenKind {
case .keyword(.private): return false
case .keyword(.fileprivate): return false
case .keyword(.internal): return false
case .keyword(.package): return false
case .keyword(.public): return true
case .keyword(.open): return true
default: return false
}
}
}
extension WithModifiersSyntax {
var isPublic: Bool {
self.modifiers.contains { modifier in
modifier.isPublic
}
}
}
extension AttributeListSyntax.Element {
/// Whether this node has `JavaKit` attributes.
var isJava: Bool {
guard case let .attribute(attr) = self else {
// FIXME: Handle #if.
return false
}
let attrName = attr.attributeName.description
switch attrName {
case "JavaClass", "JavaInterface", "JavaField", "JavaStaticField", "JavaMethod", "JavaStaticMethod", "JavaImplementation":
return true
default:
return false
}
}
}
extension DeclSyntaxProtocol {
/// Find inner most "decl" node in ancestors.
var ancestorDecl: DeclSyntax? {
var node: Syntax = Syntax(self)
while let parent = node.parent {
if let decl = parent.as(DeclSyntax.self) {
return decl
}
node = parent
}
return nil
}
/// Declaration name primarily for debugging.
var nameForDebug: String {
return switch DeclSyntax(self).as(DeclSyntaxEnum.self) {
case .accessorDecl(let node):
node.accessorSpecifier.text
case .actorDecl(let node):
node.name.text
case .associatedTypeDecl(let node):
node.name.text
case .classDecl(let node):
node.name.text
case .deinitializerDecl(_):
"deinit"
case .editorPlaceholderDecl:
""
case .enumCaseDecl(let node):
// FIXME: Handle multiple elements.
if let element = node.elements.first {
element.name.text
} else {
"case"
}
case .enumDecl(let node):
node.name.text
case .extensionDecl(let node):
node.extendedType.description
case .functionDecl(let node):
node.name.text + "(" + node.signature.parameterClause.parameters.map({ $0.firstName.text + ":" }).joined() + ")"
case .ifConfigDecl(_):
"#if"
case .importDecl(_):
"import"
case .initializerDecl(let node):
"init" + "(" + node.signature.parameterClause.parameters.map({ $0.firstName.text + ":" }).joined() + ")"
case .macroDecl(let node):
node.name.text
case .macroExpansionDecl(let node):
"#" + node.macroName.trimmedDescription
case .missingDecl(_):
"(missing)"
case .operatorDecl(let node):
node.name.text
case .poundSourceLocation(_):
"#sourceLocation"
case .precedenceGroupDecl(let node):
node.name.text
case .protocolDecl(let node):
node.name.text
case .structDecl(let node):
node.name.text
case .subscriptDecl(let node):
"subscript" + "(" + node.parameterClause.parameters.map({ $0.firstName.text + ":" }).joined() + ")"
case .typeAliasDecl(let node):
node.name.text
case .variableDecl(let node):
// FIXME: Handle multiple variables.
if let element = node.bindings.first {
element.pattern.trimmedDescription
} else {
"var"
}
}
}
/// Qualified declaration name primarily for debugging.
var qualifiedNameForDebug: String {
if let parent = ancestorDecl {
parent.qualifiedNameForDebug + "." + nameForDebug
} else {
nameForDebug
}
}
/// Signature part of the declaration. I.e. without body or member block.
var signatureString: String {
return switch DeclSyntax(self.detached).as(DeclSyntaxEnum.self) {
case .functionDecl(let node):
node.with(\.body, nil).triviaSanitizedDescription
case .initializerDecl(let node):
node.with(\.body, nil).triviaSanitizedDescription
case .classDecl(let node):
node.with(\.memberBlock, "").triviaSanitizedDescription
case .structDecl(let node):
node.with(\.memberBlock, "").triviaSanitizedDescription
case .protocolDecl(let node):
node.with(\.memberBlock, "").triviaSanitizedDescription
case .accessorDecl(let node):
node.with(\.body, nil).triviaSanitizedDescription
case .subscriptDecl(let node):
node.with(\.accessorBlock, nil).triviaSanitizedDescription
case .variableDecl(let node):
node
.with(\.bindings, PatternBindingListSyntax(
node.bindings.map {
$0.detached
.with(\.accessorBlock, nil)
.with(\.initializer, nil)
}
))
.triviaSanitizedDescription
default:
fatalError("unimplemented \(self.kind)")
}
}
/// Syntax text but without unnecessary trivia.
///
/// Connective trivia are condensed into a single whitespace, but no space
/// after opening or before closing parentheses
var triviaSanitizedDescription: String {
let visitor = TriviaSanitizingDescriptionVisitor(viewMode: .sourceAccurate)
visitor.walk(self.trimmed)
return visitor.result
}
}
class TriviaSanitizingDescriptionVisitor: SyntaxVisitor {
var result: String = ""
var prevTokenKind: TokenKind = .endOfFile
var prevHadTrailingSpace: Bool = false
override func visit(_ node: TokenSyntax) -> SyntaxVisitorContinueKind {
let tokenKind = node.tokenKind
switch (prevTokenKind, tokenKind) {
case
// No whitespace after open parentheses.
(.leftAngle, _), (.leftParen, _), (.leftSquare, _), (.endOfFile, _),
// No whitespace before close parentheses.
(_, .rightAngle), (_, .rightParen), (_, .rightSquare):
break
default:
if prevHadTrailingSpace || !node.leadingTrivia.isEmpty {
result += " "
}
}
result += node.text
prevTokenKind = tokenKind
prevHadTrailingSpace = !node.trailingTrivia.isEmpty
return .skipChildren
}
}