Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift compiler: Printing the AST of a Swift file with 3rd party imports

I'm trying to print the Abstract Syntax Tree (AST) from a Swift file using the Swift compiler with the -print-ast flag. This is without Xcode & xcodebuild.

I'm stuck handling imports of 3rd party frameworks, built via Carthage. Given a source file with the following code:

Source

import Foundation
import BrightFutures // 3rd party framework

class MyAsyncService {
    func asyncFunc() -> Future<String, NSError> {
        return Promise<String, NSError>().future
    }
}

Compiling for MacOS works

By specifying the framework search path (-F) the following command:

swiftc -print-ast Source.swift -F Carthage/Build/Mac

Produces the expected output:

import Foundation
import BrightFutures

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

Compiling for iOS?

I need to print the AST for a project only targeting iOS, with dependencies built for iOS.

When I try pointing to the frameworks built for iOS:

swiftc -print-ast Source.swift -F Carthage/Build/iOS

The command fails:

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()
}

I've tried also tried adding the -sdk flag:

-sdk $(xcrun --sdk iphoneos --show-sdk-path) to specify the iphoneos SDK, but this spits out an error about unsupported architectures.

How can I get this to build?

like image 723
odlp Avatar asked Mar 19 '16 13:03

odlp


1 Answers

Looks like an alternative to printing the AST with the Swift compiler is to use SourceKit.

There's a CLI tool called SourceKitten which allows you to parse the structure of a Swift source file into JSON format, without needing to handle imports of 3rd party frameworks and other source files.

like image 191
odlp Avatar answered Oct 01 '22 09:10

odlp