swift - 如何使用 SwiftSyntax 库递归迭代 Swift 语法?
问题描述
我想像这样在我的代码中迭代 Swift AST,找到 struct 关键字。
private func recursion(node: Syntax) -> String {
for child in node.children {
if let tokenKind = (child as? TokenSyntax)?.tokenKind, tokenKind == .structKeyword {
// if type(of: child) == StructDeclSyntax.self {
print ("yeah")
}
recursion(node: child)
}
}
let input = """
public struct cmd_deleteEdge<E: VEdge> : EdgeCommand {
public var keyEquivalent = KeyEquivalent.none
public let title = "Delete Edge"
public let id = "deleteEdge"
public let toolTip = "Delete selected Edge"
public let icon = Icon.delete
//receivers
public let edge: E
public init(edge: E) {
self.edge = edge
}
public func execute() throws -> ActionResult {
edge.deleteYourself()
return .success("deleted edge")
}
}
"""
public func convert(structText: String) throws -> String {
let sourceFile = try SyntaxParser.parse(source: structText)
let result = recursion(node: Syntax(sourceFile))
return result
}
try convert(structText: input)
它根本行不通,我从来没有达到“是的”(这意味着我在递归期间无法做任何有用的事情)。
我觉得这个库很混乱。有人会有一个很好的 UML 图来解释它是如何工作的吗?
在你告诉我之前,是的,我知道我可以使用访客,但我想自己了解它是如何工作的。
解决方案
我在反复试验和审查 API 后发现了它。
private func recursion(node: Syntax) -> String {
for child in node.children {
if let token = TokenSyntax(child), token.tokenKind == .structKeyword {
print ("yeah")
}
recursion(node: child)
}
return node.description
}
这种识别令牌种类的方法有效,并且将达到打印语句。同样,我确实想知道 SwiftSyntax 的类图会是什么样子。
推荐阅读
- azure - 无法更新 Web 应用设置:Web 工作人员的数量必须大于零
- java - 如何解决 spark-submit 错误:错误:加载类失败?
- python - 如何使用字典从嵌套 json 创建熊猫数据框
- json - Helm 为 nginx 模板转换数据
- sql - 如何将特定列数据插入到 bigquery 中的表中?
- opencart - 在 opnecart 中导出产品时获取完整的图像 URL
- python-xarray - 使用多个可能值按月拟合 xarray.DataArray
- video-indexer - 是否可以获得包含分析的视频的所有视频 ID 的列表?
- javascript - 为什么没有使用插入符号版本控制在 CI 中安装最新的可能版本
- python - 多列的分组