ToolSphere

Phases of a Compiler

Computer science

Trace an assignment through tokens, syntax and typed trees, int-to-float conversion, three-address code, constant optimization and abstract target code.

Type one assignment to follow it through the compiler stages.

t1 = rate * 60.0; t2 = initial + t1; position = t2

Copy walkthrough
Type settings — int means whole number, float allows fractions

Assumed types for this assignment

Names default to float in this teaching context. This input is one assignment, not a declaration parser. Float calculations use a finite JavaScript-number model; target code is illustrative.

1. Lexical analysis

LexemeClassAttribute
positionidentifiersymbol #1
=operatoroperator
initialidentifiersymbol #2
+operatoroperator
rateidentifiersymbol #3
*operatoroperator
60numberdecimal integer (text preserved)
;punctuationdelimiter or punctuation

2. Syntax analysis

Scroll inside the diagram to see all branches. Full labels are also available in the node tooltips.

=, position, +, initial, *, rate, 60==positionposition++initialinitial**raterate6060

3. Semantic analysis

Scroll inside the diagram to see all branches. Full labels are also available in the node tooltips.

+: float, initial: float, *: float, rate: float, int → float, 60: int+: float+: floatinitial: floatinitial: float*: float*: floatrate: floatrate: floatint → floatint → float60: int60: int
ExpressionTypeAction
(initial + (rate * inttofloat(60)))floatcheck operand types
initialfloatuse declared/default type
(rate * inttofloat(60))floatcheck operand types
ratefloatuse declared/default type
inttofloat(60)floatinsert int-to-float conversion
60intclassify literal

4. Intermediate code

t1 = inttofloat 60
t2 = rate * t1
t3 = initial + t2
position = t3

5. Constant optimization

t1 = rate * 60.0
t2 = initial + t1
position = t2
RuleBeforeAfter
fold constant int-to-float conversioninttofloat(60)60.0

6. Abstract target code

LDF R0, rate
MULF R1, R0, #60.0
LDF R2, initial
ADDF R3, R2, R1
STF position, R3

I/F suffixes distinguish integer/float operations. This is generated register-machine notation, not executable assembly for a real CPU.

On this browser only

Give feedback

Did this tool help?

Tell us what worked, what didn’t, or what you’d like next.

Opens Google Forms in a new tab with this tool’s name filled in. No sign-in or email required. Feedback is optional.

How to use Phases of a Compiler

  1. 1Start with the loaded position assignment, or enter one supported scalar assignment.
  2. 2Choose the assumed int or float type for each identifier; undeclared context defaults to float.
  3. 3Read the token stream, syntax tree and inserted conversions in phase order.
  4. 4Compare generated intermediate code with its constant-optimized form and target instructions.
  5. 5Copy the walkthrough, including its type assumptions, when checking a coursework answer.

About Phases of a Compiler

Follow one assignment through the compiler phases

This interactive walkthrough turns a scalar assignment into a token stream, syntax tree, typed expression tree, intermediate code, constant-optimized code and simple target instructions. The position-update example is loaded immediately, but the results are generated from the current input. Changing an identifier, operator, constant or assumed type changes the corresponding stages rather than leaving a fixed textbook picture on screen.

The tool is intended for introductory compiler-design coursework. It uses a small assignment language and an explicit int/float teaching context. It does not process a complete C translation unit, expand macros, resolve a scoped declaration environment, link libraries or create a native executable. Those boundaries keep each displayed representation inspectable while still showing why a later phase needs information from an earlier one.

Start with the lexical token stream

The first stage uses the site's lexical analyzer. It preserves each lexeme and shows its class and attribute, including symbol-name references for identifiers. The loaded assignment produces 8 tokens with its terminating semicolon included. Whitespace is skipped, and comments can be present without becoming arithmetic operands.

A lexical error stops this walkthrough before parsing. The error identifies its source position rather than inventing a plausible syntax tree. The standalone lexer accepts more literal spellings than the assignment parser, so this walkthrough explicitly limits numeric input to decimal integers and decimal-point literals. Exponents, suffixes and hexadecimal notation are outside this small expression language even when they are valid token shapes in the lexer.

Build the syntax tree from precedence

Syntax analysis uses the existing assignment and arithmetic parser. Multiplication, division and remainder bind more tightly than addition and subtraction. Parentheses change grouping, and unary minus creates its own operation node. The assignment's destination is separate from its expression subtree. The SVG tree is generated recursively, with full labels available in node titles when a long name needs a shortened display label.

The input must contain one scalar assignment. Declarations, calls, array expressions, branches and loops are not part of this walkthrough. A malformed expression clears the earlier results and reports the parser's error. For a wider intermediate-code exercise involving supported control flow, use the three-address code generator.

Supply the type context and inspect coercions

The type controls state the assumed type of each identifier. Names default to float to reproduce the familiar position-update example, but you can select int explicitly. These controls supply a teaching context; the tool does not infer a declaration from an assignment's spelling. They remain available when a type error occurs so you can correct the context without losing the program.

An integer literal starts as int and a decimal-point literal starts as float. A mixed arithmetic operation promotes its int operand to float. Assigning an int expression to a float destination can also add a conversion. The typed tree and semantic table show these inserted int-to-float nodes. A float expression assigned to an int destination is rejected instead of silently choosing a narrowing rule, and remainder requires int operands in this model.

The numerical model uses finite JavaScript-number calculations for float and exact safe-integer calculations for int. It is not a claim that a native language's float type has this width or that all target processors use identical rounding. Integer division truncates in the model. Invalid constant operations or values outside the stated finite/exact range produce readable errors.

Generate three-address intermediate code

Expression operations become temporaries, and the final instruction assigns the destination. Temporary names are chosen to avoid clobbering identifiers already present in the source. A conversion is an explicit intermediate operation before optimization, making the semantic decision visible in the next representation.

The loaded example generates:

t1 = inttofloat 60
t2 = rate * t1
t3 = initial + t2
position = t3

This sequence contains 4 instructions. The integer literal's conversion precedes its use in multiplication. The multiplication result then supplies an operand of addition, and the final copy updates the destination. Another compiler may choose different temporary names without changing the operation dependencies.

Fold constants without changing operation order

The optimization stage folds constant subtrees and constant conversions. It does not reassociate floating-point expressions or apply the separate integer optimizer's algebraic rules. In the default case, the conversion of the integer literal can be performed at compile time, yielding:

t1 = rate * 60.0
t2 = initial + t1
position = t2

The resulting sequence has 3 instructions. A change table identifies each folded expression or conversion and its replacement. If no constant subtree is available, the stage preserves the expression and explains that nothing was folded. This avoids presenting every input as though an optimization must always exist.

The regression interpreter evaluates both intermediate sequences. With initial = 10 and rate = 2 in the loaded example, position is 130 before and 130 after. Those values are computed by the library, not copied from a static illustration. Additional tests compare integer division, mixed arithmetic, parentheses, unary minus and temporary-name collisions.

Read the abstract target instructions

The final stage translates the optimized intermediate operations into a simple typed register-machine notation:

LDF R0, rate
MULF R1, R0, #60.0
LDF R2, initial
ADDF R3, R2, R1
STF position, R3

I and F suffixes distinguish integer and floating operations. Loads bring named values into registers, arithmetic consumes registers or immediate constants, and a store updates the assignment destination. Conversion uses an explicit integer-to-float instruction when it survives optimization. Register numbering is generated for readability; this stage does not model a fixed hardware register budget or perform production register allocation.

These instructions are illustrative target code, not assembly accepted by a particular processor or assembler. Instruction count is not an execution-time benchmark. The purpose is to connect an abstract operation with a possible low-level representation while retaining the type information that controls instruction selection.

Use the stage boundaries to explain an exam answer

Explain which representation each phase consumes and produces. Lexical analysis classifies spelling; syntax analysis determines grouping; semantic analysis applies the supplied type rules; intermediate generation makes dependencies explicit; optimization folds safe constants; target generation chooses typed operations. Symbol and type information support several stages rather than appearing only once and then disappearing.

The compiler lab links this walkthrough to parsing and intermediate-code tools. Copy walkthrough saves the source, type context, tokens and generated code stages as text. Keep the assumptions with the result so another reader can reproduce the same conversions and instruction choices.

Guides and tutorials

Frequently asked questions

Does this display change when I edit the assignment?

Yes. Tokens, trees, conversions, intermediate instructions and target code are generated from the current input. The example is a starting program, not a fixed diagram.

Why does the integer literal become float?

A mixed operation requires a common type in this model. When an int operand participates in a float operation, semantic analysis inserts an explicit conversion.

Where do identifier types come from?

The controls supply the assumed context for this assignment, with float as the default. The walkthrough does not parse a full declaration environment or infer scopes.

Can I enter several statements or a loop?

This page accepts one scalar assignment. Use the three-address code generator for its broader supported source syntax and control-flow examples.

Why can the lexer recognize a literal that this page rejects?

The lexer has a broader C-like token dialect than the assignment parser. This walkthrough documents its smaller decimal-literal expression language rather than silently misparsing another spelling.

What optimization is performed?

Constant subexpressions and constant int-to-float conversions are folded. Operation order is preserved, and general integer algebraic rewrites are not applied to floating expressions.

Are temporary names fixed?

They are generated and avoid names already used by the source. Equivalent intermediate code may use different temporary names while retaining the same dependencies.

Does float mean a native C float here?

No hardware width is promised. The walkthrough uses a finite JavaScript-number teaching model and labels its abstract operations as int or float.

Can the target code run on my computer?

It is illustrative register-machine notation. It is not emitted for a real processor, assembler, ABI or register budget.

How are the code stages checked?

Unit tests interpret the original and optimized intermediate sequences under the stated type model. They also check the textbook-style conversion example and malformed or unsupported input.

Have a suggestion for Phases of a Compiler?Share your feedback ↗