Part III — Advanced Systems · Chapter 12 · Lesson 1 of 7 · 5 min read
Lesson 1: From Source Text to Tokens, Syntax Trees, and Semantic Checks
Lesson level: Advanced
Purpose: Follow a PeaLang program through the front end of the toolchain: lexing, parsing into a syntax tree, and semantic analysis before any code runs.
Release note: internal node names, diagnostic codes, and inspection commands in this lesson are illustrative. Verify them against your installed v0.63 release before relying on them.
Learning objectives
By the end of this lesson, you should be able to:
- Describe the stages of the PeaLang front end and what each produces.
- Trace a statement from characters to tokens to a syntax tree.
- Explain how precedence becomes tree shape.
- Describe what semantic checks add beyond parsing.
- Locate the stage responsible for a given diagnostic.
1.1 The front-end pipeline
| Stage | Input | Output | Typical errors |
|---|---|---|---|
| Lexer | UTF-8 source text | Positioned tokens | Unterminated string, unexpected character |
| Parser | Token stream | Syntax tree | Unexpected token, missing delimiter |
| Semantic analysis | Syntax tree | Annotated tree and diagnostics | Undefined name, duplicate declaration, type mismatch |
| Back end | Checked tree | Interpreted execution or bytecode | Covered in Lessons 2 to 5 |
Each stage trusts the previous one only for structure, not for meaning. A well-formed tree can still contain a reference to a name that does not exist.
1.2 Lexing revisited
Chapter 2 introduced tokens from a learner's point of view. Inside the toolchain, each token carries a kind, its text or value, and a source position. Later stages never re-read characters; they work only with tokens and positions.
let total = price * 2
LET "let" 1:1
IDENT "total" 1:5
ASSIGN "=" 1:11
IDENT "price" 1:13
STAR "*" 1:19
NUMBER 2 1:21
NEWLINE 1:22
1.3 Why positions matter
Every later diagnostic points back to a token position. Keeping positions on tree nodes is what lets the checker report rules.pea:7:14 rather than a vague message.
1.4 Parsing into a syntax tree
The parser groups tokens into nested nodes according to the grammar. Statements become declaration, assignment, print, if, while, function, and return nodes. Expressions become binary, unary, call, index, literal, and name nodes.
LetDecl name=total
Binary op=*
Name price
Number 2
1.5 Precedence becomes shape
The precedence table from Chapter 2 decides which operator sits higher in the tree. In a + b * c, multiplication binds tighter, so it becomes the child of addition.
Binary op=+
Name a
Binary op=*
Name b
Name c
Evaluation walks the tree from the leaves up, so tree shape fixes the order of operations without any further precedence logic.
1.6 Recursive descent
A common way to build such a parser is recursive descent: one function per grammar level, from lowest precedence (or) to highest (primary values). Each function calls the next-higher level for its operands. Treat this as a model for understanding the tree, not a claim about the exact internal code.
1.7 Error recovery
When the parser meets an unexpected token, it reports the problem and may skip ahead to a statement boundary, such as a newline or closing brace, so it can report further errors in one pass. Fix the first error first; later errors may be consequences.
1.8 Semantic analysis
Semantic analysis walks the syntax tree with a symbol table, the compile-time counterpart of the runtime environments from Chapter 2. It checks meaning that grammar cannot express.
| Check | Example it catches |
|---|---|
| Name resolution | Reading subtotl when only subtotal exists |
| Duplicate declaration | Two let score declarations in one scope |
| Constant assignment | Assigning to a const binding |
| Return placement | return outside a function |
| Loop control placement | break outside a loop |
| Optional types | Passing a string where an annotated integer is expected (Chapter 7) |
1.9 Scopes in the symbol table
The analyzer pushes a scope when it enters a block or function and pops it on exit, mirroring runtime lookup: nearest scope first, then outward. This lets it report an undefined name before the program ever runs.
1.10 Static checks versus runtime checks
Some failures can only be detected at runtime, such as division by a value that becomes zero or a missing map key that depends on input. The front end catches what is visible in the source; tests and runtime validation catch the rest.
1.11 Inspecting the front end
pea check rules.pea
pea tokens rules.pea
pea ast rules.pea
pea check was introduced in Chapter 1. The token and tree inspection commands are illustrative; confirm whether your release exposes them, or use the debugger and diagnostic output instead.
1.12 Worked example
Consider this fragment from the order_rules project:
const bulk_threshold = 10
function reason(qty) {
if qty >= bulk_threshhold {
return "BULK"
}
return "NONE"
}
Lexing succeeds: every character forms a valid token. Parsing succeeds: the function, if statement, and returns are well formed. Semantic analysis fails: bulk_threshhold is not declared in any enclosing scope. The diagnostic points to line 3 and may suggest bulk_threshold.
1.13 Mapping diagnostics to stages
| Diagnostic | Stage |
|---|---|
| Unterminated string | Lexer |
| Expected "}" but found end of file | Parser |
| Undefined variable | Semantic analysis |
| Cannot assign to constant | Semantic analysis or runtime |
| Division by zero | Runtime |
1.14 Common mistakes
- Fixing later errors first: parser recovery can produce follow-on errors.
- Assuming a clean parse means a correct program: semantic checks still apply.
- Expecting static checks to catch data-dependent failures: test and validate at runtime.
- Ignoring positions: they point to the exact token that failed.
1.15 Guided practice
- Write the token stream for if total > 100 { print "big" }.
- Draw the syntax tree for a or b and not c.
- Explain why let = 3 fails in the parser, not the lexer.
- Classify five diagnostics from earlier chapters by stage.
1.16 Hands-on lab
Take one module from the order_rules project. Introduce one lexical error, one parse error, and one semantic error in separate copies. Run the checker on each and record the message, position, and stage.
Deliverable: a table of the three defects with the diagnostic output and a hand-drawn or text syntax tree for one correct function.
1.17 Review questions
- What does each front-end stage produce?
- Why do tree nodes keep source positions?
- How does precedence determine tree shape?
- What does semantic analysis check that parsing cannot?
- Why can some errors only be found at runtime?
1.18 Applied challenge
Write a short design note for one new static check, such as warning on unused variables. State which stage runs it, what information it needs from the symbol table, and how it avoids false positives.
Lesson summary
- The front end turns text into tokens, tokens into a tree, and the tree into a checked structure.
- Precedence is encoded in tree shape.
- Semantic analysis uses scoped symbol tables to catch meaning errors early.
- Diagnostics map to stages, and the first error is the one to fix.
Transition to Lesson 2
With a checked tree in hand, the simplest way to run it is to walk it directly. Lesson 2 covers tree-walking interpretation.
Lesson status: Ready for review.