Executing ANTLR and Testing Recognizers

Here’s a simple grammar that recognizes phrases like hello parrt and hello world:

​ ​grammar​ Hello​;​ ​// Define a grammar called Hello​
​ r ​:​ ​'hello'​ ID ​;​ ​// match keyword hello followed by an identifier​
​ ID ​:​ ​[​a​-​z​]+​ ​;​ ​// match lower-case identifiers​
​ WS ​:​ ​[​ ​\​t​\​r​\​n​]+​ ​->​ skip ​;​ ​// skip spaces, tabs, newlines, \r (Windows)​

To keep things tidy, let’s put grammar file Hello.g4 in its own directory, such as /tmp/test. Then we can run ANTLR on it and compile the results.

​ ​$ ​​cd​​ ​​/tmp/test​
​ ​$ ​​# copy-n-paste Hello.g4 ...

Get The Definitive ANTLR 4 Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.