12 ms·
LL and LR in Context: Why Parsing Tools Are Hard (2013)
- musesum 11y agoHas anyone done a comparison of memory footprints for parsers? Say, Antlr vs Bison vs ???. 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.
- Terr_ 11y agoAre you sure the issue was with the tool and not the language/grammar?
- musesum 11y agoWas probably a bit of both. Using a LL parser for NLP is an odd fit. The problem was that the n-gram parsers had a fairly large file footprint. So, paging from memory would be slow and consume battery. 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).
- beat 11y agoWoohoo, real computer science! 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.
- deleted 11y ago[deleted]
- Drup 11y ago> While rolling your own parser will free you from ever getting error messages from your parser generator, it will also keep you from learning about ambiguities you may be inadvertently designing into your language. 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. [1]: http://gallium.inria.fr/~fpottier/menhir/ http://gallium.inria.fr/~fpottier/menhir/
- ufo 11y agoMenhir is really amazing. Being able to use the high-level rules to parse lists, without needing to use recursion, was super nice. It also gives decent error messages when it detects an ambiguity.
- aardvark179 11y agoYeah. Reverse engineering a grammar you can give to a parser generator from a hand crafted parser is a fun and occasionally horrifying experience. There's nothing quite like discovering that 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...
- comex 11y agoOut of curiosity, is that a real example from some language?
- aardvark179 11y agoSlightly altered to protect the guilty, but yes, this is a real example. There are few things more frustrating when converting hand written recursive descent parsers into proper grammars than having to insert arbitrary rules about where newlines can or cannot be. You generally can't change the language if there's production code out there (and if there isn't, why are reverse engineering a grammar?) because changing the semantics will lead to more confusion. 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.
- redbeard0x0a 11y agoAnother note, recently Go stopped using yacc(bison).
- biomcgary 11y agoI would appreciate a reference with an explanation about why that has changed. Is it to support code transformation?
- koenigdavidmj 11y agoThey recently did a mostly-automated rewrite of the compiler from C to Go. I expect it was easier to hand-rewrite the parser instead of writing a Go backend for yacc or converting the C parser that yacc generated.
- nordsieck 11y agoIt looks like there has been a version of yacc in the go source tree (that works with go, not c) for at least 11 months. https://github.com/golang/go/tree/master/src/cmd/yacc https://github.com/golang/go/tree/master/src/cmd/yacc
- gilgoomesh 11y agoHandwritten recursive descent parsers offer much more control than the output of a parser generator. Most major C/C++ compiler front-ends do this.
- vidarh 11y agoIn fact, very few production compilers use generated parsers - sooner or later they tend to end up with hand-written parsers for one reason or other. Particularly down to error reporting. Parser generators need to get much better before that will change.
- nostrademons 11y agoI wonder if it might have something to do with error reporting. The usual way to handle error messages in a CFG is to make a superset of the grammar that contains all likely mistakes, along with custom error messages for each one. As you can imagine, the resulting grammars get pretty hairy. You also have more information available for reporting & recovery with a hand-written parser: think, for example, of how Clang can spell-correct mistyped keywords, something that's not possible without the ability to interpret an identifier as a keyword if it happens to be a certain edit-distance off.
- nanolith 11y agoSomething interesting that isn't covered in this blog entry but is relevant to many of us is the importance of deterministic parsers for DOS / DDOS prevention. APIs that make use of parsers, be they regular expression parsers, or parsers for more complex grammars such as CFGs, can be abused if the underlying parser is nondeterministic. Reducing a parser to a DFA (deterministic finite automaton) provides it with measurable performance per character parsed. If an NFA (non-deterministic finite automaton) is used instead, then an attacker can abuse backtracking to increase parse time, often exponentially. 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.
- wolfgke 11y ago> Reducing a parser to a DFA (deterministic finite automaton) provides it with measurable performance per character parsed. If an NFA (non-deterministic finite automaton) is used instead, then an attacker can abuse backtracking to increase parse time, often exponentially. 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 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.
- deleted 11y ago[deleted]
- amalcon 11y agoThere are still pathological cases for NFAs: they are just quadratic in runtime and linear in (additional) storage, instead of exponential in runtime. That's frequently good enough, but sometimes you really want the linear runtime and constant memory usage of a DFA.
- Terr_ 11y ago> Terence Parr, author of ANTLR, often uses the metaphor of parsing as a maze 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-Domain-Specific-Programming/dp/193435645X/ http://www.amazon.com/Language-Implementation-Patterns-Domai... [1]: https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools#First_edition https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniq...
- johnbender 11y agoIn many cases trading in non-deterministic choice for deterministic choice (ie, parsing expression grammars) makes reasoning about and writing grammars much easier. For example, in the case of the arithmetic expressions grammar the rules should work as-is to get precedence. 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.
- fiatjaf 11y agoFor what do people use parser generators, besides writing new programming languages? I'm very curious to know about the use cases.
- e12e 11y agoThe sibling comment alludes to parsing calendar events (possibly .ical files). In general you need it for any kind of (de)serialization -- and as the recent java deserialization bug[1] (along with similar bugs in python, ruby) illustrates -- even in a mature language, "common practice" might not be "best practice" (everyone should've known that the various uses of blind deserialization was a bad idea -- but that doesn't really matter after the fact -- lots of high-profile libraries were completely broken). So "just use a library" might not be possible. 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-Cleaveland/dp/0130258784 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_bug/ http://fishbowl.pastiche.org/2015/11/09/java_serialization_b... http://blog.codeclimate.com/blog/2013/01/10/rails-remote-code-execution-vulnerability-explained/ http://blog.codeclimate.com/blog/2013/01/10/rails-remote-cod...
- Blackthorn 11y agoThey should be used anywhere you receive input for a defined protocol, rather than writing your own ad-hoc implementation. Security is much, much better that way.
- yanowitz 11y agoThis is a great article (I haven't written a compiler in years but was still able to follow along) that can easily suck up an evening of descending his explanatory links. That's a good thing. 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 (!!)"
- atomicbeanie 11y agoI think the tools are challenging, but it is soooo refreshing to have tools that don't pass the complexity on to the user. The parser library that has done this for me is https://github.com/engelberg/instaparse https://github.com/engelberg/instaparse. Using Instaparse is downright liberating. BNF in, parser out. Done.
- lucio 11y agoI believe PEGS are a better, modern approach to parsing. PEGS are only mentioned in the article, with no links. Here's the PEG paper: http://www.brynosaurus.com/pub/lang/peg.pdf http://www.brynosaurus.com/pub/lang/peg.pdf
- petermonsson 11y agoThe article mentions PEG in good detail and notes the ambiguity problems. Can you guide me on how those can be resolved with PEG?
- sklogic 11y agoAll such articles are always mumbling about "ambiguity problems", and never cares to provide even a marginally real world example of such. In practice PEGs do not have an ambiguity problem, period. Stop this FUD!
- EdiX 11y ago> some notable language implementations do use Bison (like Ruby, PHP, and Go) Note that Go is also moving away from yacc: https://www.reddit.com/r/golang/comments/46bd5h/ama_we_are_the_go_contributors_ask_us_anything/d03zx6f https://www.reddit.com/r/golang/comments/46bd5h/ama_we_are_t...
- geromek 11y agoExcellent article, it explains pretty much the same (but with much more mathematical detail) as the article I wrote some months ago about why parser generator tools are mostly useless [1] . [1] https://buguroo.com/why-parser-generator-tools-are-mostly-useless-in-static-analysis https://buguroo.com/why-parser-generator-tools-are-mostly-us... .
- sklogic 11y agoI don't get all these attacks on PEG being "ambiguous". This is a feature, and it is great once you get it. 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.
- qznc 11y ago"Error messages" is the usual argument I hear. The article does not address this. I would appreciate an article, why parser generators can or cannot provide error messages on par with handwritten parsers.
- haberman 11y agoGood point. I have heard this too and I don't have a deep answer to this question. Maybe someday I'll get to the bottom of it and write a follow-up article. (Article author here).
- user51442 11y agoYears ago I worked on an SML parser that used LR tables, on errors (ie. with no valid transition) it would try to find a symbol to insert/delete/modify that would allow parsing to continue. It dealt reasonably well with simple errors, though ML syntax is a bit flexible - function application is juxtaposition and it has user-defined infix operators (to deal with them, the parser would resolve reduce-reduce and reduce-shift conflicts dynamically by calling a function at runtime). Code is here, in fact: https://github.com/Ravenbrook/mlworks/blob/master/src/parser/_LRparser.sml https://github.com/Ravenbrook/mlworks/blob/master/src/parser...
- ericbb 11y agoHere's one that might interest you. Generating Good Syntax Errors http://research.swtch.com/yyerror http://research.swtch.com/yyerror
- alexk7 11y agoI am working on a compiler for my new language. I went from learning about Yacc at the university (reaction: disgust) to discovering PEG (reaction: I should build my own parser generator!) to wisdom (reaction: just write the damn thing by hand and be done with it!) 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!
- thesz 11y agoParser combinators for lazy streams can be written as recursive descent and perform as, more or less, generalized LR parsing (exploring all tree branches "simultaneously"). http://www.cs.nott.ac.uk/~pszgmh/monparsing.pdf 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/partialparse.pdf 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/parser-claessen.pdf 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.
- dfox 11y agoThe article mentions that PHP uses bison for it's parser, which is true. After looking through the flex and bison grammar files in PHP source some time back I would say that it's perfect example of why you don't want to use parser generators for that.
- bariumbitmap 11y agoI don't know of any light-weight markup language that are intentionally designed to be context-free and unambiguous. I wish I did. 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/ http://roopc.net/posts/2014/markdown-cfg/ https://github.com/asciidoctor/asciidoc-grammar-prototype https://github.com/asciidoctor/asciidoc-grammar-prototype https://stackoverflow.com/questions/6178546/antlr-grammar-for-restructuredtext-rule-priorities https://stackoverflow.com/questions/6178546/antlr-grammar-fo... https://www.mediawiki.org/wiki/Markup_spec https://www.mediawiki.org/wiki/Markup_spec
- nielsbot 11y agoSeems like bison does not support running user-defined code to handle things like C's declaration vs statement problem. Is that true? Otherwise seems like Bison covers all the problems mentioned in the article.
- nielsbot 11y agoAlso, interested in how well Top Down Operator Precedence works with real-world languages: http://javascript.crockford.com/tdop/tdop.html http://javascript.crockford.com/tdop/tdop.html