首页 > 解决方案 > 如何使用 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 图来解释它是如何工作的吗?

在你告诉我之前,是的,我知道我可以使用访客,但我想自己了解它是如何工作的。

标签: swiftabstract-syntax-tree

解决方案


我在反复试验和审查 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 的类图会是什么样子。


推荐阅读