|
| 1 | +# AST Generation |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +After ANTLR parses the source file it produces a **Parse Tree** whose nodes are ANTLR `Context` objects. `ASTGenerationSTVisitor` traverses this Parse Tree and converts it into a typed **Abstract Syntax Tree (AST)** built from the static inner classes defined in `AST.java`. |
| 6 | + |
| 7 | +## AST Node Hierarchy |
| 8 | + |
| 9 | +All nodes extend the abstract `Node` interface. Each concrete node carries the children and data that are relevant for later phases: |
| 10 | + |
| 11 | +| Node | Description | |
| 12 | +|---|---| |
| 13 | +| `ProgLetInNode` | Top-level `let … in` program | |
| 14 | +| `ProgNode` | Top-level expression-only program | |
| 15 | +| `ClassNode` | Class declaration (fields + methods) | |
| 16 | +| `FieldNode` | A class field (like a parameter) | |
| 17 | +| `MethodNode` | A class method (like a function) | |
| 18 | +| `FunNode` | Function declaration | |
| 19 | +| `ParNode` | Function parameter | |
| 20 | +| `VarNode` | Variable declaration | |
| 21 | +| `IdNode` | Identifier use | |
| 22 | +| `CallNode` | Function call | |
| 23 | +| `ClassCallNode` | Method call (`obj.method(...)`) | |
| 24 | +| `NewNode` | Object instantiation (`new C(...)`) | |
| 25 | +| `EmptyNode` | `null` literal | |
| 26 | +| `PlusNode` / `MinusNode` | Addition / subtraction | |
| 27 | +| `TimesNode` / `DivNode` | Multiplication / division | |
| 28 | +| `EqualNode` / `GreaterEqualNode` / `LessEqualNode` | Comparison | |
| 29 | +| `AndNode` / `OrNode` / `NotNode` | Logical operators | |
| 30 | +| `IfNode` | `if / then / else` | |
| 31 | +| `PrintNode` | `print(exp)` | |
| 32 | +| `IntNode` | Integer literal | |
| 33 | +| `BoolNode` | Boolean literal | |
| 34 | + |
| 35 | +## Type Nodes |
| 36 | + |
| 37 | +Type information is represented separately as `TypeNode` subtypes that appear in symbol-table entries: |
| 38 | + |
| 39 | +| Type Node | Meaning | |
| 40 | +|---|---| |
| 41 | +| `IntTypeNode` | `int` | |
| 42 | +| `BoolTypeNode` | `bool` | |
| 43 | +| `RefTypeNode` | Reference to a class | |
| 44 | +| `EmptyTypeNode` | Type of `null` | |
| 45 | +| `ArrowTypeNode` | Function type (only in STentry) | |
| 46 | +| `MethodTypeNode` | Method type (only in STentry) | |
| 47 | +| `ClassTypeNode` | Class type (maps field/method indices to types) | |
| 48 | + |
| 49 | +## Accept–Visit Cycle |
| 50 | + |
| 51 | +The visitor pattern uses a two-step dispatch: |
| 52 | + |
| 53 | +1. The visitor calls `visit(node)` → delegates to `node.accept(this)`. |
| 54 | +2. The node calls `visitor.visitNode(this)` passing its specific type. |
| 55 | + |
| 56 | +This double dispatch allows the visitor to select the correct `visitNode` overload at runtime without explicit casts. |
0 commit comments