by userbinator · 8y ago · 0 comments
Unfortunately this is something that no compiler I know of does, as evidenced by their -O0 being far worse than even what a naive Asm programmer (human) could do, and it's one of the things that irks me about compilers. Dataflow-directed, "work backwards" techniques might be the solution to this, but once again I don't know of any compilers that do it.
On the other hand, his points about using recursive-descent parsing seem to agree with the majority of widely-used compilers. However, this is factually incorrect:
I even think that the availability of powerful bottom-up parser generators such as Yacc are responsible for the cryptic syntax of C.
Dennis Ritchie's first C compiler used recursive descent. Yacc itself was written in C, so it could not have come before. You can see the sources yourself here: https://news.ycombinator.com/item?id=5748672
> Unfortunately this is something that no compiler I know of does,
You're probably right compared to modern compilers. What you need to compare to are the compilers of the era, which were truly abysmal.
It's not that the Wirth compilers generated fantastic code (e.g. at least one of Wirths students explored adding much more aggressive optimization to his Oberon compiler), but they generated code that was a great deal better than a lot of non-Wirth style compilers at the time.
Some compilers of the time even depended on peephole optimizer passes because the code they generated was so bad that even simple 2-3 instruction peephole passes were enough to drastically improve the code. There was little reason for this. E.g. most of the time it was a matter of as basic stuff as passing on information about the registers to use rather than the dumb/naive approach of generating everything using scratch registers that you move things to/from.
I remember back in my asm days that I once had the C source for a GUI component I wanted to use, but the code the C compiler I had available generated was so awful that in exasperation I compiled it, disassembled it, and proceeded to manually clean it up. I deleted about half the instructions of about several thousand lines of compiler output, with very minimal fixups.
The first Java client jit compiler, was developed by Robert Griesemer (former PhD student of Wirth). The design of the compiler is described in the paper "A compiler for the java hotspot virtual machine", published in the same book: "The School of Niklaus Wirth: The Art of Simplicity".
Turbo Pascal (and Delphi), originally influenced by Wirth's books did exactly that. It was an incredibly fast compiler that generated surprizingly decent binaries.
I'm sure it helped that Pascal had a IMNHO saner calling convention (more like the current amd64 convention) - so would utilise register for passing arguments rather than always using the stack.
I'm not saying you can't, I'm just saying that "as fast machine code as early 90s era c compilers" might not translate to as fast as today's c++ compilers machine code.
http://minnie.tuhs.org/cgi-bin/utree.pl?file=V6/usr/source/c...
Search for statement() and forstmt().
(This site has a more modern, easier-to-read version of the Github files, which at least has #defines rather than hard-coded ints!!!)
But a large part of it is also Dijikstra's shunting yard algorithm:
http://minnie.tuhs.org/cgi-bin/utree.pl?file=V6/usr/source/c...
Read an expression and return a pointer to its tree. It's the classical bottom-up, priority-driven scheme. The initflg prevents the parse from going past "," or ":" because those delimitesrs are special in initializer (and some other) expressions.
tree()
Related post: Code for the Shunting Yard Algorithm, and More http://www.oilshell.org/blog/2017/04/22.htmlAs for using it for the entire programming language, like for/while/switch, I see the discussion with vidarh below.
I haven't seen a parser written like this, so that's interesting.
However I consider the "opposite" sort of a mistake? Doug Crockford uses top-down operator precedence to parse ALL of JavaScript, not just the expression language.
Review of Pratt/TDOP Parsing Tutorials http://www.oilshell.org/blog/2016/11/02.html
I remember being confused by this, and I think it is still confusing. It seems to me that the statement language and expression language are separate things, and it makes sense to use recursive descent for the statement language and either top-down or bottom-up precedence for expressions. In other words, the architecture of the original C compiler is very clean, and no doubt influenced the language design. (On the other hand, it's probably also responsible for the fact that C has so many levels of precedence, some of which don't make sense!)
Also, the difference between "Pratt parsing" and "Precedence climbing" is sort of a code organization issue -- do you handle a[i] and x?a:b in the same place as a*b a+b etc.? I wondered if there is an analogous thing for bottom-up expression parsing. I like having each "form" in one function.
Pratt parsing is a nice complement to recursive descent; it's accurate to say that it's a variant of recursive descent with the additional input of numerical priorities.
I've done a full Pascal-like language using bottom up precedence parsing in the past. It was my first compiler project about 25 years ago or so, and "invented" precedence parsing with the help of a symbolic expression evaluator in Prolog in a book I picked up that I tried to figure out how to translate to Pascal.
It was very disappointing to find out it was a well known algorithm, but it was very interesting to try to expand it to handle a full language, which involved funky things like handling operators with different structure than just simple single-operand prefix/postfix + infix operators. E.g. I implemented a dual-arity prefix operator to handle for/while/if/ternary for example. So "while" took two expressions: the condition and a block.
The hard part was not handling the control structures, but getting the priorities right.
I'm not sure I'd do that again. My Ruby parser uses recursive descent for the top level productions.
But it was fascinating to do, as it did make for a very compact parser.
> It seems to me that the statement language and expression language are separate things,
I think if you go down that route, then you are implicitly deciding that everything is an expression. In e.g. Ruby that is true, though many constructs just returns nil (e.g "somevar = while condition; end" is valid). But given that many of the "operators" are only allowed at specific levels, it makes less sense to use a precedence parser anyway (e.g. "class" can't occur in a method body for example).
For me, those two are the biggest considerations to whether or not I'd consider a precedence parser: Whether or not everything is an expression, and which keywords are only allowed in specific contexts.
But even if it's feasible without too many contortions, it may still be very painful.
If you're willing to sacrifice a bit more generality you can parse a lot more. E.g. my (very much in-progress and incomplete) Ruby compiler uses precedence parsing with tweaks to parse most of the Ruby grammar, including blocks (do/end, {/}), array indices and initializers (foo[1], vs [1,2,3]) and more.
It's been hell to adjust the priorities, and it's not correct yet, but I also think it can be cleaned up quite a bit more. The biggest pain point, actually, is tidying up the generated tree to remove superfluous nodes and flaten various bits, and that's where I'll need to do the most work to simplify.
There are of course ugly parts of this with Ruby that ruined my originally quite nice and clean generic shunting yard code. E.g. if "foo" is a local variable "foo [1]" should parse as "foo.[](1)" (that is '[]' is a method name), while if "foo" is not a local variable, it is implicitly a method call, and "foo [1]" should parse as "foo([1])" with "self" as implicit receiver. I've for now resolved that by having a few "artificial" terminals to handle this and a few other ambiguities that are picked based on context and resolved later, but I'm really not happy about it. Worst case is I "surrender" and convert it to a recursive descent like the higher levels of the grammar, but I want to see what I can do with the current one first.
Currently the full parser, which still lacks some parts of Ruby is about 1600 lines of Ruby (including the lexical tokenizer and some generic parser/scanner utility classes), which I'm distinctly displeased about - it's much smaller than MRI, but not as much smaller as I think should be possible, especially since it's still missing pieces; granted there's a lot of comments, but I think parsing Ruby in Ruby should be doable in <1000 lines of Ruby code using recursive descent + precedence parsing despite Ruby's many idiosyncracies. Less if you exclude the code for a decent generic parser library. I think that says a lot of the simplicity of applying both recursive descent and precedence parsing..
Sure, you can also deal with terminal overloading using adjacency if you want. However, the parser gets more complex and it becomes less worth it. In the parsers I build, I match braces in a separate earlier phase anyways (you don’t need a parser to do that, and it makes the parser much more robust if you do).
However, the main drawback of a precedence parser is that you don’t get any parse errors out of it, and you have to manually go back and check that your trees are actually well formed. So I’ve went back to pure recursive descent.
> Dataflow-directed, "work backwards" techniques might be the solution
Destination driven code generation is a known technique. It doesn't generate good enough results to have gotten much attention (better than what you get from -O0, though).