Want to Write a Compiler? Just Read These Two Papers (2008) - Comments

Want to Write a Compiler? Just Read These Two Papers (2008)

downbad_
msla

fanf2 on Dec 25, 2015 [dead] | parent | prev | next [–]

I quite like "understanding and writing compilers" by Richard Bornat - written in the 1970s using BCPL as the implementation language, so rather old-fashioned, but it gives a friendly gentle overview of how to do it, without excessive quantities of parsing theory.

msla
Tor3

I like that book too, I bought it many decades ago and learned enough to write a transpiler for converting Fortran source code to Turbo Pascal.

ac50hz
itsmemattchung

It's been about 4 years since I took a compilers course (from OMSCS, graduate program) and still shutter ... it was, hands down, the most difficult (yet rewarding) classes I've taken.

msla

It made me drink myself Venetian blind.

Pay08

I would like to agree with this comment, but I certainly didn't find it rewarding. It was pure pain.

nirvdrum

Based on another reply I can’t tell if there’s a clever window-based pun that I’m missing. If not, I think you want “shudder” and not “shutter” here. I’m sorry if I just ruined the joke.

tjarjoura

What did you find more painful about compilers than other forms of programming?

bluedino

I used to judge CS programs based on if they had compiler classes or not.

shepherdjerred

I loved that course so much but it was incredibly difficult to do while also working

krtkush

I wonder if it makes sense to do the nand2tetris course for an absolute beginner since it too has compiler creation in it.

imrozim

[dead]

wartywhoa23

I highly recommend nand2tetris to everyone. For me, nothing ever explained the whole domain from logic gates and inner workings of a CPU to compilers better than this course.

petcat

And Nystrom's book

vlaaad

Yeah, I really enjoyed Crafting Interpreters, wholeheartedly recommend!

armchairhacker

Nowadays I’ve heard recommended Crafting Interpreters. (https://craftinginterpreters.com)

The Nanopass paper link doesn’t work.

ramon156

Awesome course! finished it while i was doing my final CS year because I had to wait on a bunch of classes (and frankly had no one to talk to before classes). I haven't tried nanopass, but there's other links that work, so I'll give it a go.

tmountain

Incredible book for self guided learning!

gobdovan

Compilers are broad enough that when someone recommends a "compiler book", it's rarely exactly the slice you wanted.

So this made me do a runnable cheat sheet for Crafting Interpreters. I keep parsing demonstrative, and the AST is a little more Lisp-y than the book's.

Disclaimer: it's meant to convey the essence of what you'll learn, it is NOT by any means a replacement for the book. I'd also describe the book as more of an experience (including some things Nystrom clearly enjoyed, like the visitor pattern) than a compilers manual. If anyone's interested, I can do a separate visitor-pattern cheat sheet too, also in Python.

I turned it into a 'public-facing artifact' from private scripts with an AI agent.

[0] https://ouatu.ro/blog/crafting-interpreters-cheat-sheet/

orthoxerox

Crafting Interpreters is great, I wish it had a companion book that covered:

  - types and typing
- optimization passes
- object files, executables, libraries and linking
Then two of them would be sufficient for writing a compiler.

menato

[dead]

GCUMstlyHarmls

Nanopass paper seems to be dead but can be found here at least https://stanleymiracle.github.io/blogs/compiler/docs/extra/n...

kunley
NordStreamYacht

Also you could go to Andy Keep's site: https://nanopass.org/

consomida

[dead]

imrozim

[dead]

rdevilla

Almost 20 years old. This knowledge, this entire field of study, is obsolete in the AI era. What's next, handwritten XHTML?

KnuthIsGod

Some of us enjoy intellectual challenges....

The Bornat book looks great.

The fact that it is in BCPL is ultra cool.

noosphr

lol

voidUpdate

I've been handwriting my website since forever. That way I don't have to also load megabytes of JS libraries, and it keeps it nice and lean (ish)

fzeindl

A similarly scoped book series is „AI game programming wisdom“, which contains a multitude of chapters that focus on diverse, individual algorithms that can be practically used in games for a variety of usecases.

jll29

*Donald Knute -> Donald Ervin Knuth is the author of the book "The Art of Computer Programming" (in progress for a couple of decades, currently volume 4c is being written). It is quite advanced, and it will likely not cover compilers anymore (Addison-Wesley had commissioned a compiler book from Knuth when he was a doctoral candidate, now he is retired and has stated his goal for the series has changed).

I disagree with the author's point: the "Dragon book"'s ("Compilers: Principles, Techniques, and Tools" by Aho et al.) Chapter 2 is a self-sufficient introduction into compilers from end to end, and it can be read on its own, ignoring the rest of the excellent book.

Another fantastic intro to compiler writing is the short little book "Compilers" by Niklaus Wirth, which explains and contains the surprisingly short source code of a complete compiler (the whole book is highly understandable - pristine clarity, really) and all in <100 pages total (99).

(I learned enough from these two sources to write a compiler in high school.)

Hendrikto
antiquark

There is still hope for a compiler book. From Knuth's website:

> And after Volumes 1--5 are done, God willing, I plan to publish Volume 6 (the theory of context-free languages) and Volume 7 (Compiler techniques), but only if the things I want to say about those topics are still relevant and still haven't been said.

https://www-cs-faculty.stanford.edu/~knuth/taocp.html

projektfu

The dragon book almost convinced me never to try to write a compiler. I don't know why people recommend it. I guess you're a lot smarter than I am.

There are some excellent books out there. In its own way, the dragon book is excellent, but it is a terrible starting place.

Here are a bunch of references from the same vintage as OP. I recommend starting with a book that actually walks through the process of building a compiler and doesn't spend its time exclusively with theory.

https://news.ycombinator.com/item?id=136875

Findecanor

The "Dragon Book" contains a lot on parsing, but I wouldn't recommend it if you want to make many optimisation passes or a back-end.

I had bought the first edition when I was in High School back in the '90s. It was my first CS textbook and as a young programmer I learned a lot from it. A couple years ago, I started on a modern compiler back-end, and found that I needed to update my knowledge quite a lot.

The second edition covers data-flow analysis, which is very important. However, modern compilers (GCC, LLVM, Cranelift) are built around an intermediary representation in Static Single Assignment-form, and the second ed. has only a single page about it, but you'd need to also learn a lot of theory about its properties to actually use it.

LoganDark

I'd never seen Knuth's middle name until your comment. I think it safely could be left out of an article.

LiamPowell

See also, Andy Keep's dissertation [1] and his talk at Clojure/Conj 2013 [2].

I think that the nanopass architecture is especially well suited for compilers implemented by LLMs as they're excellent at performing small and well defined pieces of work. I'd love to see Anthropic try their C compiler experiment again but with a Nanopass framework to build on.

I've recently been looking in to adding Nanopass support to Langkit, which would allow for writing a Nanopass compiler in Ada, Java, Python, or a few other languages [3].

[1]: https://andykeep.com/pubs/dissertation.pdf

[2]: https://www.youtube.com/watch?v=Os7FE3J-U5Q

[3]: https://github.com/AdaCore/langkit/issues/668

bradley13

Maybe I'm missing the point of this article? Writing a simple compiler is not difficult. It's not something for beginners, but towards the end of a serious CS degree program it is absolutely do-able. Parsing, transforming into some lower-level representation, even optimizations - it's all fun really not that difficult. I still have my copy of the "Dragon Book", which is where I originally learned about this stuff.

In fact, inventing new programming languages and writing compilers for them used to be so much of a trend that people created YACC (Yet Another Compiler Compiler) to make it easier.

zionpi

[dead]

omcnoe

Been working on a toy compiler for fun recently.

I have ignored all the stuff about parsing theory, parser generators, custom DSL's, formal grammers etc. and instead have just been using the wonderful Megaparsec parser combinator library. I can easily follow the parsing logic, it's unambiguous (only one successful parse is possible, even if it might not be what you intended), it's easy to compose and re-use parser functions (was particularly helpful for whitespace sensitive parsing/line-fold handling), and it removes the tedious lexer/parser split you get with traditional parsing approaches.

mrkeen

I'll push back and say that the lexer/parser split is well worth it.

And the best thing about the parser combinator approach is that each is just a kind of parser, something like

  type Lexer = ParsecT e ByteString m [Token]


type Parser = ParsecT e [Token] Expr
All the usual helper functions like many or sepBy work equally well in the lexing and parsing phases.

It really beats getting to the parentheses-interacting-with-ordering-of-division-operations stage and still having to think "have I already trimmed off the whitespace here or not?"

armchairhacker

It seems to me LL and LR parser generators are overrated, and hand-written recursive descent is best in practice. I understand why academics teach them, but not why some spend so long on different parsing techniques, nor why hobbyists who just want to compile their toy language are directed to them.

I work in PL, and from my first compiler to today, have always found recursive descent easiest, most effective (less bugs, better error diagnostics, fast enough), and intuitive. Many popular language compilers use recursive descent: I know at least C# (Roslyn) and Rust, but I believe most except Haskell (GHC) and ocaml.

The LR algorithm was simple once I learned it, and yacc-like LR (and antlr-like LL) parser generators were straightforward once I learned how to resolve conflicts. But recursive descent (at least to me) is simpler and more straightforward.

LR being more expressive than LL has never mattered. A hand-written recursive descent parser is most expressive: it has unlimited lookahead, and can modify parsed AST nodes (e.g. reordering for precedence, converting if into if-else).

The only solution that comes close is tree-sitter, because it implements GLR, provides helpful conflict messages, and provides basic IDE support (e.g. syntax highlighting) almost for free. But it’s a build dependency, while recursive descent parsers can be written in most languages with zero dependencies and minimal boilerplate.

soegaard

An Incremental Approach to Compiler Construction

Abdulaziz Ghuloum

http://scheme2006.cs.uchicago.edu/11-ghuloum.pdf

Abstract

Compilers are perceived to be magical artifacts, carefully crafted by the wizards, and unfathomable by the mere mortals. Books on compilers are better described as wizard-talk: written by and for a clique of all-knowing practitioners. Real-life compilers are too complex to serve as an educational tool. And the gap between real-life compilers and the educational toy compilers is too wide. The novice compiler writer stands puzzled facing an impenetrable barrier, “better write an interpreter instead.”

The goal of this paper is to break that barrier. We show that building a compiler can be as easy as building an interpreter. The compiler we construct accepts a large subset of the Scheme programming language and produces assembly code for the Intel-x86 architecture, the dominant architecture of personal computing. The development of the compiler is broken into many small incremental steps. Every step yields a fully working compiler for a progressively expanding subset of Scheme. Every compiler step produces real assembly code that can be assembled then executed directly by the hardware. We assume that the reader is familiar with the basic computer architecture: its components and execution model. Detailed knowledge of the Intel-x86 architecture is not required.

The development of the compiler is described in detail in an extended tutorial. Supporting material for the tutorial such as an automated testing facility coupled with a comprehensive test suite are provided with the tutorial. It is our hope that current and future implementors of Scheme find in this paper the motivation for developing high-performance compilers and the means for achieving that goal.

asibahi

Inspired by Ghuloum's book is this really nice book by Nora Sandler: Writing a C Compiler https://norasandler.com/book/

morphle

Compiler writing has progressed a lot. Notably in meta compilers [1] written in a few hundred lines of code and adaptive compilation [3] and just in time compilers.

[1] Ometa https://tinlizzie.org/VPRIPapers/tr2007003_ometa.pdf

[2] Other ometa papers https://tinlizzie.org/IA/index.php/Papers_from_Viewpoints_Re...

[3] Adaptive compilation https://youtu.be/CfYnzVxdwZE?t=4575

voidUpdate

I've been having a look at the Crenshaw series, and it seems pretty good, but one thing that kinda annoys me is the baked-in line wrapping. Is there a way to unwrap the text so its not all in a small area on the left of my screen?

ape4

Would a practical approach be parsing the source into clang's AST format. Then let it make the actual executable.

stupefy

One nice piece of advice that I received is that books are like RAMs, you do not have to go through them sequentially, but can do random access to the parts of it you need. With this in mind I find it doable to get one the thick books and only read the part that I need for my task.

But, to also be fair, the above random access method does not work when you don't know what you don't know. So I understand why having a light, but good introduction to the topic is important, and I believe that's what the author is pointing out.

commandlinefan

I've seen people suggest that throughout the years, but it's never worked out for me. To get anything meaningful out of a printed book, I've had to read them cover to cover. There used to be worthwhile reference books, but those have moved on to the internet.

wglb

A significant fraction of my technical library is used just this way--as a reference, checking out the parts to answer a specific question.

baarse

[dead]

blueybingo

the article's framing around nanopass is undersold: the real insight isn't the number of passes but that each pass has an explicit input and output language, which forces you to think about what invariants hold at each stage. that discipline alone catches a suprising number of bugs before you even run the compiler. crenshaw is fantastic but this structural thinking is what separates toy compilers from ones you can actaully extend later.

lateforwork

These days there's an even easier way to learn to write a compiler. Just ask Claude to write a simple compiler. Here's a simple C compiler (under 1500 lines) written by Claude: https://github.com/Rajeev-K/c-compiler It can compile and run C programs for sorting and searching. The code is very readable and very easy to understand.

angusturner

why read that, vs an actually well-written compiler though?

voidfunc

For those of us that learn better by taking something and tinkering with it this is definitely the better approach.

Ive never been a good book learner but I love taking apart and tinkering with something to learn. A small toy compiler is way better than any book and its not like the LLM didnt absorb the book anyways during training.

LLMCodeAuditor

I did not and will not run this on my computer but it looks like while loops are totally broken; note how poor the test coverage is. This is just my quick skimming of the code. Maybe it works perfectly and I am dumber than a computer.

Regardless, it is incredibly reckless to ask Claude to generate assembly if you don't understand assembly, and it's irresponsible to recommend this as advice for newbies. They will not be able to scan the source code for red flags like us pros. Nor will they think "this C compiler is totally untrustworthy, I should test it on a VM."

aldousd666

I learned from the Dragon Book, decades ago. I already knew a lot of programming at that point, but I think most people writing compilers do. I'm curious if there really is an audience of people whose first introduction to programming is writing a compiler... I would think not, actually.

mzs

archive of forth translation of Crenshaw’s howto

https://web.archive.org/web/20190712115536/http://home.iae.n...

notnullorvoid

I might be in the minority, but I think the best way to learn how to write a compiler is to try writing one without books or tutorials. Keep it very small in scope at first, small enough that you can scrap the entire implementation and rewrite in an afternoon or less.

anthk

https://t3x.org has literal books on that, from a simple C compiler to Scheme (you might heard of s9) and T3X0 itself which can run under Unix, Windows, DOS, CP/M and whatnot.

PD: Klong's intro to statisticks, even if the compiler looks like a joke, it isn't. It can be damn useful. Far easier than Excel. And it comes with a command to output a PS file with your chart being embedded.

https://t3x.org/klong/

Intro to statistics with Klong

https://t3x.org/klong/klong-intro.txt.html

https://t3x.org/klong/klong-ref.txt.html

On S9, well, it has Unix, Curses, sockets and so on support with an easy API. So it's damn easy to write something if you know Scheme/Ncurses and try stuff in seconds. You can complete the "Concrete Abstractions" book with it, and just adapt the graphic functions to create the (frame) one for SICP (and a few more).

And as we are doing compilers... with SICP you create from some simulator to some Scheme interpreter in itself.

kuharich
WalterBright

What taught me how to write a compiler was the BYTE magazine 1978-08 .. 09 issues which had a listing for a Tiny Pascal compiler. Reading the listing was magical.

What taught me how to write an optimizer was a Stanford summer course taught by Ullman and Hennessy.

The code generator was my own concoction, and is apparently quite unlike any other one out there!

I have the Dragon Book, but have never actually read it. So sue me.

downbad_
msla

fanf2 on Dec 25, 2015 [dead] | parent | prev | next [–]

I quite like "understanding and writing compilers" by Richard Bornat - written in the 1970s using BCPL as the implementation language, so rather old-fashioned, but it gives a friendly gentle overview of how to do it, without excessive quantities of parsing theory.

msla
Tor3

I like that book too, I bought it many decades ago and learned enough to write a transpiler for converting Fortran source code to Turbo Pascal.

ac50hz
itsmemattchung

It's been about 4 years since I took a compilers course (from OMSCS, graduate program) and still shutter ... it was, hands down, the most difficult (yet rewarding) classes I've taken.

msla

It made me drink myself Venetian blind.

Pay08

I would like to agree with this comment, but I certainly didn't find it rewarding. It was pure pain.

nirvdrum

Based on another reply I can’t tell if there’s a clever window-based pun that I’m missing. If not, I think you want “shudder” and not “shutter” here. I’m sorry if I just ruined the joke.

tjarjoura

What did you find more painful about compilers than other forms of programming?

bluedino

I used to judge CS programs based on if they had compiler classes or not.

shepherdjerred

I loved that course so much but it was incredibly difficult to do while also working

krtkush

I wonder if it makes sense to do the nand2tetris course for an absolute beginner since it too has compiler creation in it.

imrozim

[dead]

wartywhoa23

I highly recommend nand2tetris to everyone. For me, nothing ever explained the whole domain from logic gates and inner workings of a CPU to compilers better than this course.

petcat

And Nystrom's book

vlaaad

Yeah, I really enjoyed Crafting Interpreters, wholeheartedly recommend!

armchairhacker

Nowadays I’ve heard recommended Crafting Interpreters. (https://craftinginterpreters.com)

The Nanopass paper link doesn’t work.

ramon156

Awesome course! finished it while i was doing my final CS year because I had to wait on a bunch of classes (and frankly had no one to talk to before classes). I haven't tried nanopass, but there's other links that work, so I'll give it a go.

tmountain

Incredible book for self guided learning!

gobdovan

Compilers are broad enough that when someone recommends a "compiler book", it's rarely exactly the slice you wanted.

So this made me do a runnable cheat sheet for Crafting Interpreters. I keep parsing demonstrative, and the AST is a little more Lisp-y than the book's.

Disclaimer: it's meant to convey the essence of what you'll learn, it is NOT by any means a replacement for the book. I'd also describe the book as more of an experience (including some things Nystrom clearly enjoyed, like the visitor pattern) than a compilers manual. If anyone's interested, I can do a separate visitor-pattern cheat sheet too, also in Python.

I turned it into a 'public-facing artifact' from private scripts with an AI agent.

[0] https://ouatu.ro/blog/crafting-interpreters-cheat-sheet/

orthoxerox

Crafting Interpreters is great, I wish it had a companion book that covered:

  - types and typing
- optimization passes
- object files, executables, libraries and linking
Then two of them would be sufficient for writing a compiler.

menato

[dead]

GCUMstlyHarmls

Nanopass paper seems to be dead but can be found here at least https://stanleymiracle.github.io/blogs/compiler/docs/extra/n...

kunley
NordStreamYacht

Also you could go to Andy Keep's site: https://nanopass.org/

consomida

[dead]

imrozim

[dead]

rdevilla

Almost 20 years old. This knowledge, this entire field of study, is obsolete in the AI era. What's next, handwritten XHTML?

KnuthIsGod

Some of us enjoy intellectual challenges....

The Bornat book looks great.

The fact that it is in BCPL is ultra cool.

noosphr

lol

voidUpdate

I've been handwriting my website since forever. That way I don't have to also load megabytes of JS libraries, and it keeps it nice and lean (ish)

fzeindl

A similarly scoped book series is „AI game programming wisdom“, which contains a multitude of chapters that focus on diverse, individual algorithms that can be practically used in games for a variety of usecases.

jll29

*Donald Knute -> Donald Ervin Knuth is the author of the book "The Art of Computer Programming" (in progress for a couple of decades, currently volume 4c is being written). It is quite advanced, and it will likely not cover compilers anymore (Addison-Wesley had commissioned a compiler book from Knuth when he was a doctoral candidate, now he is retired and has stated his goal for the series has changed).

I disagree with the author's point: the "Dragon book"'s ("Compilers: Principles, Techniques, and Tools" by Aho et al.) Chapter 2 is a self-sufficient introduction into compilers from end to end, and it can be read on its own, ignoring the rest of the excellent book.

Another fantastic intro to compiler writing is the short little book "Compilers" by Niklaus Wirth, which explains and contains the surprisingly short source code of a complete compiler (the whole book is highly understandable - pristine clarity, really) and all in <100 pages total (99).

(I learned enough from these two sources to write a compiler in high school.)

Hendrikto
antiquark

There is still hope for a compiler book. From Knuth's website:

> And after Volumes 1--5 are done, God willing, I plan to publish Volume 6 (the theory of context-free languages) and Volume 7 (Compiler techniques), but only if the things I want to say about those topics are still relevant and still haven't been said.

https://www-cs-faculty.stanford.edu/~knuth/taocp.html

projektfu

The dragon book almost convinced me never to try to write a compiler. I don't know why people recommend it. I guess you're a lot smarter than I am.

There are some excellent books out there. In its own way, the dragon book is excellent, but it is a terrible starting place.

Here are a bunch of references from the same vintage as OP. I recommend starting with a book that actually walks through the process of building a compiler and doesn't spend its time exclusively with theory.

https://news.ycombinator.com/item?id=136875

Findecanor

The "Dragon Book" contains a lot on parsing, but I wouldn't recommend it if you want to make many optimisation passes or a back-end.

I had bought the first edition when I was in High School back in the '90s. It was my first CS textbook and as a young programmer I learned a lot from it. A couple years ago, I started on a modern compiler back-end, and found that I needed to update my knowledge quite a lot.

The second edition covers data-flow analysis, which is very important. However, modern compilers (GCC, LLVM, Cranelift) are built around an intermediary representation in Static Single Assignment-form, and the second ed. has only a single page about it, but you'd need to also learn a lot of theory about its properties to actually use it.

LoganDark

I'd never seen Knuth's middle name until your comment. I think it safely could be left out of an article.

LiamPowell

See also, Andy Keep's dissertation [1] and his talk at Clojure/Conj 2013 [2].

I think that the nanopass architecture is especially well suited for compilers implemented by LLMs as they're excellent at performing small and well defined pieces of work. I'd love to see Anthropic try their C compiler experiment again but with a Nanopass framework to build on.

I've recently been looking in to adding Nanopass support to Langkit, which would allow for writing a Nanopass compiler in Ada, Java, Python, or a few other languages [3].

[1]: https://andykeep.com/pubs/dissertation.pdf

[2]: https://www.youtube.com/watch?v=Os7FE3J-U5Q

[3]: https://github.com/AdaCore/langkit/issues/668

bradley13

Maybe I'm missing the point of this article? Writing a simple compiler is not difficult. It's not something for beginners, but towards the end of a serious CS degree program it is absolutely do-able. Parsing, transforming into some lower-level representation, even optimizations - it's all fun really not that difficult. I still have my copy of the "Dragon Book", which is where I originally learned about this stuff.

In fact, inventing new programming languages and writing compilers for them used to be so much of a trend that people created YACC (Yet Another Compiler Compiler) to make it easier.

zionpi

[dead]

omcnoe

Been working on a toy compiler for fun recently.

I have ignored all the stuff about parsing theory, parser generators, custom DSL's, formal grammers etc. and instead have just been using the wonderful Megaparsec parser combinator library. I can easily follow the parsing logic, it's unambiguous (only one successful parse is possible, even if it might not be what you intended), it's easy to compose and re-use parser functions (was particularly helpful for whitespace sensitive parsing/line-fold handling), and it removes the tedious lexer/parser split you get with traditional parsing approaches.

mrkeen

I'll push back and say that the lexer/parser split is well worth it.

And the best thing about the parser combinator approach is that each is just a kind of parser, something like

  type Lexer = ParsecT e ByteString m [Token]


type Parser = ParsecT e [Token] Expr
All the usual helper functions like many or sepBy work equally well in the lexing and parsing phases.

It really beats getting to the parentheses-interacting-with-ordering-of-division-operations stage and still having to think "have I already trimmed off the whitespace here or not?"

armchairhacker

It seems to me LL and LR parser generators are overrated, and hand-written recursive descent is best in practice. I understand why academics teach them, but not why some spend so long on different parsing techniques, nor why hobbyists who just want to compile their toy language are directed to them.

I work in PL, and from my first compiler to today, have always found recursive descent easiest, most effective (less bugs, better error diagnostics, fast enough), and intuitive. Many popular language compilers use recursive descent: I know at least C# (Roslyn) and Rust, but I believe most except Haskell (GHC) and ocaml.

The LR algorithm was simple once I learned it, and yacc-like LR (and antlr-like LL) parser generators were straightforward once I learned how to resolve conflicts. But recursive descent (at least to me) is simpler and more straightforward.

LR being more expressive than LL has never mattered. A hand-written recursive descent parser is most expressive: it has unlimited lookahead, and can modify parsed AST nodes (e.g. reordering for precedence, converting if into if-else).

The only solution that comes close is tree-sitter, because it implements GLR, provides helpful conflict messages, and provides basic IDE support (e.g. syntax highlighting) almost for free. But it’s a build dependency, while recursive descent parsers can be written in most languages with zero dependencies and minimal boilerplate.

soegaard

An Incremental Approach to Compiler Construction

Abdulaziz Ghuloum

http://scheme2006.cs.uchicago.edu/11-ghuloum.pdf

Abstract

Compilers are perceived to be magical artifacts, carefully crafted by the wizards, and unfathomable by the mere mortals. Books on compilers are better described as wizard-talk: written by and for a clique of all-knowing practitioners. Real-life compilers are too complex to serve as an educational tool. And the gap between real-life compilers and the educational toy compilers is too wide. The novice compiler writer stands puzzled facing an impenetrable barrier, “better write an interpreter instead.”

The goal of this paper is to break that barrier. We show that building a compiler can be as easy as building an interpreter. The compiler we construct accepts a large subset of the Scheme programming language and produces assembly code for the Intel-x86 architecture, the dominant architecture of personal computing. The development of the compiler is broken into many small incremental steps. Every step yields a fully working compiler for a progressively expanding subset of Scheme. Every compiler step produces real assembly code that can be assembled then executed directly by the hardware. We assume that the reader is familiar with the basic computer architecture: its components and execution model. Detailed knowledge of the Intel-x86 architecture is not required.

The development of the compiler is described in detail in an extended tutorial. Supporting material for the tutorial such as an automated testing facility coupled with a comprehensive test suite are provided with the tutorial. It is our hope that current and future implementors of Scheme find in this paper the motivation for developing high-performance compilers and the means for achieving that goal.

asibahi

Inspired by Ghuloum's book is this really nice book by Nora Sandler: Writing a C Compiler https://norasandler.com/book/

morphle

Compiler writing has progressed a lot. Notably in meta compilers [1] written in a few hundred lines of code and adaptive compilation [3] and just in time compilers.

[1] Ometa https://tinlizzie.org/VPRIPapers/tr2007003_ometa.pdf

[2] Other ometa papers https://tinlizzie.org/IA/index.php/Papers_from_Viewpoints_Re...

[3] Adaptive compilation https://youtu.be/CfYnzVxdwZE?t=4575

voidUpdate

I've been having a look at the Crenshaw series, and it seems pretty good, but one thing that kinda annoys me is the baked-in line wrapping. Is there a way to unwrap the text so its not all in a small area on the left of my screen?

ape4

Would a practical approach be parsing the source into clang's AST format. Then let it make the actual executable.

stupefy

One nice piece of advice that I received is that books are like RAMs, you do not have to go through them sequentially, but can do random access to the parts of it you need. With this in mind I find it doable to get one the thick books and only read the part that I need for my task.

But, to also be fair, the above random access method does not work when you don't know what you don't know. So I understand why having a light, but good introduction to the topic is important, and I believe that's what the author is pointing out.

commandlinefan

I've seen people suggest that throughout the years, but it's never worked out for me. To get anything meaningful out of a printed book, I've had to read them cover to cover. There used to be worthwhile reference books, but those have moved on to the internet.

wglb

A significant fraction of my technical library is used just this way--as a reference, checking out the parts to answer a specific question.

baarse

[dead]

blueybingo

the article's framing around nanopass is undersold: the real insight isn't the number of passes but that each pass has an explicit input and output language, which forces you to think about what invariants hold at each stage. that discipline alone catches a suprising number of bugs before you even run the compiler. crenshaw is fantastic but this structural thinking is what separates toy compilers from ones you can actaully extend later.

lateforwork

These days there's an even easier way to learn to write a compiler. Just ask Claude to write a simple compiler. Here's a simple C compiler (under 1500 lines) written by Claude: https://github.com/Rajeev-K/c-compiler It can compile and run C programs for sorting and searching. The code is very readable and very easy to understand.

angusturner

why read that, vs an actually well-written compiler though?

voidfunc

For those of us that learn better by taking something and tinkering with it this is definitely the better approach.

Ive never been a good book learner but I love taking apart and tinkering with something to learn. A small toy compiler is way better than any book and its not like the LLM didnt absorb the book anyways during training.

LLMCodeAuditor

I did not and will not run this on my computer but it looks like while loops are totally broken; note how poor the test coverage is. This is just my quick skimming of the code. Maybe it works perfectly and I am dumber than a computer.

Regardless, it is incredibly reckless to ask Claude to generate assembly if you don't understand assembly, and it's irresponsible to recommend this as advice for newbies. They will not be able to scan the source code for red flags like us pros. Nor will they think "this C compiler is totally untrustworthy, I should test it on a VM."

aldousd666

I learned from the Dragon Book, decades ago. I already knew a lot of programming at that point, but I think most people writing compilers do. I'm curious if there really is an audience of people whose first introduction to programming is writing a compiler... I would think not, actually.

mzs

archive of forth translation of Crenshaw’s howto

https://web.archive.org/web/20190712115536/http://home.iae.n...

notnullorvoid

I might be in the minority, but I think the best way to learn how to write a compiler is to try writing one without books or tutorials. Keep it very small in scope at first, small enough that you can scrap the entire implementation and rewrite in an afternoon or less.

anthk

https://t3x.org has literal books on that, from a simple C compiler to Scheme (you might heard of s9) and T3X0 itself which can run under Unix, Windows, DOS, CP/M and whatnot.

PD: Klong's intro to statisticks, even if the compiler looks like a joke, it isn't. It can be damn useful. Far easier than Excel. And it comes with a command to output a PS file with your chart being embedded.

https://t3x.org/klong/

Intro to statistics with Klong

https://t3x.org/klong/klong-intro.txt.html

https://t3x.org/klong/klong-ref.txt.html

On S9, well, it has Unix, Curses, sockets and so on support with an easy API. So it's damn easy to write something if you know Scheme/Ncurses and try stuff in seconds. You can complete the "Concrete Abstractions" book with it, and just adapt the graphic functions to create the (frame) one for SICP (and a few more).

And as we are doing compilers... with SICP you create from some simulator to some Scheme interpreter in itself.

kuharich
WalterBright

What taught me how to write a compiler was the BYTE magazine 1978-08 .. 09 issues which had a listing for a Tiny Pascal compiler. Reading the listing was magical.

What taught me how to write an optimizer was a Stanford summer course taught by Ullman and Hennessy.

The code generator was my own concoction, and is apparently quite unlike any other one out there!

I have the Dragon Book, but have never actually read it. So sue me.