Swift 编译器:使用 3rd 方导入打印 Swift 文件的 AST

odl*_*dlp 5 abstract-syntax-tree ios swift

我正在尝试使用带有标志的 Swift 编译器从 Swift 文件中打印抽象语法树 (AST)-print-ast。这是没有 Xcode & 的xcodebuild

我一直在处理通过 Carthage 构建的 3rd 方框架的导入。给定一个包含以下代码的源文件:

来源

import Foundation
import BrightFutures // 3rd party framework

class MyAsyncService {
    func asyncFunc() -> Future<String, NSError> {
        return Promise<String, NSError>().future
    }
}
Run Code Online (Sandbox Code Playgroud)

为 MacOS 编译工作

通过指定框架搜索路径 ( -F) 以下命令:

swiftc -print-ast Source.swift -F Carthage/Build/Mac
Run Code Online (Sandbox Code Playgroud)

产生预期的输出:

import Foundation
import BrightFutures

internal class MyAsyncService {
  internal func asyncFunc() -> Future<String, NSError>
  @objc deinit
  internal init()
}
Run Code Online (Sandbox Code Playgroud)

为iOS编译?

我需要为仅针对 iOS 的项目打印 AST,并为 iOS 构建依赖项。

当我尝试指向为 iOS 构建的框架时:

swiftc -print-ast Source.swift -F Carthage/Build/iOS
Run Code Online (Sandbox Code Playgroud)

命令失败:

Source.swift:2:12: error: module file was created for incompatible target x86_64-apple-ios8.0: [...]/Carthage/Build/iOS/BrightFutures.framework/Modules/BrightFutures.swiftmodule/x86_64.swiftmodule
    import BrightFutures // 3rd party framework
           ^
import Foundation
import BrightFutures

internal class MyAsyncService {
  internal func asyncFunc() -> <<error type>>
  @objc deinit
  internal init()
}
Run Code Online (Sandbox Code Playgroud)

我也试过尝试添加-sdk标志:

-sdk $(xcrun --sdk iphoneos --show-sdk-path)指定的iPhoneOS SDK,但这吐出有关不支持的架构错误。

我怎样才能得到这个建立?

odl*_*dlp 5

看起来使用 Swift 编译器打印 AST 的替代方法是使用SourceKit

有一个名为SourceKitten的 CLI 工具,它允许您将 Swift 源文件的结构解析为 JSON 格式,而无需处理第 3 方框架和其他源文件的导入。