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.
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.
- The compiler reads the text and finds its shape. The result is a tree.
- The compiler finds, for each name, where that name was defined.
- The compiler finds the type of each part of the program.
- The compiler writes the program again in a small language where nothing is implicit.
- 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.