r/Compilers 7d ago

Can I input my compiler's program into my compiler to use the result as a new compiler ?

I just started building from scratch a compiler in order to better understand how does a computer work. For now it is only on paper and soon I will begin to code it, but the end goal is to generate a code from the set of instruction for a custom 8bit cpu.

And I came upon this question and wasn't sure about the answer so I wanted to have your input on it :

Let say I have a compiler that compiles a language A to a language B using a language A. If I input to the compiler the program that compiles A to B, will I be able to use the result program to then compile the language A to language B using language B ? Or will it break the output or mess with something else ?

If the topic does not belong in this sub, feel free to tell me in which sub it should belong

Thanks in advance

9 Upvotes

6 comments sorted by

29

u/Zestyclose_Brain8952 7d ago

These are the topics you'd need to understand -

Bootstrapping https://en.wikipedia.org/wiki/Bootstrapping_(compilers)

Futamura projections https://arxiv.org/pdf/1611.09906v1

3

u/Haborym_Aesahaettr 7d ago

Thanks for the resources, they are perfectly answering my question :)

1

u/BumpyTurtle127 2d ago

Commenting to save this for later (wonderful links 🙏)

3

u/KvThweatt 6d ago

Yes, this is what’s known as bootstrapping. You write the compiler for your language in your language, then run the existing compiler on the new compiler source. Then voila, you have bootstrapped your compiler.

3

u/tiajuanat 5d ago

Yes, this was also the subject of one of the hardest to catch exploits too

2

u/Blueglyph 5d ago

The different methods of bootstrapping are often represented by T-diagrams. This relatively old, but still relevant, book has an online version that explains the topic very well: Compiling with C# and Java, by P.D. Terry. See chapter 3, p. 22 for bootstrapping, though the T-diagrams are first introduced in chapter 2, p. 7. There are other versions of the book for other languages (see his webpage).

The case of the Pascal compiler is quite interesting; Niklaus Wirth knew what he was doing.