PeaBox Lab › PeaLang › Learn › Chapter 12 › Lesson 1

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:

1.1 The front-end pipeline

StageInputOutputTypical errors
LexerUTF-8 source textPositioned tokensUnterminated string, unexpected character
ParserToken streamSyntax treeUnexpected token, missing delimiter
Semantic analysisSyntax treeAnnotated tree and diagnosticsUndefined name, duplicate declaration, type mismatch
Back endChecked treeInterpreted execution or bytecodeCovered 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.

CheckExample it catches
Name resolutionReading subtotl when only subtotal exists
Duplicate declarationTwo let score declarations in one scope
Constant assignmentAssigning to a const binding
Return placementreturn outside a function
Loop control placementbreak outside a loop
Optional typesPassing 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

DiagnosticStage
Unterminated stringLexer
Expected "}" but found end of fileParser
Undefined variableSemantic analysis
Cannot assign to constantSemantic analysis or runtime
Division by zeroRuntime

1.14 Common mistakes

1.15 Guided practice

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

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

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.

← Previous Next →