picol: A Tcl interpreter in 500 lines of code
Source: Hacker News
Picol is a Tcl‑alike interpreter written in about 500 lines of C (the parser alone is roughly 250 lines). It was first released on 15 March 2007 and has been archived on GitHub together with the main points of the original article.
Rules
When I built this code I kept a few goals in mind:
- Use a normal C coding style, with familiar spacing and comments.
- Design the interpreter similarly to a real Tcl implementation, making it a useful learning example for anyone new to writing interpreters.
- Ensure the interpreter can run non‑trivial programs—not just a simple “set a variable and print hello world”.
The resulting interpreter: Picol
The parser is very close to Tcl’s, and Picol supports interpolation:
set a "pu"
set b {ts}
$a$b "Hello World!"
Picol provides an interactive shell; just run the executable without arguments.
Compilation
gcc -O2 -Wall -o picol picol.c
Running a script
picol filename.tcl
Supported features
- String interpolation (e.g.,
"2+2 = [+ 2 2]"or"My name is: $foobar"). - Procedures with
return; ifreturnis omitted, the result of the last command is used. - Control structures:
if,if … else …,while(withbreakandcontinue). - Recursion.
- Proper variable scoping via call frames, just like Tcl.
- Built‑in commands:
set, arithmetic operators (+,-,*,/), comparison operators (==,!=,>,=).
“Inside every large program there is a small program trying to get out.” – Sir Tony Hoare