Search code examples
compilation

How can a compiler compile itself?


I am researching CoffeeScript on the website http://coffeescript.org/, and it has the text

The CoffeeScript compiler is itself written in CoffeeScript

How can a compiler compile itself, or what does this statement mean?


Solution

  • The first edition of a compiler can't be machine-generated from a programming language specific to it; your confusion is understandable. A later version of the compiler with more language features (with source rewritten in the first version of the new language) could be built by the first compiler. That version could then compile the next compiler, and so on. Here's an example:

    1. The first CoffeeScript compiler is written in Ruby, producing version 1 of CoffeeScript
    2. The source code of the CS compiler is rewritten in CoffeeScript 1
    3. The original CS compiler compiles the new code (written in CS 1) into version 2 of the compiler
    4. Changes are made to the compiler source code to add new language features
    5. The second CS compiler (the first one written in CS) compiles the revised new source code into version 3 of the compiler
    6. Repeat steps 4 and 5 for each iteration

    Note: I'm not sure exactly how CoffeeScript versions are numbered, that was just an example.

    This process is usually called bootstrapping. Another example of a bootstrapping compiler is rustc, the compiler for the Rust language.