Play n Tools

Free tools & games for everyone

Free · No sign-up · No accounts

Compiler explorer

See a tiny language compiled stage by stage: tokens, syntax tree, stack machine code with constant folding, then run it and see the output.

1. Tokens

2. Syntax tree

3. Stack machine code

4. Output

How to use

  1. Write a program or load an example. The language has whole numbers, variables (total = 3;), + - * / % and brackets, comparisons (< > <= >= == !=, which give 1 or 0), print expression;, if condition { ... } else { ... } and while condition { ... }. A # starts a note.
  2. Press Compile and run. You see the four stages side by side: the tokens the scanner found, the syntax tree the parser built, the instructions the code generator wrote, and what the program printed.
  3. Untick Fold constants to see the code without that optimisation, and compare the number of instructions.

Keyboard and touch

TabMove between the menu, the program box and the button (inside the box, Tab moves on rather than typing a tab)
EnterOn the button: compile and run

Tips

  • Look at the tree for 2 + 3 * 4: the multiplication sits lower, so it is worked out first. That is all precedence means.
  • A stack machine needs no registers: operands go on the stack and each operation takes them off and puts the result back. Many real virtual machines work this way.
  • A while loop becomes a label, a test, a jump out when false, the body, and a jump back to the label.
  • Division keeps whole numbers and rounds toward zero, as in C and Java: 7 / 2 is 3 and -7 % 3 is -1.

About this tool

The scanner is a single pattern loop; the parser is a hand-written recursive descent parser with one function per precedence level, the way many real compilers start. The code generator walks the tree and writes stack instructions (PUSH, LOAD, STORE, ADD ... NE, NEG, JMP, JZ, PRINT, HALT); constant folding works out any part of an expression made only of numbers before code is written. Numbers are 32-bit whole numbers that wrap around. A program may run at most 200,000 steps and print 1,000 lines.

The language is a small teaching language, not a real one. Everything runs in your browser.

See you tomorrow!

A fresh daily puzzle every morning, and new tools added every month.

Browse every product