The Definitive ANTLR Reference
Joe Kauzlarich writes "Finally, someone has done us all the great service of publishing a
book about the second most well-known compiler compiler, Terence
Parr's Antlr, and it was written, moreover, by Parr himself and
published as part of the somewhat-usually-reliable Pragmatic Bookshelf
series. Take note, while it requires a JVM to run, Antlr is not just
for Java developers; it generates compilers in Python, Ruby, C, C++,
C# and Objective-C. Also note that this book is more than just an
elaborated man-page; it is also an excellent introduction to the
concepts of compiler and parser design." Keep reading for the rest of Joe's review.
The Definitive ANTLR Reference
author
Terrance Parr
pages
361
publisher
Pragmatic Bookshelf
rating
9
reviewer
Joe Kauzlarich
ISBN
978-0-9787392-5-6
summary
introduction to parser/compiler design using ANTLR
First off, I have no preference between Yacc-style parsers, JavaCC and
Antlr; I've never used Yacc, have used JavaCC in college and have
since played with Antlr and am just as ignorant in the use of them
all. The fundamental difference is that Antlr is a top-down LL(*)
(simply-put, variable-lookahead) parser generator while Yacc is a
bottom-up LR parser generator. JavaCC is also top-down, but employs a
different parsing strategy. The book describes the meanings of these
terms in simple detail.
I happen to have learned in my experience that good documentation for any of these products is hard to come by and difficult to follow, simply because the subject matter is obtuse and few, until now, have ventured to write expository literature to explain the myriad concepts to the non-academician. Of the three mentioned above, Antlr appears to be the more 'modern' and can also generate lexers from within the same grammar definition file, so the notions are integrated. Antlr also has a useful IDE called AntlrWorks with visualization features, causing grammar construction to be far simpler for a beginner.
That said, I don't wish to use this review to push Antlr over its alternatives, but only to press the point that this book serves not only to introduce Antlr to the average programmer, but the concepts of parser design as well. The concepts become necessary to understand while writing and debugging grammars, as not everything written in Backus-Naur Form will produce a working parser, and this holds true for any parser generator. Learning what works and what doesn't, as well as what workarounds are available, is key to becoming proficient in Antlr, Yacc or JavaCC. Once proficiency is acheived, you'll have the valuable skill of producing domain-specific languages on demand.
Terence Parr, as mentioned before, is not only the author and maintainer of Antlr, but he wrote the book as well. Antlr is on its long-awaited third version and has been maintained by Parr throughout the project's lifetime. He is a university professor and himself developed the path-breaking LL(*) parsing strategy employed by Antlr.
Parr begins with a one chapter background in computer language design before diving into a simple example of a parser for basic integer expressions. Part II is the meat of the book, describing various aspects of writing grammars for Antlr. Generally speaking, he covers the basic semantics of grammar writing, the many optimization, supplementary and 'workaround' options provided by Antlr, grammar actions and attributes, syntax trees, error reporting and related practical topics.
The third part, Understanding Predicated LL(*) Grammars, is the valuable 'textbook' portion of the book. It gives readers a short and comprehensible introduction to exactly what predicated-LL(*) means as well as a look at how competing parser generators work in contrast.
Both of the second and third parts are scattered with theoretical tidbits to help language designers better understand why grammars must work as they do. Those who can't pick their nose without a rudimentary theoretical overview of the subject can enjoy a few casual browsings through the book before even sitting in front of a computer. It works *almost* that well as a textbook, though it still doesn't approach such classics as Aho, et al's, Compilers: Principles, Techniques, and Tools (if you want to get seriously involved in compiler design). Take it for what it is though, as a chance to learn a tool of possible value without having to dig through old mailing lists and last-minute README's on the one hand, as was much the case a year ago, and on the other hand, devoting pain-staking class and study time to a lot of theory you won't find of practical value.
So I'll recommend this book on the basis that there's nothing else like it available; and don't wait until a project comes along that requires knowledge of compiler design, because there's a heck of a learning curve (I'm still on the very low end and I wrote a compiler in college). If you think compiler or parser design is interesting or may conceivably write a domain-specific language for your workplace, the Definitive Antlr Reference is not only a good place to start, but one of the only places to start short of signing up for a university course.
You can purchase The Definitive ANTLR Reference from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
I happen to have learned in my experience that good documentation for any of these products is hard to come by and difficult to follow, simply because the subject matter is obtuse and few, until now, have ventured to write expository literature to explain the myriad concepts to the non-academician. Of the three mentioned above, Antlr appears to be the more 'modern' and can also generate lexers from within the same grammar definition file, so the notions are integrated. Antlr also has a useful IDE called AntlrWorks with visualization features, causing grammar construction to be far simpler for a beginner.
That said, I don't wish to use this review to push Antlr over its alternatives, but only to press the point that this book serves not only to introduce Antlr to the average programmer, but the concepts of parser design as well. The concepts become necessary to understand while writing and debugging grammars, as not everything written in Backus-Naur Form will produce a working parser, and this holds true for any parser generator. Learning what works and what doesn't, as well as what workarounds are available, is key to becoming proficient in Antlr, Yacc or JavaCC. Once proficiency is acheived, you'll have the valuable skill of producing domain-specific languages on demand.
Terence Parr, as mentioned before, is not only the author and maintainer of Antlr, but he wrote the book as well. Antlr is on its long-awaited third version and has been maintained by Parr throughout the project's lifetime. He is a university professor and himself developed the path-breaking LL(*) parsing strategy employed by Antlr.
Parr begins with a one chapter background in computer language design before diving into a simple example of a parser for basic integer expressions. Part II is the meat of the book, describing various aspects of writing grammars for Antlr. Generally speaking, he covers the basic semantics of grammar writing, the many optimization, supplementary and 'workaround' options provided by Antlr, grammar actions and attributes, syntax trees, error reporting and related practical topics.
The third part, Understanding Predicated LL(*) Grammars, is the valuable 'textbook' portion of the book. It gives readers a short and comprehensible introduction to exactly what predicated-LL(*) means as well as a look at how competing parser generators work in contrast.
Both of the second and third parts are scattered with theoretical tidbits to help language designers better understand why grammars must work as they do. Those who can't pick their nose without a rudimentary theoretical overview of the subject can enjoy a few casual browsings through the book before even sitting in front of a computer. It works *almost* that well as a textbook, though it still doesn't approach such classics as Aho, et al's, Compilers: Principles, Techniques, and Tools (if you want to get seriously involved in compiler design). Take it for what it is though, as a chance to learn a tool of possible value without having to dig through old mailing lists and last-minute README's on the one hand, as was much the case a year ago, and on the other hand, devoting pain-staking class and study time to a lot of theory you won't find of practical value.
So I'll recommend this book on the basis that there's nothing else like it available; and don't wait until a project comes along that requires knowledge of compiler design, because there's a heck of a learning curve (I'm still on the very low end and I wrote a compiler in college). If you think compiler or parser design is interesting or may conceivably write a domain-specific language for your workplace, the Definitive Antlr Reference is not only a good place to start, but one of the only places to start short of signing up for a university course.
You can purchase The Definitive ANTLR Reference from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
Why is it called ANTLR when it's an LL parser? Personally I prefer LR parsers, even though you can't parse Java with it (as far as I know).
“Common sense is not so common.” — Voltaire
I recently ran across this problem at my job: we maintain compilers for several(!) in-house languages, and I recently re-wrote the one for the most simple of them, changing it from a collection of three separate utilities (the most complicated of which was written in FORTRAN, which is generally horrible for manipulating text) into a Lex/Yacc/C (or rather, Flex/Bison/C) compiler.
I chose Lex and Yacc not because they were good, but because they're (in my opinion) very likely to be around 50 years from now. Are there any other compiler generators (such as possibly ANTLR) that might also meet this criteria, and would have been a better choice?
"[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz
If you think compiler or parser design is interesting or may conceivably write a domain-specific language for your workplace, the Definitive Antlr Reference is not only a good place to start, but one of the only places to start short of signing up for a university course.
I am currently reading Programming Language Pragmatics. It's pretty good I think, but then, I have nothing to compare with. I'll probably pick up the Antlr book too.
Being bitter is drinking poison and hoping someone else will die
You did better than I did, I got confused at "Kauzlarich".
Nerd rage is the funniest rage.
Antlr? Never heard of it. Now Lex/YACC, I have.
When I last used ANTLR there was an issue where I could not use the latest version because some vendor's jar file happened to be using an older version of ANTLR. Some other yacc-type programs generate all source code supplied with a class prefix of your choice and do not use a common library. This allows combining many parsers in the same program - even with different versions of the parser generator. Has ANTLR followed suit yet? The workaround using class loaders is a pain.
One thing I really don't like is that a ANTLR grammar is limited to a single target language. You can use the same grammar to produce both a Java and C# parser. You need to make a few tedious changes to the grammar file.
We currently have a grammar that needs to be preprocessed a bit before we feed it to ANTLR to produce the parser. It's only about 5 lines in the grammar that need to be changed.
I had the (miss?)opportunity to start doing compilers with Yacc, Lex. It's easy to make mistakes and you're bound to C.
ANTLR takes some weight by letting you pick a language in which it will generate code. It also has a defaul implementation for an AST and as of a few weeks back you can use BNF notation to make changes to ASTs too (this feature is not covered in the book).
Having the book close while writing new compilers was of great help. It's only useful for your first compilers, you tend to use from the start many of the features ANTLR gives you, and you learn them by heart.
The book can certainly be improved (I know I had trouble understanding in some corner cases why ANTLR worked the way it did), but compared to the information available on the net only, it's really worth having close.
..problem is, you can't really do anything non-trivial in ANTLR 3.0 without buying the book.
They've drastically reduced the freely available documentation on their web page, so you are essentially forced to buy it.
"I'm an old-fashioned type of guy. I worship the Sun and Moon as gods. And fear them."
I would encourage anyone who is interested in parsing or ANTLR to follow my project Gazelle. It is intended to be a next-gen parsing framework that builds on the ideas set forth in ANTLR but packages them in a significantly different way, which offers a lot of benefits (which I list in detail on the website).
The primary thing I am trying to deliver is reusability of parsers. The open-source community should be able to cooperate to write canonical parsers for all popular languages, but this goal is hampered by the fact that almost all parsing tools (ANTLR included) encourages you to write non-reusable grammars by virtue of the fact that you embed actions into the grammar.
Gazelle also takes a interpreter+JIT approach instead of emitting code in an imperative language. So for example, if you want a really fast HTTP parser from Ruby (which is precisely the raison d'etre for Mongrel), you can use the HTTP Gazelle parser from Ruby, but since the parsing is actually performed by the interpreter+JIT (written in C), you get extremely fast parsing without writing a line of C.
Gazelle is still very immature and not ready for people to try out, but I would encourage anyone who's interested to follow the Gazelle category on my blog.
You can also check out:
- the current draft of the manual, which will give you a better idea of the specifics of where I'm going with this.
- a graphical dump of the grammar for JSON, which the current development code is capable of generating.
ANTLR - Am Now The Laziest Reader. I didn't read this article. Guess that makes me the average slashdotter.
I hate my uncle
but I love my antlrs
'cause antlrs are a moose's best friend!
The C# parser here: www.temporal-wave.com has an online C# parser running in Java from ANTLR. There are also Java parsers in C# from ANTLR output and Python parsers in C and C parsers in ActionScript and err now I am totally confused....
I've used both ANTLR from PCCTS 1.3 and Bison pretty extensively. We have multiple bison and ANTLR grammars in our product. I like ANTLR generally better than bison. The extended BNF is really useful. And when you get used to writing top-down grammars, they are not so odd. In fact, with eBNF notation, alot of the peculiarity is taken away.
I also like Sorcerer. In PCCTS 1.3, Sorcerer is a kind of tree traversal grammar tool. You create ASTs, with ANTLR, and Sorcerer creates a program which will traverse them, and call action routines where you specify. It's really pretty neat.
I'm thinking about something else though. I'm thinking we should really think about programming with grammars more than we do. Say, for example, you have a user interface of some kind. It gets certain events, its state changes, and it reacts to the environment. A good fraction of the set of state changes can be captured with some kind of finite state machine. But a context free grammar is equivalent to a finite state machine with a pushdown list to hold context. So, it seems very likely to me that a good way to build user interfaces is to somehow compose grammars. The tokens are events, and the action routines are the non-FSM state changes.
So, why is this interesting in this discussion? Well, ANTLR from PCCTS 1.3 is a recursive descent parser, and YACC/Bison are bottom up parsers. This means that the pushdown list for ANTLR is the execution stack, and the pushdown list for YACC/Bison is in data space. It's hard to see how one would maintain multiple ANTLR-style automata concurrently, but that's what you want to do for this style of programming.
Generally YACC/Bison pushdown lists and other parsing data are kept in global variables, but there is a way to make Bison generate C++ useable grammars where the parsing data are saved in a heap allocated object. This means they have a fixed size, which may be a problem. But it would not take a lot of work to change the parsing algorithm for Bison to make the pushdown list a linked list, and that might make things easier.
So, in short, I think it's pretty interesting to look at parsing, even if you're not writing compilers.
Some years ago, I wrote an interpretting parser, which simply loads a grammer (in extended BNF) and next parses a string according to it. The lexical analyses needs to be hand coded, but examples for the most common literals are included. The interesting bit is that the parser controls the lexer, which simply gives you context sensitive lexing. The whole thing is rather small. The nice thing is that it doesn't generate code. I once tried to make it generate code, but the produced code was actually slower than the interpretting version. (Probably has to do with the fact that the interpretter fits in the primary processor cache.) The parser uses back-tracking, but uses some smart caching, making it very fast. The whole interpretting parser consists of a single C file of about 100 Kbyte and can be found here.
sure, we skimped on the java implementation.. but it was able to handle simple functions like factorial, and sorting algorithm, Objects.. I didnt manage to get inheritance to work, but that's my goof.
Storm
Yes indeed,
A fine single malt that Kauzlarich
Antlr 3.0 has been invaluable for Drools, can't wait for 3.1 which has better performance.
We did an interview with Ter and put it on our blog
http://blog.athico.com/2007/06/interview-with-antlr-30-author-terrence.html
Mark
http://blog.athico.com blog
http://labs.jboss.org/drools homepage
Is the saying "Painstaking" hyphenated as Pain-staking or Pains-taking?
I always thought of it as Pains-taking.
IE:
I have taken great pains to get this right.
Just curious if i have been using it correctly.
(stolen from DaBum) I am dyslexia of borg - your ass will be laminated.
About seven years ago, I needed to write a DSL. I used ANTLR to do it, and it was a pleasure - even though I didn't know Java! I wrote out the grammar, ANTLR wrote all the code for me, everyone was happy. And that was long before there was anything as amazing as ANTLRWorks.
But lately I've been wondering: Do we really need parser generators anymore? In Ruby, if you're writing a DSL, you usually implement it in terms of the Ruby language itself. I imagine that's true for other dynamic languages too. Look at Rails, or Adhearsion, or RSpec: They're DSLs, but they're valid Ruby.
And if you're not writing your own DSL, but parsing a "well-known" format, parsers have a downside there too: They're picky. If I need to scrape a bit of data out of an XHTML page, I'm better off *not* using an XML parser; it'll choke. It's usually easier to use a regex, waste some theoretical CPU, and throw away the bits I don't need.
So, parser lovers: Why do we still need cool tools like ANTLR? What do they provide that crude regular expressions don't?
No, it's not obtuse, it's obscure.
Obtuse is the antonym of acute. In geometry, an obtuse angle is one greater than 90 degrees. Metaphorically, an obtuse person is one who is not sharp.
Obscure, on the other hand, from the Latin word for "dark", means difficult to perceive or understand.
Your god may be dead, but mine aren't!
e : (e*)
Lisp is particularly suited to this sort of thing.
Here's an example http://bc.tech.coop/blog/050711.html
Crude regular expressions only work for crude regular languages. You mention parsing XHTML, but what evidence do we have that regex don't choke on html just as often as XML parsers? HTML is complicated and often broken enough in distribution that I'm not sure you can define a universal accepted "well formed-ness" checker. And it's not that regex waste CPU -- you can implement them in time linear to the input, it's that they break quite easily if there's any variety in your input. I recall someone complaining that the Wordpress XML parser was regex written to handle their own output, and when someone wanted to migrate from one to the other, their valid XML didn't work because it assumed a certain order of elements.
For most XML doctypes, I think it's useful to have a generated parser available. If you want your input to be something akin to XML and you want to accept as many files as possible, grammars and parsers are your only valid option.
I Browse at +4 Flamebait
Open Source Sysadmin
..I would have trimmed my ANTLRs.
Regular expressions cannot handle recursive grammars.
On a project I was on, I needed to parse 50+ COBOL copybooks in .NET so that we could use those data definitions to whittle down a 600MB flat file full of nightly data for a data warehouse.
.NET with it instead of Java, there's a reserved circle in hell for that.
I tried ANTLR, and I wound up abandoning it. I wanted ANTLR to work - I really thought it seemed to be the best and most mature solution, but the documentation is ABYSMAL. And if you want to use
I'm sure if I'd had proper documentation, I could have managed it. I have a CS degree and took a 400 level automata class as part of my curriculum, so I'm no feather weight on this topic. Heck, I've even used this in a past life. But, I still was at a loss as to how to even begin with ANTLR and C#.
I found Gold Parser, and I was done with 151 commented lines in my grammar file, 148 lines of generated C# code in a constants file, and less than 500 lines of business logic to actually deal with the parsed copybook to do what we needed to do with it. The whole development effort was mere days, and let me quickly get out of the weeds and back to solving the real business problem.
Recently, I saw this ANTLR reference discarded on a shelf in Half Price Books, and just had to pick it up. I thought, maybe this would have gotten me there. Alas, the book is not even close to a reasonable reference. Moving from tokenizers and Regular Expressions to full-fledged CFGs is not a layman's topic, but there's not much help to be gleaned from the arcane drivel that comes from Mr. Parr's book on his already overly complicated application. If you're interested in theory and wallowing in the mire of acedemia, then this is the book for you. But, if you have a working understanding of the topic and just want to get the blasted tool to work, the best advice I have is to stay far, far away. At least, that is, until someone other than Parr himself sets forth a reasonable guide to this ANTLR'ed beast.
I found this to be much the same with Parr's StringTemplate project. After trying to figure it out from the limited documentation, I found it less painful to just dredge up NVelocity from its hidden location at Castle Project, fish for the necessary dlls, throw away the rind (who uses Castle anyway???) and happily went about my merry way.
As in, "I am taking pains to see that such-and-such is done to exacting standards..."
> the second most well-known compiler compiler, Terence Parr's Antlr
I was pretty sure the two best-known compiler compilers were yacc and bison, though I couldn't have told you which one is the most well-known and which one the second-most well-known these days. (I know which is older and which is newer... but that isn't necessarily the same thing.) I've never heard of Terence Parr's Antlr before. (I _have_ heard of PGE, but only because I read Perl-related news occasionally.)
Cut that out, or I will ship you to Norilsk in a box.
I found the STG library extremely useful. I recently replaced an ANTLR based compiler with a JParsec based one, and STG handled the code generation phase with aplomb. It's a little inconsistent at times, but still saved a ton of work.
JParsec is pretty damn cool too. Write your grammars in as re-usable, refactorable code, using your favourite IDE, rather than using an external file format. It's based on Parsec, a haskell Parser Combinator, so supports LL(k), LL(*), as well as combining lexical and syntax analysis (so tokenizing can be done at parse time), making context sensitive grammars possible.
We used JParsec because some of our tokens contained special characters e.g. A+, but that's another story.
OK, I did, but it's not done running yet...
I bought and read significant chunks of this book. It is not only an excellent reference for understanding and deploying Antlr, but a fun read for those interested in learning more about the basics of parsing, grammars, and compiler compilers. I will admit to some bias as I have known Terence since his PhD days at Purdue, when he began working on the early versions of Antlr. I've watched the software progress and mature over the years into the highly refined tool Antlr has become, and I am sure it will continue to get better.
How is ANTLR better than YACC? Since the reviewer isn't familiar with the grand-daddy of compiler-compiler tools, how can one take the review seriously? As for the statement "there's nothing else like it out there", that's just plain fiction - there are a number of compiler-compiler books out there, especially dealing with YACC.
-- Ed Carp, N7EKG erc@pobox.com PGP KeyID: 0x0BD32C9B What I'm up to: http://intuitives.mine.nu
A nice review! I will have to check out this book-- I like ANTRL, and all things parsing in general.
Folks in C++ land who are considering lex and yacc may wish to explore Boost.Spirit. The latest version is especially interesting.