As a 2-year iOS developer, I just learned about AST recently…

AST application in iOS

1. Check the code syntax, check the code style, format the code, highlight the code, error prompt the code, and complete the code automatically

The parser generates an abstract syntax tree (AST). After that, the semantic parser does its work and generates an AST that passes type-checking, relying on SwiftSyntax (developed based on the libSyntax library)

How do I generate an AST?

1. Command line

Write a swift_func. Swift file as follows:

var a = 1
func add(b: Int) -> Int {
    return a + b
}
Copy the code

CD Run the command to the current directory

xcrun swiftc -frontend -emit-syntax swift_func.swif

The result is a string of AST in JSON format

"kind": "CodeBlockItemList"."layout": [{"kind": "CodeBlockItem"."layout": [{"kind": "VariableDecl"."layout": [
                                null,
                                null,
                                {
                                    "leadingTrivia": []."presence": "Present"."tokenKind": {
                                        "kind": "kw_var"
                                    },
                                    "trailingTrivia": [{"kind": "Space"."value": 1}]}, {"kind": "PatternBindingList"."layout": [{"kind": "PatternBinding"."layout": [{"kind": "IdentifierPattern"."layout": [{"leadingTrivia": []."presence": "Present"."tokenKind": {
                                                                "kind": "identifier"."text": "a"
                                                            },
                                                            "trailingTrivia": [{"kind": "Space"."value": 1}]}],Copy the code

Reworking its AST structure a bit, it’s much more complex than JavaScript’s AST

2, SwiftSyntax

SwiftSyntax is used to generate an AST: github.com/ChengRuipen…

swift build

Wait for compilation to complete and execute

.build/debug/swift-ast-generator swift_func.swift

A JOsn file is generated under the directory, which is the corresponding AST

What can we do with AST?

1. Rewrite Swift code

There is an example in SwiftSyntax that shows how to write a program that iterates over integers in a source file and increments their value by 1

2. Highlight code

Can AST be compiled to Swift?

Leon… After studying for 2 days, I still haven’t found the method to compile back to Swift.