284 points · by mmphosis · 3y ago · 130 comments
Recently in an app, instead of supporting the bare minimum I wanted to support a bit more sophisticated search expression, like embedded commands and compounded conditional expression. I just hand-rolled the lexical tokenizer and the parser, and stopped without going the full mile. The tokenizer used simple regex to break up the terms and tagged them with token types. Came up with a grammar for the mini language. The parser used the standard recursive descent parsing technique on the grammar production. It's simple to handle errors and do auto-completion of the missing syntax because the parser knew what to expect at the point of error and could fill in the default nodes in the tree as needed. The generated AST was enough to implement the search tree and the embedded commands. The whole thing was only couple files and done in couple days, but it's very useful for the app.
After one year of development on my free time I had the compiler and a form editor, but lots of out of memory errors when running the code on the simulator (and real devices) :-|
At the same time, Palm sold the OS licenses to ACCESS inc., IIRC, and the future of the platform was sealed. Long story short, I shelved the project and I lost it during one of my cyclical "move backups to to a bigger disk" migration.
I would imagine a lot of the type resolution are redundant. E.g. +, -, *, and / would have the same type resolution for numbers. Those can reuse the same type resolver. May be + also work on string. Then call the string type resolver on it in addition to see if it can be resolved.
Anyway, kudos for the amazing work.
In case you were interested :P (I say compiler, it compiled to byte code, not asm.)
This is not something uncommon for a dynamically typed language; I think the simplest approach is a multidimensional array lookup.
I had to write a VBScript parser some 25 years ago (to syntax-check ASP files before they would crash live) and to get it to parse valid syntax correctly, I ended up with a messy patchwork of logic which was also letting through some really pathological edge cases. While trying to fix it, to my utter delight, I found that Microsoft’s parsers also allowed the exact same cases which looked nothing like valid code otherwise. I don’t recall specific examples anymore, but they were far from obvious without looking at the parser code, and I made and won bets with other programmers on whether those snippets would throw syntax errors or not.
Wait till you're faced with the endless .h files with their inevitable use of nutburger undocumented C extensions.
You create the header files.
There are push and pop instructions which are perfectly suited to this nested value use. In the past, lamenting how many compilers don't seem to realise that (and the fact that push/pop are specially optimised on x86 via hardware known as the stack engine), I wrote a piece of a code generator with similar capabilities to the one in this article as a proof-of-concept, and with the addition of some trivial (rotating FIFO-like) register allocation, was able to generate surprisingly compact and fast code that looks like it could've been written by a human Asm programmer.
I believe Crenshaw's famous compiler tutorial also makes the same simplification, and it's also a powerful generalisation since it means that arbitrarily deep nested expressions can be compiled, as long as there is sufficient stack space.
That's fair, but in the article I also store local variables relative to %rsp, so I wouldn't want it changing at all
I could use %rbp for that instead, but then I'd have to explain it in the article :^)
You only need to keep track of how much you've put on the stack (which can be a single counter) and adjust the offsets appropriately.
But then you'd have to explain that too...
in ur-scheme i just pushed and popped, getting performance much less terrible than i expected, but still probably a third of the performance the rotating fifo register allocator would give
Personally i've written so many parsers over the years that the code for writing one "flows" naturally and i feel like Flex/Bison would introduce complexity and dependencies for no gain.
Ironically I think the sheer number of parser generators reflects our collective failure to make a good one more so than their amazing utility (sure, some projects so actually use some).
I'm knee deep in her another parser generator these days, and I'm mildly hopeful (then that's always the case at the outset) of taking an augmented BNF variant and producing something DFA like that retains links from each state to higher level rules to retain enough information to backtrack to a reasonable place to both report errors from and/or resume parsing after an error.
I doubt the overall approach is novel in any way, and I suspect I'll be back to hand rolling parsers soon enough, but who knows, I might end up with some worthwhile reusable components from it...
it's also dramatically easier for other people to understand
The first versions were very barebones (they supported little more than variables, expressions and if/else), but over time I expanded it to support loops, arrays, pointers, structures... nowadays it's still not a full C compiler but it has been good enough for me to write several full games reliably, and even a few people have been using it too.
For example: React, Operating Systems, AI, CSS and assembly.
Understand how the math work is one level. Understanding _why_ the math work is another level.
I've been lurking for a while but only now made an account :^)
It's a bit like saying that building a rocket is no big deal, and wanting others to assume you've built a space shuttle when really it's a hobby rocket.
Plus, the language itself is probably less than 15% of the work. You'll need a build system, a standard library, a code formatter, a syntax highlighter, support for incremental and cached builds, helpful error messages, bindings for a systems language like C, among other things.
you can learn a lot of basics building a shed -- pouring concrete, adding spaces for wiring, drainage, etc. -- but ultimately it's just a small one off for learning.
Joke aside, great work up! Thank you.
I ran through the first half or so of both versions earlier this year while looking for material for a colleague (and a few other books, courses, and tutorials). Overall I like the approach which is based on the nanopass compiler concept mentioned by some other commenters. You get a functioning compiler (as in it produces an executable program) very early, and then spend the rest of the book extending the language and adding passes.
The author chose TypeScript for the Compiler, which makes it somewhat more accessible to these days programmers.
Thorston Ball's Compiler and Interpreter book series is the only other book on the subject I find widely recommend and modern.
I get there's yasm, and libnasm, and asmjit, and libgccjit, and llvm, etc but they're all varying degrees of "bad" for the purposes of a simple code generator for someone that doesn't want to dig through ARM and Intel's developer docs.
I wrote it for the purpose of making it easy to write JIT compilers in C++ and it has been adopted even by projects that are written in C (like Erlang). It's also one of the smallest libraries out there and has a great performance.
I understand why people don't want to use projects such as libgccjit or llvm, but asmjit is just super easy to use compared to others.
And back when I last used it, the docs were pretty rough. I understand that's changed a lot and they look much better now.
I think that asmjit's biggest strength is in its completeness and performance, so it can be used to generate code in a sub-millisecond time, which higher level code generators such as LLVM don't offer.
It does, it's called C :-)
> I get there's yasm, and libnasm, and asmjit, and libgccjit, and llvm, etc but they're all varying degrees of "bad" for the purposes of a simple code generator for someone that doesn't want to dig through ARM and Intel's developer docs.
This is only for language developers who aren't writing in C, right? Because if you're writing in C, what would you use this assembler for?
Anything a cross-platform assembler emits is going to be portable, so it's only going to be as performant as C is, so why not just emit C?
Having a C library that emits C might be a nice thing to have - then all the other languages can emit "code" that is cross-platform.
For example, C has a calling convention. It has a notion of a stack and heap. Certain things like arbitrary control flow, threading, and process spawning cannot be expressed in C. It has a memory model that you must adhere to.
If you actually want to implement a programming language, C is not sufficient as a transpilation target except for mostly trivial designs.
Yes, all trivially bypassed or worked-around if you're emitting C. Considering the initial constraint was "cross-platform":
1. Calling convention - what would be the point of a calling convention different to the rest of the system? You wouldn't be able to do system calls, for one. And if you need a different calling convention within the language itself C will let you push elements onto a stack and jump to a different piece of code[1], optionally saving and restoring registers.
2. The notion of a stack and heap - what's the alternative you have in mind when using assembler? Assemblers also have a notion of a stack and non-stack addresses, after all.
3. Arbitrary control flow - you can emit goto's to your hearts content (see [1] below).
4. Threading - this is platform-specific by nature, but if you're emitting C you can emit calls to the platform's thread primitives (CreateThreadEx, pthread_create, etc) the same way you'd have to do if you were using an assembler. Nothing stops you from proving a wrapper for threads that your emitted C code calls (so that it works on multiple platforms).
5. Process-spawning - once again, this is platform-specific, so even in assembler you're going to have to make a call to the platform's CreateProcess/posix_spawn/exec functions. If you're going to call a platform function from assembly, you may as well call it from C.
6. Memory model - I'll give you this point, even though the memory model is not that much different from assembler. If you're emitting C, you're still free to allocate/define a large array and use that memory in whatever way you wish.
> If you actually want to implement a programming language, C is not sufficient as a transpilation target except for mostly trivial designs.
Actually, many languages with non-trivial and advanced features, such as Common Lisp, already have implementations that transpile to C. They implement the entire Common Lisp standard, and don't seem to be missing any features even though they are emitting C and not assembler.
Anonymous functions? Done with emitted C.
Closures, continuations? Done with emitted C.
Garbage collection? Same.
What feature do you have in mind that cannot be implemented by emitting C[2], but can be implemented by emitting assembler[3]?
[1] Some constraints on the jumping exist, but emitting GCC-specific C let's you do calculated expressions for the jump target - you don't need to `goto` a constant address.
[2] I initially thought that something like Goroutines or async functions might be a candidate, but off the top of my head, I can think of at least one way to implement async functions and/or go routines by emitting C. There's probably more.
[3] I'm not being contentious, I'd really rather like to know - my own toy language (everyone has one) currently in the phase of "I'm thinking really hard about what it should look like" is going to be emitting C. I couldn't find any feature for the language that can't be done by emitting C, so I really want to know what you have in mind.
AFAIK MSVC does that unless you tell it to generate Asm output, whereas GCC always goes through the separate assembler route.
You get multiple platforms for free if I'm not wrong.
so far the author of this one has only written the first chapter
i've written a few didactic compilers that are complete enough to compile themselves, though not complete enough to compile anything else; these may be of more interest to someone who's looking for how to make writing a compiler surprisingly easy, though they do lack the extensive explanatory text in the linked blog post
- http://canonical.org/~kragen/sw/urscheme (from a subset of scheme to at&t-syntax i386 assembly, 1553 lines of code)
- https://github.com/kragen/stoneknifeforth (from a forth-like language to an i386 linux elf executable, 132 lines of code)
- https://github.com/kragen/peg-bootstrap/blob/master/peg.md (from a peg grammar with semantic actions to javascript, 66 lines of code)
- https://github.com/kragen/peg-bootstrap/blob/master/handaxew... (tangles a literate program in virtually any plain-text format, such as markdown, html, restructuredtext, or tex, into virtually any plain-text programming language, 208 lines of code; used to tangle both itself and the peg compiler compiler above)
- http://canonical.org/~kragen/sw/dev3/meta5ix.m5 (from meta5ix, a language for writing parsers derived from val schorre's meta-ii, to meta5ix assembly, 18 lines of code; it is a top-down parsing language with limited backtracking, like pegs, but less expressive and implementable without heap allocation or the ability to backtrack past the beginning of a line; see http://canonical.org/~kragen/sw/dev3/meta5ixrun.py for an m5asm interpreter)
- http://canonical.org/~kragen/sw/dev3/meta5ix2c2.m5 (from a slightly different variation of meta5ix to c, 133 lines of code)
most of these do take the same ast-free approach as the linked blog post and crenshaw, just emitting code as they finish parsing a production (or, in the case of stoneknifeforth, a token), but ur-scheme in particular does not; it uses scheme s-expressions as its syntax tree, because some kind of syntax tree is necessary to be able to allocate some local variables on the stack while also supporting closures. peg-bootstrap can certainly handle code that builds an ast with its semantic actions, but its implementation of itself just glues together snippets of javascript text
also worth mentioning in this connection:
- darius bacon's work, especially parson (for example, https://github.com/darius/parson/blob/master/eg_calc_compile...)
- the oberon compiler in wirth and gutknecht's oberon book
- the later chapters of sicp
You might also consider using the file format from the WHATWG/W3C hypertext system as your source code + presentation format. (I.e. HTML, CSS, and JavaScript.) Readers that support the format (i.e. web browsers) are ubiquitous, and JS is capable and every bit as good of a didactic language as other choices (if not better, e.g. in comparison to Python). Viz:
<https://www.colbyrussell.com/LP/debut/index.html>
(It happens to have the nice property of supporting forward declarations and function redefinition, not demonstrated in the link above.)
Once you understand the trick, you can exploit it to great effect for other purposes, like the plain.txt.htm hack:
One approach is to finish the whole compiler first and then to split it up for presentation, but I imagine most writers don't want to do that.
Also I don't have time to learn x86 instruction encoding right now :(
Lets say the slot value is 2, instruction for this would be to move the value located at %rsp-24, into the %rax register.
So your instruction becomes mov -24(%rsp), %rax
Correct?
Most teams, ours included, wrote 2 (probably rather crappy) compilers in 3 days.
> This last reason is hard for me to admit, because it’s so close to my heart. Ever since I learned to program as a kid, I felt there was something magical about languages. When I first tapped out BASIC programs one key at a time I couldn’t conceive how BASIC itself was made.
> Later, the mixture of awe and terror on my college friends’ faces when talking about their compilers class was enough to convince me language hackers were a different breed of human—some sort of wizards granted privileged access to arcane arts.
> It’s a charming image, but it has a darker side. I didn’t feel like a wizard, so I was left thinking I lacked some inborn quality necessary to join the cabal. Though I’ve been fascinated by languages ever since I doodled made-up keywords in my school notebook, it took me decades to muster the courage to try to really learn them. That “magical” quality, that sense of exclusivity, excluded me.
> And its practitioners don’t hesitate to play up this image. Two of the seminal texts on programming languages feature a dragon and a wizard on their covers.
> When I did finally start cobbling together my own little interpreters, I quickly learned that, of course, there is no magic at all. It’s just code, and the people who hack on languages are just people.
> There are a few techniques you don’t often encounter outside of languages, and some parts are a little difficult. But not more difficult than other obstacles you’ve overcome. My hope is that if you’ve felt intimidated by languages and this book helps you overcome that fear, maybe I’ll leave you just a tiny bit braver than you were before.
Sorry, I am by no means a compiler expert, but spent enough years in study of them and taken enough stabs at writing my own that this take is hopelessly naive, and I really hope the author realizes it.
Not doing a finite state machine for any stream interpretation is a huge mistake, just as much as it is outside of the compiler tokenisation, such as protocol decoders and even just parsing config files.
edit: There is a well known book with a dragon on it, but I first learnt from The Unix Programming Environment, by Brian W. Kernighan and Rob Pike. In just a few pages they clearly explain how to write an basic calculator like this, that generates intermediate code to run on a stack based interpreter. I started with this and expanded it to emit assembly for an arcane DG machine. I know that code generated ran for at least 20 years. Kinda surreal as nothing lasts that long usually.
Also this post is aimed at the author's imagined teenage self. Does that change anything?
We call this a graph, but there is no need to confuse things with advanced terms.
However, figuring out errors, adding type checking, etc now that’s hard.
A compiler is just `source -> generate -> target`. All the other fancy things are optional. IMPORTANT things, but don't detract from calling it a "compiler".
---
This is similar to anything else: A single `.html` served on `:80` is a website. A 2d, grayscale `pacman` is a videogame. `print("hello world")` is a program, etc.
Which _is_ surprisingly easy to write. But it might be a stretch to call it "a compiler" :D
Control flow and pointers are coming in the next part, and it's still surprisingly easy
"..because it was defined at [....] and used [....] and [...] as a int32 type (thus coerced to int64), but passed in [...] as a"
this may actually be somewhere between step one and two.