222 points · by ingve · 10y ago · 95 comments
I tried several time to explain why I think people should use parser generators and the conclusion of this article express my point of view perfectly. The fact that we have a very good parser generator in OCaml (and Coq!)[1] really helps here.
I still think that ambiguities of the third kind, "Type/variable ambiguity", are a design issue and your grammar should be changed, because it's going to be completely ambiguous for humans too.
As Meredith and Sergey explain in their talk[1] at 28c3, Turing complete input and parsers that don't validate the input are creating a "weird machine" just waiting to be programmed in malicious and unexpected ways.
[1] https://media.ccc.de/v/28c3-4763-en-the_science_of_insecurit...
Do you think the use of parser generators is practical also for performance-critical binary data? For example video streams? (I've never parsed one but I imagine they could be so optimized that it could be impractical to do it with a generic parser generator).
What formats are examples of complex structure where parser generators are practical?
For my personal needs, I've been getting along very well with plain text relational data. Like
numPersons 2
numAncestors 1
person john "John Doe"
person jane "Jane Dane"
ancestor john jane
That's so trivial that I would never want to depend on a parser generator. Instead I handroll a parser for this format in 10 minutes and 20 lines of C if I don't mind bad error messages. And what parser generator would make it easy to check (relational) integrity of above data in a secure way?If I leave away the num* fields above, the parser would need one token of lookahead. What type of grammars are these two versions?
That's not a question I consider very important, because prioritizing performance over correctness (safety) is irresponsible.
That said, using a parser generator shouldn't have a significant impact on performance. When a network is involved, the parser isn't going to be the bottleneck anyway.
> video
I am not very familiar with the details of video formats, but I would suggest trying the parser combinator library Meredith mentions in the talk in my previous [1], known as "hammer"[2]. It's very easy to use, and it has specific support for bit-level parsing of binary formats.
> numPersons 2
I highly recommend not using formats like this, because it's more complex than deterministic context-free. Using a length field requires that the parser remember state. It's also redundant information, creating the possibility of a miss-match between the number specified in "numPersons" and the actual number of rows.
A format that uses s-expressions would be safer and more easier to implement:
(ancestry
(ancestor
(person john "John Doe")
(person jane "Jane Doe")
)
)
The closing tag of the s-expression provides a similar benefit as the num* fields by simply marking the end of a complete record/field.> That's so trivial that I would never want to depend on a parser generator
Is it really "trivial"? Or is your parse that you write in 10 minutes accepting ambiguous or invalid data? Is it actually checking for all of the error conditions? For most real-world grammars, it's unlikely you will catch all of the subtle ambiguities, interactions, and edge cases.
The benefit of using a parser generator is that those entire classes of bugs are impossible.
> check (relational) integrity
In the trivial example you gave, you shouldn't have a grammar that requires checking relational integrity. In a more complex grammar, such checks would be the job of whatever is walking the AST that the parser returns. Parsers interpret syntax, not semantics.
> If I leave away the num* fields above, the parser would need one token of lookahead.
You need at least one token of lookahead anyway. Including the num* fields means the parser needs to remember and manage state.
Now, it seems to me that being easier to use and understand is an inherent advantage - I can't see how easier to understand doesn't make bugs easier to understand and so-forth.
Moreover, constructing a recursive descent parser involves understanding and transforming your language, an exercise which can also discover ambiguities and give a "deeper" understanding as well. It's hard for me to see Bison commands + code fragments as the ultimate in illumination concerning one's language's properties.
However, have you tried parser combinators? Parsec (a Haskell library) is really nice if it fits your grammar.
Here is one guy who simulated that in Python, also very nice:
* attoparsec remains the king of speed, generating parsers competitive in speed with C
* trifecta remains the king of error messages, generating gorgeous clang-style errors
* earley is a newcomer but deals with context-free grammars, while other parser combinatory are basically recursive descent parsers
* and good old alex+happy for direct yacc+bison equivalent
* I should probably mention that in certain simple cases you don't even need a parser combinator library to parse things. Just a good old `StateT (Text, r) [] ()` or similar can do wonders.
loop @a
...
endloop
means start the loop labeled a but loop
@a
...
endloop
means start a loop, the first statement of which refers to attribute a, but that this is the only use of labels in the language where these two cases are parsed differently...You just end up making a grammar with really weird rules about where newlines can or cannot be put, and comments that this should not be changed. Oh, and a BIG test suite.
Once you've dealt with the grammar then you'll only have bugs in the compiler and runtime semantics to emulate, and language implementations often have an exciting set of those.
Edit: this is actually explained much better in the article.
Incorrect. The choice is explicit. Ambiguity gone, period. If the order makes some of the branches unreachable, it can be easily statically proven. In practice this is more than enough and does not require nearly as much effort as all the other parsing approaches.
This has been used, quite famously, in standards conforming XML parsers which have some very ugly backtracking issues dealing with entities and entity references. More commonly, people who decide to add regular expression validation to their APIs are often surprised to discover that an attacker can take up all sorts of server time while the API is trying to validate a carefully crafted degenerate case message. Many regular expression libraries out there are NFA, including the ones built into some popular high-level language runtimes.
An NFA does not use backtracking - at least in a sensible implementation. The problem is that most implementors of RE engines prefer "obvious hands-on" implementation that uses backtracking instead of understating the elegant theory behind NFAs. Here is how to implement an NFA without using backtracking:
> https://swtch.com/~rsc/regexp/regexp1.html
Addendum: And it is also a bad idea to convert am NFA to an DFA for parsing because the number of necessary states can explode exponentially by this transformation.
Of course, backreferences and other stuff take you out of the realm of regular languages. Avoid these.
You can skirt this problem using a lazy DFA with a bounded cache. (i.e., See the third article in Cox's series.)
If you're going to implement this important feature in a sane way then at SOME point you're going to need to backtrack.
And there are plenty of "real world" regex engines in wide use that don't support backreferences.
I learned a lot from this. I did take compiler theory in college, but that was pretty academic (mostly Dragon Book), and more theory than practice. This is a good explanation of why lex/yacc is not enough.
As someone who had a technical but "not real CS" curriculum, I enjoyed Parr's "Language Implementation Patterns" book [0] because it illustrates how certain grammar-forms become recognizable code-patterns and control-flow.
Granted, it's definitely got a bent towards Parr's ANTLR project and the Java language, but I still found it made things "click" a lot better than my daunting lack of progress an old "Dragon Book" [1] which IIRC tended to float along with more mathy-notations and theory than concrete examples.
[0]: http://www.amazon.com/Language-Implementation-Patterns-Domai...
[1]: https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniq...
Oddly you would think that sacrificing non-determinism would really hurt the power of PEGs to express languages but there are languages that are not context free (eg, `a^nb^nc^n`) that can be written as a PEG.
And if you have a sufficiently smart compiler, it'll warn you about most of the practically important cases anyway. I wrote PEG parsers for dozens of different types of languages, and never ran into problems with an explicit choice order. This anti-PEG FUD should stop at once.
Favorite new trivia bit:
"C++ has an even more extreme version of this problem since type/variable disambiguation could require arbitrary amounts of template instantiation, and therefore just parsing C++ is technically undecidable (!!)"
I'm not sure if any exist, although some people have tried to write grammars for existing markup languages.
http://roopc.net/posts/2014/markdown-cfg/
https://github.com/asciidoctor/asciidoc-grammar-prototype
https://stackoverflow.com/questions/6178546/antlr-grammar-fo...
I have a few basic reasons why I now think parser generators are a mistake for my purpose: 1) It is hard to learn all the details of a particular parser generator that you need for a complex parsing project. 2) The mix of grammar and semantic actions one has to come up with is ugly and complex. 3) The output is both ugly and hard to debug.
The most complicated part of a compiler is not recognizing good input, put doing something with it. A hand-written recursive descent parser can be a thing of beauty and simplicity that increases the joy of working on the meat of the compiler, that is semantics!
http://www.cs.nott.ac.uk/~pszgmh/monparsing.pdf
What is more, these combinators can express context-sensitive grammars: https://www.cs.york.ac.uk/plasma/publications/pdf/partialpar... (page 5).
And, by tweaking combinators, you can arrive to the wonders of stream processing parsing without (mostly) space leaks: http://www.cse.chalmers.se/edu/year/2015/course/afp/Papers/p...
It is easy to add syntax error position reporting, also it is easy to add syntax error corrections. All this can be done in under a day.
For me it offers good things from both worlds - declarative specification of parser generators and easy modifications from "parse damn thing by hand".
I actually encountered one case where that approach shines incommensurably: supporting old languages like VHDL. VHDL fits every parser formalism almost without seams but still has one place where you cannot do things either efficiently or elegantly: character literals and attributes. 'a' is a character literal, a'a is an invocation of attribute a on the object a. The ambiguity is in the lexing level, needing feedback from parsing level. Usual parsing tools cannot do that good enough, with parsing combinators it is trivial.
Here's the PEG paper: http://www.brynosaurus.com/pub/lang/peg.pdf
In practice PEGs do not have an ambiguity problem, period. Stop this FUD!
Code is here, in fact:
https://github.com/Ravenbrook/mlworks/blob/master/src/parser...
Generating Good Syntax Errors http://research.swtch.com/yyerror
[1] https://buguroo.com/why-parser-generator-tools-are-mostly-us... .
Note that Go is also moving away from yacc:
https://www.reddit.com/r/golang/comments/46bd5h/ama_we_are_t...
I used Antlr3 to create a NLP parser for entering a calendar event. For iOS, the C runtime's parse tree source was many megabytes and difficult to debug directly. For Android, the Java runtime parse tree ran out of memory and had to be broken into smaller pieces. Haven't tried Antlr4.
Current workaround is to parse a document directly into a token tree. Instead of separate lever + parser, merged a tweaked BNF with regex. Memory stays rather small and can download a revised grammar without recompiling a new binary.
As for tool, the Antlr3 C runtime was very fiddly. On the forums, I saw one developer give up on porting their working Antlr2 C++ runtime to Antler's C runtime. This may have been due to C lacking exception handing, so had to implement backtracking another way. (Still, kudos to the volunteer who implemented the C runtime; in our case, it did make it into production.)
For really simple NLP parsing, one hack is combine an Island parser with an LL parser. This is essentially what Siri used several years ago (have no idea what it uses now).
https://groups.google.com/forum/#!searchin/golang-checkins/r...
From what I recall reading about the change, it was believed it would allow them more flexibility in the frontend, and they greatly preferred to write the parser in Go instead of yacc.
Also, at this point, they felt this would also make it easier for others to contribute improvements to the project.
Parser generators need to get much better before that will change.
Any time you take native objects/data and persist them, or marshal them, you need a parser -- or a parser library. That might mean reading some CSV, parsing some XML, reading some YAML, JSON or what-not.
Then there's configuration that does more than set some variables, like for Nginx, Apache (web server), etc.
One might want to have a short-hand for defining templates -- either for general meta-programming, or just to generate a layout-language (eg: html, css). If you're doing markdown (or markdown-like) processing, you might want to have some assurances that that's all that code can do -- generate html. Or you might want do meta-programming on some higher level, like generating interfaces for some java-beans based on a CSV structure. For more on meta-programming in Java, I recommend (the now slightly dated: http://www.amazon.com/Program-Generators-Java-Craig-Cleavela... ). It's a shame he didn't name it as he claims he considered in the foreword: "Program Generators for Fun and Profit!".
And finally there's "real" programming languages - full blown DSLs of some kind. Perhaps in an effort to represent some kind of business logic (eg: authorization based on group membership, roles and time of day) in a language that is "safe" -- has no side-effects.
[1] http://fishbowl.pastiche.org/2015/11/09/java_serialization_b...
http://blog.codeclimate.com/blog/2013/01/10/rails-remote-cod...
https://github.com/YorickPeterse/oga/blob/master/lib/oga/css...
https://github.com/YorickPeterse/oga/blob/master/lib/oga/xml...
https://github.com/YorickPeterse/oga/blob/master/lib/oga/xpa...