AST(Abstract Syntax Tree)

7과11사이·2024년 2월 8일
0
post-custom-banner

As I tried to learn more about Macros and try to deep dive into it, I've came across a word never mentioned by anyone.

AST

Abbreviated from Abstract Syntax Tree,
it seemed like a pretty important piece of information.
Therefore, I'd take a minute to write down what I've learned.

AST is what and the hows a compiler uses to try and understand what our code imply.


Initially, we write the code which are called 'source code'.
They are broken into smaller pieces of what's called token through lexical analysis (Whatever this is)

Then the broken down pieces of token are then parsed into a tree - the Syntax Tree through what's known as 'Parser'.


Lexical Analysis

Similar to how we TRY and interpret a foreign language - or a sentence, we break up the sentence into pieces. Most notably, noun, verbs and any other words.
This is what Lexical Analysis does.

When we write the source code, the compiler works and tries to figure out the different types of nouns, verbs, words - or also named as tokens, within the source code.

So when I write a piece of code in an IDE, the compiler tries to understand each words or tokens by breaking the pieces.

struct VideoGame {
	var name: String
    var releaseDate: Date
    var price: Int
    var publisher: String
}

let tekken = VideoGame(name: "Tekken", releaseDate: 24/01/26, price: 70000, publisher: "Bandai")

In the given example, we can say the compiler is breaking up each individual piece of 'words' written and identifying its origin.
"struct, String, Date, Int" would be considered a type
"name", "releaseDate", "price", "publisher" would be considered the name and so on.

Syntactic Analysis

After tokenization, to fully understand the information, we need to parse the relationship between the words. How they fit and work together. Which would form the language's grammar so to speak.

Thus, the syntax analysis or parsing occurs.
To achieve this 'parsing' the parser runs the written code into a tree, the previously mentioned AST.

so... again! AST

The AST concretes the relationship in between code.
Giving the code a deeper meaning.
A tree that has nodes which holds children.
Therefore, each node containing information of individual tokens and related data.

The article claims if node presents a function call,
the argument and the return values are the associated values.

post-custom-banner

0개의 댓글