Skip to content
pwang00Public

About

Piet interpreter and retargetable compiler written in Rust using LLVM as a backend

Topics

Resources

Stars

19 stars

Watchers

2 watching

Forks

Repository files navigation

PietCC

CI License Rust Version

PietCC is a Rust interpreter and compiler for the Piet esoteric language using inkwell and LLVM as a backend / IR generator. To read more about the compiler, visit this writeup.

Organization

  1. piet_core: shared language types, control flow graph (CFG), execution state, and settings.
  2. frontend: converts Piet source rasters into CFGs through connected-component labeling and parsing, and infers codel size.
  3. interpreter: executes the CFG, with support for runtime interpretation and compile-time static evaluation.
  4. backend: workspace containing the compiler backend:
    • cfg_to_ir: lowers CFGs and static evaluation results to LLVM IR, runs LLVM optimization passes, and emits executables, LLVM IR, or bitcode.
    • optimizer: Piet optimization pass manager, analysis cache, and static evaluation pass.
  5. src: main CLI, image loading, and orchestration of the frontend, interpreter, and compiler pipelines.
  6. tests: shared test helpers and integration tests for the compiler and interpreter.
  7. images: sample Piet programs and test inputs.
  8. scripts: test runners and development utilities.

Dependencies

  • Rust 1.89+ (Stable, Beta, or Nightly), for inkwell
  • LLVM libraries, including clang and llc, for generating IR / lowering to assembly.

Features

  • Supports treating unknown colors as white / black.
  • Supports white block tracing and elimination
  • Supports nontermination detection for certain classes of programs
  • Supports running LLVM module optimization passes via inkwell
  • Supports static evaluation / constant folding optimizations at the CFG level

TODO

Compiler

  • Develop more Piet-specific optimizations and respective optimization passes

Installation

Clone this repository via

git clone https://github.com/pwang00/pietcc
cd pietcc

Building PietCC

To build PietCC, first make sure you have supported versions of rustc and LLVM on your system. This project uses inkwell 0.11.0 with LLVM 23.1. If selecting another LLVM version, update the feature in all three manifests: Cargo.toml, piet_core/Cargo.toml, and backend/cfg_to_ir/Cargo.toml.

inkwell = { version = "0.11.0", features = ["llvm23-1"] }

However, other versions are supported as well per the inkwell docs:

LLVM Version Cargo Feature Flag
12.0.x llvm12-0
13.0.x llvm13-0
14.0.x llvm14-0
15.0.x llvm15-0
16.0.x llvm16-0
17.0.x llvm17-0
18.1.x llvm18-1
19.1.x llvm19-1
20.1.x llvm20-1
21.1.x llvm21-1
22.1.x llvm22-1
23.1.x llvm23-1

Use exactly one LLVM feature consistently across all manifests. For LLVM 23 on Linux, configure both library discovery and the tools used to generate executables:

export LLVM_SYS_231_PREFIX=/usr/lib/llvm-23
export PATH="$LLVM_SYS_231_PREFIX/bin:$PATH"

On macOS, install llvm@23 with Homebrew and set LLVM_SYS_231_PREFIX to $(brew --prefix llvm@23), then prepend its bin directory to PATH. The libraries, llc, and clang should come from the same LLVM installation.

Once you have verified that the LLVM version is correct, run

cargo build --release
mv target/release/pietcc .

Alternatively, it is possible to combine the build / run workflow via

cargo run --release <image> <flags>, but this attempts to check for changes to the PietCC source on every run, so is not recommended.

Testing

PietCC includes comprehensive unit and integration tests.

Prerequisites

The test runner builds a pinned npiet revision with the compatibility patch in scripts/patches/npiet-modern-c.patch. The patched executable lives in target/npiet/bin; no system installation is needed. Install its build dependencies first:

Ubuntu/Debian:

sudo apt-get install build-essential git libgd-dev libpng-dev libgif-dev

macOS:

brew install gd libpng giflib
export CPPFLAGS="-I$(brew --prefix)/include"
export LDFLAGS="-L$(brew --prefix)/lib"

The patch fixes the signal handler signature and supports current giflib APIs. The first integration run requires network access to fetch the pinned source; subsequent runs reuse the build until the script, patch, or build settings change.

Running Tests

# Run all tests
./scripts/run_tests.sh

# Or prepare the reference interpreter for direct Cargo runs
./scripts/build_npiet.sh
export PATH="$PWD/target/npiet/bin:$PATH"
cargo test

For detailed information about the test infrastructure, writing tests, and CI/CD, see TESTING.md.

Interpreting Piet programs

PietCC provides several options for interpreting programs, as shown below.

USAGE:
    pietcc [OPTIONS] <input>

ARGS:
    <input>    Piet source file to interpret

OPTIONS:
...
    -i, --interpret                Interpret the given program
    -o, --output <out>             Output an executable into <file> [default: program.out]
    -s, --size <codel_size>        Interpret or compile with a supplied codel size (must divide
                                   program height and width)
    -v, --verbosity <verbosity>    Sets the interpreter's verbosity
    --ub                           Treats unknown pixels as black (default: error)
    --uw                           Treats unknown pixels as white (default: error)

PietCC will by default try to infer the codel width of the program. The heuristic used computes the gcd of all the block widths and heights with each other and the program width / height, and will produce a correct estimate of the codel width with high probability. However, to correctly interpret some programs, supplying the size flag with a corresponding value for the codel width is necessary.

The images/ directory contains a list of sample programs.

Here's an example run with fizzbuzz.png:

Piet FizzBuzz

./pietcc images/fizzbuzz.png -i -v 2

Running with codel width of 1 (size of 1)

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16

Doing cargo run --release images/fizzbuzz.png -i -v 2 will also work.

Compiling Piet programs

PietCC supports emitting executables, LLVM IR, and LLVM bitcode. The latter two options can be useful for targeting architectures other than x86_64. The relevant flags are shown below.

Piet compiler and interpreter

USAGE:
    pietcc [OPTIONS] <input>

ARGS:
    <input>    Piet source file to interpret

OPTIONS:
    -d, --default <use_default>    Interpret or compile with a codel size of 1
        --emit-llvm                Emit LLVM IR for a given Piet program
        --emit-llvm-bitcode        Emit LLVM bitcode for a given Piet program
    -h, --help                     Print help information
    -i, --interpret                Interpret the given program
    -o, --output <out>             Output an executable into <file> [default: program.out]
        --o1                       Sets the compiler optimization level to 1 (LLVM default<O1>, attempts
                                   Piet constant folding)
        --o2                       Sets the compiler optimization level to 2 (LLVM default<O2>, attempts
                                   Piet constant folding)
        --o3                       Sets the compiler optimization level to 3 (LLVM default<O3>,
                                   attempts Piet compile-time evaluation to fold constant programs)
    -s, --size <codel_size>        Interpret or compile with a supplied codel size (must divide
                                   program height and width)
        --ub                       Treats unknown pixels as black (default: error)
        --uw                       Treats unknown pixels as white (default: error)
    -v, --verbosity <verbosity>    Sets the interpreter or compiler's verbosity
    -w, --warn-nt                  Attempts to detect nontermination behavior in a Piet program
                                   during compilation

To compile a Piet program to an ELF executable, LLVM IR, and LLVM bitcode respectively, do

  • ./pietcc <image> -o <output>
  • ./pietcc <image> -o <output> --emit-llvm
  • ./pietcc <image> -o <output> --emit-llvm-bitcode

To specify an optimization level while compiling, do

./pietcc <image> --o[1|2|3] -o <output>

Without an optimization flag, PietCC skips Piet static evaluation and LLVM module optimization passes. Choose one of the following levels:

Flag LLVM pipeline Effect
--o1 default<O1> Basic LLVM optimizations with a lower optimization cost.
--o2 default<O2> More extensive LLVM optimizations for runtime performance.
--o3 default<O3> More aggressive LLVM optimizations, potentially increasing compile time and code size.

All three levels first attempt the same Piet compile-time evaluation, limited to 200,000 steps. If evaluation completes, the compiler emits the precomputed result; if it stops for input or reaches the step limit, compilation continues from the partially evaluated state. The levels differ in their LLVM pipeline, not in the Piet evaluation budget.

To specify behavior when encountering unknown pixels, do

./pietcc <image> --[ub|uw] -o <output>

and to enable warnings about nontermination, do

./pietcc <image> -w -o <output>

Terminating Piet programs

Here are some example terminating Piet program images with compilation logs:

Piet Pi Approximation

Piet Pi

$ ./pietcc images/piet_pi.png -o piet_pi
$ ./piet_pi 
31405


Stack empty

Hello World 1

Hello World with Codel Size 11

$ ./pietcc images/hw1-11.gif -o hw1-11
$ ./hw1-11 
Hello, world!
Stack empty

Piet Brainfuck Interpreter

Piet Brainfuck interpreter

Per the relevant section under piet samples

"The Piet program takes a Brainfuck program, and its input (seperated by |), from STDIN and prints the output of the Brainfuck program to STDOUT. E.g. the input ",+>,+>,+>,+.<.<.<.|sdhO" would generate the output 'Piet'"

$ ./pietcc images/piet_bfi.gif -o piet_bfi
$ ./piet_bfi 
Enter char: ,+>,+>,+>,+.<.<.<.|sdhO
Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Enter char: Piet
Stack (size 29): 18 0 7 18 80 0 105 0 101 0 116 44 43 62 44 43 62 44 43 62 44 43 46 60 46 60 46 60 46 

Piet text-based quest

Piet text-based quest

(This one takes a really long time to compile—upon profiling, I think it's because llc takes a long time to verify the input LLVM IR module.)

$ ./pietcc images/pietquest.png -o pietquest
$ ./pietquest
================
= Piet's Quest =
================


You find yourself in a rather dark studio.
There is an easel here.
There is a ladder leading down.

Please select:

1 - paint
2 - go down ladder
Enter char: 2
Enter char: 
You find yourself in a dusty, dim hallway.
There is a door to the kitchen here.
There is a door to the bedroom here.
There is a rickety loft ladder here.

Where do you want to go today?
1 - kitchen
2 - bedroom
3 - loft
Enter char: 1
Enter char: 

You find yourself in a well-stocked kitchen.
It smells invitingly of apple pancake.
Your wife is here.
She gives you a look.

Note that in all compilation examples, codel size inference is being done implicitly.

Nonterminating Piet programs

I believe that some programs on the piet samples page are a bit buggy, and a common mistake between these programs is nontermination. Since Piet is Turing-complete, reasoning about arbitrary Piet program termination is equivalent to solving the halting problem; however, it is possible to enumerate a class of Piet programs that never terminate—the programs whose CFG nodes all have outdegree greater than 0. This is explained here.

Here are a few examples of this class of nonterminating Piet programs; running PietCC with the -w or --warn-nt flag warns users accordingly.

Hello World 2

Buggy Hello World

$ ./pietcc images/hw2-11.gif --warn-nt -o hw2-11
pietcc: warning: every node in program CFG has nonzero outdegree.  This implies nontermination!

Hello World 5

Another Buggy Hello World

$ ./pietcc images/hw5.png --warn-nt -o hw5
pietcc: warning: every node in program CFG has nonzero outdegree.  This implies nontermination!

Generating a control flow graph from Piet LLVM IR

Visualizing a CFG from LLVM IR can be helpful. As an example, here's a program that simply pushes, pops, and duplicates stack values.

test2_upscaled.png

A sample program that does nothing

To generate the CFG for that program, we can do

$ ./pietcc images/test2.png -o test2 --emit-llvm
$ opt --dot-cfg test2.ll; dot .start.dot -Tpng > cfg.png

Which generates the CFG in PNG format.

Here's the relevant CFG for that program:

cfg_test.png

CFG for above program

About

Piet interpreter and retargetable compiler written in Rust using LLVM as a backend

Topics

Resources

Stars

19 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages