Complete newbie tips for ANTLR

19 January, 2011 § 1 Comment

I’m getting my feet wet with ANTLR as part of my compilers course that I’m taking this semester. ANTLR is what one may call a “compiler-compiler”: A tool that is used to create compilers. I’ve learned a couple things now about ANTLR and want to share them with others to help make your first ANTLR project a success.

First, I would highly recommend the tutorials recorded by Scott Stanchfield. Scott starts off the tutorials by showing what versions of Eclipse to download and what plugins you’ll want to use with Eclipse to make ANTLR development easier. He then moves on to explaining the ANTLR-generated code and building expression trees. I’ve watched three of the nine tutorials up to this point, and am planning on watching the rest of them shortly.

This is the code that I had after watching the first three tutorials:

grammar Sample;
options {  language = Java;}
@header {  package a.b.c;}
@lexer::header {  package a.b.c;}
 : 'program' IDENT '='
   ( constant | variable )*
   'end' IDENT '.'

: 'constant' IDENT ':' type ':=' expression ';'
: 'var' IDENT (',' IDENT)* ':' type ';'

: 'Integer'

: assignment

: IDENT ':=' expression ';'

| '(' expression ')'

: 'not'* term

: ('+' | '-')* negation

: unary (('*' | '/' | 'mod') unary)*

: mult (('+' | '-') mult)*

: add (('=' | '/=' | '<' | '<=' | '>=' | '>') add)*

: relation (('and' | 'or') relation)*

INTEGER : '0'..'9'+ ;
IDENT : ('a'..'z' | 'A'..'Z')('a'..'z' | 'A'..'Z' | '0'..'9')* ;
WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;} ;

I wanted to add code to the rules that I had written. At this point, I had rules for the parser and the lexer. After watching Tutorial 2, I learned that the code between the curly brackets was placed within the generated Java file. This means that you can place other code between the curly brackets, in addition to the “$channel = HIDDEN” that is shown above.

That is just a simple start of what I’ve got so far with the tutorials. Good luck learning ANTLR, it is a lot of fun to see it all in action.

Tagged: , ,

§ One Response to Complete newbie tips for ANTLR

  • A.J. says:

    Hey Hey Jared! ANTLR does look pretty cool in that will create expression trees easily. Though I bet for some complicated languages with complicated syntax rules that the next steps can be mighty difficult! I am really liking these updates on how your compliers course is going; keep us informed if you can!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Complete newbie tips for ANTLR at JAWS.