Lexing and parsing
Quick answer
A lexer divides source text into tokens; a parser organizes tokens into a syntactic structure. A program can be tokenizable but still violate the grammar.
From characters to expressions
The compiler recognizes identifiers, literals and punctuation before determining how expressions fit together. Operator precedence means multiplication groups more tightly than addition. Parsing is not type checking: a syntactically valid expression can have incompatible operand types. The examples expose grammar behavior without claiming to reproduce rustc's internal token stream.
Expected stdout (not executed):
14 20Parentheses change the expression tree, not the meaning of individual number tokens.
Expected: compilation fails; exact diagnostic not verified.
The semicolon cannot serve as the right operand of addition.
Common mistake
Do not treat every compiler error as a parse error; first identify the stage and the primary diagnostic.
Try it yourself
Predict the result of 8 - 3 - 2 versus 8 - (3 - 2), then explain the grouping.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lexing and parsing — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
The expression `1 + true` has valid syntax. At which stage is the incompatible operation rejected?
Lexing and parsing — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { println!("{} {}", 2 + 3 * 4, (2 + 3) * 4); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Lexing and parsing — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let _ = 2 + ; } ``` Which outcome or interpretation best matches this example?