Skip to content

Chapter 1

Help! My Haskell Became Machine Code

A compiler is a program that reads a program. It reads text that a person wrote, and it writes a program that a machine can run. This chapter gives the full journey in one picture. The next chapters look at each step.

TEXT double x = x + x TREE define double + x x PROGRAM func $double local.get 0 local.get 0 i64.add end The next chapter is about the first arrow. The second arrow takes the rest of the book.

The journey

A machine does not understand Haskell. It understands small instructions: get a value, add two values, jump to a different instruction. The compiler changes your Haskell into these instructions. It does this in a sequence of steps, and each step does one job.

  1. The compiler reads the text and finds its shape. The result is a tree.
  2. The compiler finds, for each name, where that name was defined.
  3. The compiler finds the type of each part of the program.
  4. The compiler writes the program again in a small language where nothing is implicit.
  5. The compiler writes the instructions that the machine runs.

Each chapter of this guide is about one of these steps.

Run a program

Here is the full compiler. Change the Haskell module on the left. Select Run to compile it and see its output on the right. Select Stop to stop the program.

module Main where

main :: IO ()
main = putStrLn "Hello, compiler!"

The module must have the name Main and a main function. You can use the Prelude. The browser compiles the module and runs the WASI P3 program. The first run must load the compiler tools and the libraries.

Try this

  • Change the text in the quotes. Then select Run again.
  • Write main = print (sum [1 .. 100]). The program adds the numbers from 1 to 100.
  • Write main = putStrLn 42. A number is not a string, and the compiler tells you.

Next chapterFrom text to tree