-
Notifications
You must be signed in to change notification settings - Fork 0
/
SyntaxProtocol+Extensions.swift
40 lines (35 loc) 路 1.48 KB
/
SyntaxProtocol+Extensions.swift
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
import SwiftSyntax
extension SyntaxProtocol {
/// for `struct`, `enum`, `class`, etc..
var shouldMakePublicInExtension: Bool {
guard
isDefinedInExtension(ofDeclModifierString: "private") == false,
isDefinedInExtension(ofDeclModifierString: "public") == false
else { return false }
return true
}
func findAncestorNode<T: SyntaxProtocol>(of targetNodeType: T.Type, baseNodeType: SyntaxProtocol.Type) -> T? {
var ancestor = parent
while let this = ancestor, this.is(baseNodeType.self) == false {
ancestor = ancestor?.parent
guard ancestor != nil else {
assertionFailure("鉂楋笍Unexpected AST tree. `\(type(of: baseNodeType))` must exist on ancestors.")
return nil
}
if let node = ancestor!.as(targetNodeType) {
return node
}
}
return nil
}
/// for `struct`, `enum`, `class`, etc..
private func isDefinedInExtension(ofDeclModifierString declModifierString: String) -> Bool {
precondition(["private", "public"].contains(declModifierString))
guard let extNode = findAncestorNode(of: ExtensionDeclSyntax.self, baseNodeType: CodeBlockItemSyntax.self) else { return false }
let modifiers = Array(extNode.modifiers)
if modifiers.count == 1, modifiers[0].name.text == declModifierString {
return true
}
return false
}
}