CodeBlanks Logo Icon CodeBlanks

AST

Learn the Abstract Syntax Tree (AST) structure.

AST

The AST (Abstract Syntax Tree) is the tree the compiler builds after parsing the source code. Each node represents a syntax unit (expression, statement, declaration).

Example: a + b * c becomes a BinaryExpr tree; on the left is a, on the right another BinaryExpr (b * c). This structure lets the compiler process the meaning (type checking, optimization). The AST is an internal representation independent of the source.

AST nodes

Common AST node types are: Expr (expression — a value-producing unit), Stmt (statement — a side-effect unit), BinaryExpr (a two-operand operation), Literal (a constant value), VarDecl (a variable declaration).

The compiler uses the AST in three ways: checking (type checking, scope analysis), optimization (constant folding, dead code elimination) and code generation (from AST to assembly). These synchronized phases turn the source into an executable.

Practice Write the Expr struct

Write struct Expr { int value; };. In main define Expr e{42}; and write std::cout << e.value;.

Starter code

main.cpp
#include <iostream>

// Define the Expr struct here

int main() {
    // Create an Expr instance and print its value
    return 0;
}

Sample solution

main.cpp
#include <iostream>

struct Expr {
    int value;
};

int main() {
    Expr e{42};
    std::cout << e.value;
    return 0;
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the AST struct

Question
struct BinaryExpr { Expr* left; Expr* right; std::string op; ____;
Answer
struct BinaryExpr { Expr* left; Expr* right; std::string op; };

Explanation: A struct definition ends with }.

2 What does an AST node represent?

main.cpp
struct Expr { int value; };
  • A machine instruction
  • A syntax unit (expression, statement) Correct answer
  • A memory cell
  • A file

Explanation: Each AST node represents a syntax unit.

3 Match each node to its role

Term Meaning
Expr node Expression node
Stmt node Statement node
BinaryExpr Two-operand operation
Literal Constant value

All lessons in Expert