Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do functional language compilers work? [duplicate]

I've heard of the idea of bootstrapping a language, that is, writing a compiler/interpreter for the language in itself. I was wondering how this could be accomplished and looked around a bit, and saw someone say that it could only be done by either

  • writing an initial compiler in a different language.
  • hand-coding an initial compiler in Assembly, which seems like a special case of the first

To me, neither of these seem to actually be bootstrapping a language in the sense that they both require outside support. Is there a way to actually write a compiler in its own language?

like image 254
pbh101 Avatar asked Nov 24 '22 02:11

pbh101


2 Answers

Is there a way to actually write a compiler in its own language?

You have to have some existing language to write your new compiler in. If you were writing a new, say, C++ compiler, you would just write it in C++ and compile it with an existing compiler first. On the other hand, if you were creating a compiler for a new language, let's call it Yazzleof, you would need to write the new compiler in another language first. Generally, this would be another programming language, but it doesn't have to be. It can be assembly, or if necessary, machine code.

If you were going to bootstrap a compiler for Yazzleof, you generally wouldn't write a compiler for the full language initially. Instead you would write a compiler for Yazzle-lite, the smallest possible subset of the Yazzleof (well, a pretty small subset at least). Then in Yazzle-lite, you would write a compiler for the full language. (Obviously this can occur iteratively instead of in one jump.) Because Yazzle-lite is a proper subset of Yazzleof, you now have a compiler which can compile itself.

There is a really good writeup about bootstrapping a compiler from the lowest possible level (which on a modern machine is basically a hex editor), titled Bootstrapping a simple compiler from nothing. It can be found at https://web.archive.org/web/20061108010907/http://www.rano.org/bcompiler.html.

like image 155
Derek Park Avatar answered Dec 28 '22 10:12

Derek Park


The explanation you've read is correct. There's a discussion of this in Compilers: Principles, Techniques, and Tools (the Dragon Book):

  • Write a compiler C1 for language X in language Y
  • Use the compiler C1 to write compiler C2 for language X in language X
  • Now C2 is a fully self hosting environment.
like image 27
Mark Harrison Avatar answered Dec 28 '22 10:12

Mark Harrison