SlideShare a Scribd company logo
ANTLR 4
Homepage: http:/
/www.antlr4.org
The Deļ¬nitive ANTLR 4 Reference:
http:/
/pragprog.com/book/tpantlr2/the-deļ¬nitive-
antlr-4-reference
MEET ANTLR
ANTLR is written in Java - so installing it is a
matter of downloading the latest jar, such as
antlr-4.0-complete.jar
For syntax diagrams of grammar rules, syntax
highlighting of ANTLR 4 grammars, etc, use the
ANTLRWorks 2 or ANTRLWorks 2 Netbeans plugin.
http:/
/tunnelvisionlabs.com/products/demo/
antlrworks
ANTLR (ANother Tool for Language Recognition) is a
powerful parser generator for translating structured
text.
It's widely used to build language related tools.
From a grammar, ANTLR generates a parser that can
build and walk parse trees.
What is ANTLR?
Terence Parr is the maniac behind ANTLR and has
been working on language tools since 1989. He is a
professor of computer science at the University of
San Francisco.
Twitter search uses for example ANTLR for query
parsing.
Create aliases for the ANTLR Tool, and TestRig.
$ alias antlr4='java -jar /usr/local/lib/antlr-4.0-complete.jar'
$ alias grun='java org.antlr.v4.runtime.misc.TestRig'
Getting Started
Hello.g4
/
/ Deļ¬ne a grammar called Hello
grammar Hello;
r : 'hello' ID ; /
/ match keyword hello followed by an identiļ¬er
ID : [a-z]+ ; /
/ match lower-case identiļ¬ers
WS : [ trn]+ -> skip ; /
/ skip spaces, tabs, newlines
Then run ANTLR the tool on it:
$ antlr4 Hello.g4
$ javac Hello*.java
Now test it:
$ grun Hello r -tree
hello brink
^D
(r hello brink)
A First Example
$ grun Hello r -gui
hello brink
^D
This pops up a dialog box showing that rule r matched keyword hello followed by
the identiļ¬er brink.
THE BIG PICTURE
Tokenizing:
The process of grouping characters into words or
symbols (tokens) is called lexical analysis or simply
tokenizing.
We call a program that tokenizes the input a lexer.
The lexer group related tokens into token classes, or
token types, such as INT, ID, FLOAT, etc.
Tokens consist of at least two pieces of information: the
token type and the text matched for that token by the
lexer.
The parser feeds off of the tokens to recognize the
sentence structure.
By default, ANTLR-generated parsers build a parse
tree that records how the parse recognized the input
sentence.
By producing a parse tree, a parser delivers a handy
data structure to be used by the rest of the language
translation application.
Trees are easy to process in subsequent steps and are
well understood by programmers.
Better yet, the parser can generate parse trees
automatically.
The ANTLR tool generates recursive-descent parsers
from grammar rules.
Recursive-descent parsers are really just a collection
of recursive methods, one per rule.
The descent term refers to the fact that parsing
begins at the root of a parse tree and proceeds
toward the leaves (tokens).
To get an idea of what recursive-descent parsers look
like, next some (slightly cleaned up) methods that ANTLR
generates from grammar rules:
assign : ID '=' expr ';' ; /
/ match an assignment statement like "sp = 100;"
/
/ assign : ID '=' expr ';' ;
void assign() { /
/ method generated from rule assign
match(ID); /
/ compare ID to current input symbol then consume
match('=');
expr(); /
/ match an expression by calling expr()
match(';');
}
/** Match any kind of statement starting at the current input position */
stat: assign /
/ First alternative ('|' is alternative separator)
| ifstat /
/ Second alternative
| whilestat
...
;
The parser will generate:
void stat() {
switch ( Ā«current input tokenĀ» ) {
CASE ID : assign(); break;
CASE IF : ifstat(); break; /
/ IF is token type for keyword 'if'
CASE WHILE : whilestat(); break;
...
default : Ā«raise no viable alternative exceptionĀ»
}
}
In the example on the previous slide:
Method stat() has to make a parsing decision or
prediction by examining the next input token.
Parsing decisions predict which alternative will be
successful.
In this case, seeing a WHILE keyword predicts the
third alternative of rule().
A lookahead token is any token that the parser sniffs
before matching and consuming it.
Sometimes, the parser needs lots of lookahead tokens
to predict which alternative will succeed. ANTLR
silently handles all of this for you.
Ambiguous Grammars
stat: ID '=' expr ';' /
/ match an assignment; can match "f();"
| ID '=' expr ';' /
/ oops! an exact duplicate of previous alternative
;
expr: INT ;
stat: expr ';' /
/ expression statement
| ID '(' ')' ';' /
/ function call statement
;
expr: ID '(' ')'
| INT
;
ANTLR resolves the ambiguity by choosing the ļ¬rst alternative involved in the decision.
Ambiguities can occur in the lexer as well as the parser.
ANTLR resolves lexical ambiguities by matching the input string to the rule
speciļ¬ed ļ¬rst in the grammar.
BEGIN : 'begin' ; /
/ match b-e-g-i-n sequence; ambiguity resolves to BEGIN
ID : [a-z]+ ; /
/ match one or more of any lowercase letter
Building Language Applications Using Parse Trees
Lexers process characters and pass tokens to the parser, which in turn checks syntax
and creates a parse tree.
The corresponding ANTLR classes are CharStream, Lexer, Token, Parser, and ParseTree.
The ā€œpipeā€ connecting the lexer and parser is called a TokenStream.
ANTLR uses context objects which knows the start and stop tokens for a
recognized phrase and provides access to all of the elements of that phrase.
For example, AssignContext provides methods ID() and expr() to access the
identiļ¬er node and expression subtree.
Parse-Tree Listeners and Visitors
By default, ANTLR generates a parse-tree listener interface that responds to
events triggered by the built-in tree walker.
To walk a tree and trigger calls into a listener, ANTLRā€™s runtime provides the class
ParseTreeWalker.
To make a language application, we write a ParseTreeListener.
The beauty of the listener mechanism is that itā€™s all automatic. We donā€™t have to
write a parse-tree walker, and our listener methods donā€™t have to explicitly visit
their children.
ParseTreeWalker call sequence
Parse-Tree Visitors
There are situations, however, where we want to control the walk itself, explicitly
calling methods to visit children.
Option -visitor asks ANTLR to generate a visitor interface from a grammar with a visit
method per rule.
ParseTree tree = ... ; /
/ tree is result of parsing
MyVisitor v = new MyVisitor();
v.visit(tree);
A STATER ANTLR PROJECT
Letā€™s build a grammar to recognize integers in, possibly nested, curly braces like
{1, 2, 3} and {1, {2, 3}, 4}.
grammar ArrayInit;
/** A rule called init that matches comma-separated values between {...}. */
init : '{' value (',' value)* '}' ; /
/ must match at least one value
/** A value can be either a nested array/struct or a simple integer (INT) */
value : init | INT;
/
/ parser rules start with lowercase letters, lexer rules with uppercase
INT : [0-9]+ ; /
/ Deļ¬ne token INT as one or more digits
WS : [ trn]+ -> skip ; /
/ Deļ¬ne whitespace rule, toss it out
From the grammar ArrayInit.g4, ANTLR generates the following ļ¬les:
ArrayInitParser.java This ļ¬le contains the parser class deļ¬nition speciļ¬c to
grammar ArrayInit that recognizes our array language syntax.
ArrayInitLexer.java ANTLR automatically extracts a separate parser and lexer
speciļ¬cation from our grammar.
ArrayInit.tokens ANTLR assigns a token type number to each token we deļ¬ne and
stores these values in this ļ¬le.
ArrayInitListener.java, ArrayInitBaseListener.java By default, ANTLR parsers build
a tree from the input. By walking that tree, a tree walker can ļ¬re
ā€œeventsā€ (callbacks) to a listener object that we provide.
ArrayInitListener is the interface that describes the callbacks we can implement.
ArrayInitBaseListener is a set of empty default implementations.
Brink-Van-der-Merwes-MacBook-Pro:antlr_crap brink$ grun ArrayInit init -gui
{1,{2,3},4}
Integrating a Generated Parser into a Java Program
/
/ import ANTLR's runtime libraries
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class Test {
public static void main(String[] args) throws Exception {
/
/ create a CharStream that reads from standard input
ANTLRInputStream input = new ANTLRInputStream(System.in);
/
/ create a lexer that feeds off of input CharStream
ArrayInitLexer lexer = new ArrayInitLexer(input);
/
/ create a buffer of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
/
/ create a parser that feeds off the tokens buffer
ArrayInitParser parser = new ArrayInitParser(tokens);
ParseTree tree = parser.init(); /
/ begin parsing at init rule
System.out.println(tree.toStringTree(parser)); /
/ print LISP-style tree
}
}
Building a Language Application using ArrayInitBaseListener
/** Convert short array inits like {1,2,3} to "u0001u0002u0003" */
public class ShortToUnicodeString extends ArrayInitBaseListener {
/** Translate { to " */
@Override
public void enterInit(ArrayInitParser.InitContext ctx) {System.out.print(' " '); }
/** Translate } to " */
@Override
public void exitInit(ArrayInitParser.InitContext ctx) {System.out.print(' " '); }
/** Convert short array inits like {1,2,3} to "u0001u0002u0003" */
@Override
public void enterValue(ArrayInitParser.ValueContext ctx) {
/
/ Assumes no nested array initializers
int value = Integer.valueOf(ctx.INT().getText());
System.out.printf("u%04x", value); }
}
}
Driver program for ArrayInitBaseListener
public class Translate {
public static void main(String[] args) throws Exception {
/
/ create a CharStream that reads from standard input
ANTLRInputStream input = new ANTLRInputStream(System.in);
/
/ create a lexer that feeds off of input CharStream
ArrayInitLexer lexer = new ArrayInitLexer(input);
/
/ create a buffer of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
/
/ create a parser that feeds off the tokens buffer
ArrayInitParser parser = new ArrayInitParser(tokens);
ParseTree tree = parser.init(); /
/ begin parsing at init rule
/
/ Create a generic parse tree walker that can trigger callbacks
ParseTreeWalker walker = new ParseTreeWalker();
/
/ Walk the tree created during the parse, trigger callbacks
walker.walk(new ShortToUnicodeString(), tree);
System.out.println(); /
/ print a n after translation
}
}
Building a Calculator Using a Visitor
grammar LabeledExpr;
prog: stat+ ;
stat: expr NEWLINE # printExpr
| ID '=' expr NEWLINE # assign
| NEWLINE # blank
;
expr: expr op=('*'|'/') expr # MulDiv
| expr op=('+'|'-') expr # AddSub
| INT # int
| ID # id
| '(' expr ')' # parens
;
MUL : '*' ; /
/ assigns token name to '*' used above in grammar
DIV : '/' ;
ADD : '+' ;
SUB : '-' ;
ID : [a-zA-Z]+ ; /
/ match identiļ¬ers
INT : [0-9]+ ; /
/ match integers
Driver class: Calc.java
LabeledExprLexer lexer = new LabeledExprLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
LabeledExprParser parser = new LabeledExprParser(tokens);
ParseTree tree = parser.prog(); /
/ parse
EvalVisitor eval = new EvalVisitor();
eval.visit(tree);
Use ANTLR to generate a visitor interface with a method for each labeled
$ antlr4 -no-listener -visitor LabeledExpr.g4
public interface LabeledExprVisitor<T> {
T visitId(LabeledExprParser.IdContext ctx);
T visitAssign(LabeledExprParser.AssignContext ctx);
T visitMulDiv(LabeledExprParser.MulDivContext ctx);
...
}
To implement the calculator, we override the methods associated with statement and expression alternatives.
import java.util.HashMap;
import java.util.Map;
public class EvalVisitor extends LabeledExprBaseVisitor<Integer> {
/** "memory" for our calculator; variable/value pairs go here */
Map<String, Integer> memory = new HashMap<String, Integer>();
/** ID '=' expr NEWLINE */
@Override
public Integer visitAssign(LabeledExprParser.AssignContext ctx) {
String id = ctx.ID().getText(); /
/ id is left-hand side of '='
int value = visit(ctx.expr());
memory.put(id, value);
return value;
}
etc.
Building a Translator with a Listener
Imagine you want to build a tool that generates a Java interface ļ¬le from the methods in a Java class deļ¬nition.
Sample Input:
import java.util.List;
import java.util.Map;
public class Demo {
void f(int x, String y) {...}
int[ ] g( ) { return null; }
List<Map<String, Integer>>[ ] h( ) { return null; }
}
Output:
interface IDemo {
void f(int x, String y);
int[ ] g( );
List<Map<String, Integer>>[ ] h( );
}
The key ā€œinterfaceā€ between the grammar and our listener object is called
JavaListener, and ANTLR automatically generates it for us.
It deļ¬nes all of the methods that the class ParseTreeWalker from ANTLRā€™s runtime
can trigger as it traverses the parse tree.
Here are the relevant methods from the generated listener interface:
public interface JavaListener extends ParseTreeListener {
void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx);
void exitClassDeclaration(JavaParser.ClassDeclarationContext ctx);
void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx);
...
}
Listener methods are called by the ANTLR-provided walker object, whereas
visitor methods must walk their children with explicit visit calls.
Forgetting to invoke visit() on a nodeā€™s children means those subtrees donā€™t get
visited.
ANTLR generates a default implementation called JavaBaseListener. Our
interface extractor can then subclass JavaBaseListener and override the
methods of interest.
public class ExtractInterfaceListener extends JavaBaseListener {
JavaParser parser;
public ExtractInterfaceListener(JavaParser parser) {this.parser = parser;}
/** Listen to matches of classDeclaration */
@Override
public void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx){
System.out.println("interface I"+ctx.Identiļ¬er()+" {");
}
@Override
public void exitClassDeclaration(JavaParser.ClassDeclarationContext ctx) {
System.out.println("}");
}
/** Listen to matches of methodDeclaration */
@Override
public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx)
{
/
/ need parser to get tokens
TokenStream tokens = parser.getTokenStream();
String type = "void";
if ( ctx.type()!=null ) {
type = tokens.getText(ctx.type());
}
String args = tokens.getText(ctx.formalParameters());
System.out.println("t"+type+" "+ctx.Identiļ¬er()+args+";");
}
}
Homework 6
Will be added on homepage tomorrow.
Due: 31 May

More Related Content

Similar to Antlr

Structure of the compiler
Structure of the compilerStructure of the compiler
Structure of the compiler
Sudhaa Ravi
Ā 
Gunosy.go #4 go
Gunosy.go #4 goGunosy.go #4 go
Gunosy.go #4 go
Taku Fukushima
Ā 
Parser
ParserParser
Parser
Ghufran Hashmi
Ā 
Generating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonGenerating parsers using Ragel and Lemon
Generating parsers using Ragel and Lemon
Tristan Penman
Ā 
Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...
Alexey Diyan
Ā 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesRay Toal
Ā 
role of lexical anaysis
role of lexical anaysisrole of lexical anaysis
role of lexical anaysis
Sudhaa Ravi
Ā 
Parsing
ParsingParsing
Dr. Rajeshree Khande - Java Interactive input
Dr. Rajeshree Khande - Java Interactive inputDr. Rajeshree Khande - Java Interactive input
Dr. Rajeshree Khande - Java Interactive input
jalinder123
Ā 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
DrRajeshreeKhande
Ā 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
Anujashejwal
Ā 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
Aman Sharma
Ā 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
Radhakrishnan Chinnusamy
Ā 
Sax parser
Sax parserSax parser
Sax parser
Mahara Jothi
Ā 
python1.ppt
python1.pptpython1.ppt
python1.ppt
arivukarasi2
Ā 
1._Introduction_.pptx
1._Introduction_.pptx1._Introduction_.pptx
1._Introduction_.pptx
Anbarasan Radhakrishnan R
Ā 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
Munni28
Ā 
CC Week 11.ppt
CC Week 11.pptCC Week 11.ppt
CC Week 11.ppt
KamranAli649587
Ā 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
Ā 

Similar to Antlr (20)

Structure of the compiler
Structure of the compilerStructure of the compiler
Structure of the compiler
Ā 
Gunosy.go #4 go
Gunosy.go #4 goGunosy.go #4 go
Gunosy.go #4 go
Ā 
Parser
ParserParser
Parser
Ā 
Generating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonGenerating parsers using Ragel and Lemon
Generating parsers using Ragel and Lemon
Ā 
Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...
Ā 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax Trees
Ā 
role of lexical anaysis
role of lexical anaysisrole of lexical anaysis
role of lexical anaysis
Ā 
Parsing
ParsingParsing
Parsing
Ā 
Dr. Rajeshree Khande - Java Interactive input
Dr. Rajeshree Khande - Java Interactive inputDr. Rajeshree Khande - Java Interactive input
Dr. Rajeshree Khande - Java Interactive input
Ā 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
Ā 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
Ā 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
Ā 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
Ā 
Sax parser
Sax parserSax parser
Sax parser
Ā 
Linker scripts
Linker scriptsLinker scripts
Linker scripts
Ā 
python1.ppt
python1.pptpython1.ppt
python1.ppt
Ā 
1._Introduction_.pptx
1._Introduction_.pptx1._Introduction_.pptx
1._Introduction_.pptx
Ā 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
Ā 
CC Week 11.ppt
CC Week 11.pptCC Week 11.ppt
CC Week 11.ppt
Ā 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Ā 

More from Arlene Smith

Speech Analysis Template Rhetorical Terms A Rhetori
Speech Analysis Template  Rhetorical Terms A RhetoriSpeech Analysis Template  Rhetorical Terms A Rhetori
Speech Analysis Template Rhetorical Terms A Rhetori
Arlene Smith
Ā 
College Essay Double Spaced - Buy College Application Essays
College Essay Double Spaced - Buy College Application EssaysCollege Essay Double Spaced - Buy College Application Essays
College Essay Double Spaced - Buy College Application Essays
Arlene Smith
Ā 
Example Of Critique Paper Critique Paper Article Critiq
Example Of Critique Paper Critique Paper Article CritiqExample Of Critique Paper Critique Paper Article Critiq
Example Of Critique Paper Critique Paper Article Critiq
Arlene Smith
Ā 
Christmas Writing Paper Printable - Printable Word
Christmas Writing Paper Printable - Printable WordChristmas Writing Paper Printable - Printable Word
Christmas Writing Paper Printable - Printable Word
Arlene Smith
Ā 
Where To Sell Personal Essays
Where To Sell Personal EssaysWhere To Sell Personal Essays
Where To Sell Personal Essays
Arlene Smith
Ā 
Do You Think That Someone Write My Paper For Me In 12 Hours If You Are
Do You Think That Someone Write My Paper For Me In 12 Hours If You AreDo You Think That Someone Write My Paper For Me In 12 Hours If You Are
Do You Think That Someone Write My Paper For Me In 12 Hours If You Are
Arlene Smith
Ā 
005 Creative Essay Example Narrative Pers
005 Creative Essay Example Narrative Pers005 Creative Essay Example Narrative Pers
005 Creative Essay Example Narrative Pers
Arlene Smith
Ā 
34 Of The Best Books On Writing These Will Inspire
34 Of The Best Books On Writing These Will Inspire34 Of The Best Books On Writing These Will Inspire
34 Of The Best Books On Writing These Will Inspire
Arlene Smith
Ā 
Examples Of Informative Writin
Examples Of Informative WritinExamples Of Informative Writin
Examples Of Informative Writin
Arlene Smith
Ā 
Using I In A Research Paper. Can I Use Questions In A
Using I In A Research Paper. Can I Use Questions In AUsing I In A Research Paper. Can I Use Questions In A
Using I In A Research Paper. Can I Use Questions In A
Arlene Smith
Ā 
Pin On English Teaching
Pin On English TeachingPin On English Teaching
Pin On English Teaching
Arlene Smith
Ā 
Brief Article Teaches You The Ins And Outs Of Write My R
Brief Article Teaches You The Ins And Outs Of Write My RBrief Article Teaches You The Ins And Outs Of Write My R
Brief Article Teaches You The Ins And Outs Of Write My R
Arlene Smith
Ā 
013 Argumentative Essays Examples Brillia
013 Argumentative Essays Examples Brillia013 Argumentative Essays Examples Brillia
013 Argumentative Essays Examples Brillia
Arlene Smith
Ā 
College Of Charleston From Website - MBA Central
College Of Charleston From Website - MBA CentralCollege Of Charleston From Website - MBA Central
College Of Charleston From Website - MBA Central
Arlene Smith
Ā 
How To Write An Evaluation Paper With Sample Essays Owlcation
How To Write An Evaluation Paper With Sample Essays OwlcationHow To Write An Evaluation Paper With Sample Essays Owlcation
How To Write An Evaluation Paper With Sample Essays Owlcation
Arlene Smith
Ā 
Free Sample Scholarship Essa
Free Sample Scholarship EssaFree Sample Scholarship Essa
Free Sample Scholarship Essa
Arlene Smith
Ā 
Awesome Short Essay On Leadership ~ Thatsnotus
Awesome Short Essay On Leadership ~ ThatsnotusAwesome Short Essay On Leadership ~ Thatsnotus
Awesome Short Essay On Leadership ~ Thatsnotus
Arlene Smith
Ā 
John Hanson ā€“ Paper Writing Tips From An Expert Writer
John Hanson ā€“ Paper Writing Tips From An Expert WriterJohn Hanson ā€“ Paper Writing Tips From An Expert Writer
John Hanson ā€“ Paper Writing Tips From An Expert Writer
Arlene Smith
Ā 
College Pressures
College PressuresCollege Pressures
College Pressures
Arlene Smith
Ā 
Rainbow Clouds Lined Paper Li
Rainbow Clouds Lined Paper LiRainbow Clouds Lined Paper Li
Rainbow Clouds Lined Paper Li
Arlene Smith
Ā 

More from Arlene Smith (20)

Speech Analysis Template Rhetorical Terms A Rhetori
Speech Analysis Template  Rhetorical Terms A RhetoriSpeech Analysis Template  Rhetorical Terms A Rhetori
Speech Analysis Template Rhetorical Terms A Rhetori
Ā 
College Essay Double Spaced - Buy College Application Essays
College Essay Double Spaced - Buy College Application EssaysCollege Essay Double Spaced - Buy College Application Essays
College Essay Double Spaced - Buy College Application Essays
Ā 
Example Of Critique Paper Critique Paper Article Critiq
Example Of Critique Paper Critique Paper Article CritiqExample Of Critique Paper Critique Paper Article Critiq
Example Of Critique Paper Critique Paper Article Critiq
Ā 
Christmas Writing Paper Printable - Printable Word
Christmas Writing Paper Printable - Printable WordChristmas Writing Paper Printable - Printable Word
Christmas Writing Paper Printable - Printable Word
Ā 
Where To Sell Personal Essays
Where To Sell Personal EssaysWhere To Sell Personal Essays
Where To Sell Personal Essays
Ā 
Do You Think That Someone Write My Paper For Me In 12 Hours If You Are
Do You Think That Someone Write My Paper For Me In 12 Hours If You AreDo You Think That Someone Write My Paper For Me In 12 Hours If You Are
Do You Think That Someone Write My Paper For Me In 12 Hours If You Are
Ā 
005 Creative Essay Example Narrative Pers
005 Creative Essay Example Narrative Pers005 Creative Essay Example Narrative Pers
005 Creative Essay Example Narrative Pers
Ā 
34 Of The Best Books On Writing These Will Inspire
34 Of The Best Books On Writing These Will Inspire34 Of The Best Books On Writing These Will Inspire
34 Of The Best Books On Writing These Will Inspire
Ā 
Examples Of Informative Writin
Examples Of Informative WritinExamples Of Informative Writin
Examples Of Informative Writin
Ā 
Using I In A Research Paper. Can I Use Questions In A
Using I In A Research Paper. Can I Use Questions In AUsing I In A Research Paper. Can I Use Questions In A
Using I In A Research Paper. Can I Use Questions In A
Ā 
Pin On English Teaching
Pin On English TeachingPin On English Teaching
Pin On English Teaching
Ā 
Brief Article Teaches You The Ins And Outs Of Write My R
Brief Article Teaches You The Ins And Outs Of Write My RBrief Article Teaches You The Ins And Outs Of Write My R
Brief Article Teaches You The Ins And Outs Of Write My R
Ā 
013 Argumentative Essays Examples Brillia
013 Argumentative Essays Examples Brillia013 Argumentative Essays Examples Brillia
013 Argumentative Essays Examples Brillia
Ā 
College Of Charleston From Website - MBA Central
College Of Charleston From Website - MBA CentralCollege Of Charleston From Website - MBA Central
College Of Charleston From Website - MBA Central
Ā 
How To Write An Evaluation Paper With Sample Essays Owlcation
How To Write An Evaluation Paper With Sample Essays OwlcationHow To Write An Evaluation Paper With Sample Essays Owlcation
How To Write An Evaluation Paper With Sample Essays Owlcation
Ā 
Free Sample Scholarship Essa
Free Sample Scholarship EssaFree Sample Scholarship Essa
Free Sample Scholarship Essa
Ā 
Awesome Short Essay On Leadership ~ Thatsnotus
Awesome Short Essay On Leadership ~ ThatsnotusAwesome Short Essay On Leadership ~ Thatsnotus
Awesome Short Essay On Leadership ~ Thatsnotus
Ā 
John Hanson ā€“ Paper Writing Tips From An Expert Writer
John Hanson ā€“ Paper Writing Tips From An Expert WriterJohn Hanson ā€“ Paper Writing Tips From An Expert Writer
John Hanson ā€“ Paper Writing Tips From An Expert Writer
Ā 
College Pressures
College PressuresCollege Pressures
College Pressures
Ā 
Rainbow Clouds Lined Paper Li
Rainbow Clouds Lined Paper LiRainbow Clouds Lined Paper Li
Rainbow Clouds Lined Paper Li
Ā 

Recently uploaded

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
Ā 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
Ā 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
Ā 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
Ā 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
Ā 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
Ā 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
Ā 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
Ā 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
Ā 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
Ā 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
Ā 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
Ā 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
Ā 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
Ā 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
Ā 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
Ā 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
Ā 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
Ā 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
Ā 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
Ā 

Recently uploaded (20)

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
Ā 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Ā 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Ā 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
Ā 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Ā 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Ā 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Ā 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Ā 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
Ā 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Ā 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Ā 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
Ā 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Ā 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
Ā 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Ā 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
Ā 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Ā 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
Ā 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
Ā 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
Ā 

Antlr

  • 1. ANTLR 4 Homepage: http:/ /www.antlr4.org The Deļ¬nitive ANTLR 4 Reference: http:/ /pragprog.com/book/tpantlr2/the-deļ¬nitive- antlr-4-reference
  • 2. MEET ANTLR ANTLR is written in Java - so installing it is a matter of downloading the latest jar, such as antlr-4.0-complete.jar For syntax diagrams of grammar rules, syntax highlighting of ANTLR 4 grammars, etc, use the ANTLRWorks 2 or ANTRLWorks 2 Netbeans plugin. http:/ /tunnelvisionlabs.com/products/demo/ antlrworks
  • 3. ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for translating structured text. It's widely used to build language related tools. From a grammar, ANTLR generates a parser that can build and walk parse trees. What is ANTLR?
  • 4. Terence Parr is the maniac behind ANTLR and has been working on language tools since 1989. He is a professor of computer science at the University of San Francisco. Twitter search uses for example ANTLR for query parsing.
  • 5. Create aliases for the ANTLR Tool, and TestRig. $ alias antlr4='java -jar /usr/local/lib/antlr-4.0-complete.jar' $ alias grun='java org.antlr.v4.runtime.misc.TestRig' Getting Started
  • 6. Hello.g4 / / Deļ¬ne a grammar called Hello grammar Hello; r : 'hello' ID ; / / match keyword hello followed by an identiļ¬er ID : [a-z]+ ; / / match lower-case identiļ¬ers WS : [ trn]+ -> skip ; / / skip spaces, tabs, newlines Then run ANTLR the tool on it: $ antlr4 Hello.g4 $ javac Hello*.java Now test it: $ grun Hello r -tree hello brink ^D (r hello brink) A First Example
  • 7. $ grun Hello r -gui hello brink ^D This pops up a dialog box showing that rule r matched keyword hello followed by the identiļ¬er brink.
  • 8. THE BIG PICTURE Tokenizing: The process of grouping characters into words or symbols (tokens) is called lexical analysis or simply tokenizing. We call a program that tokenizes the input a lexer. The lexer group related tokens into token classes, or token types, such as INT, ID, FLOAT, etc. Tokens consist of at least two pieces of information: the token type and the text matched for that token by the lexer.
  • 9. The parser feeds off of the tokens to recognize the sentence structure. By default, ANTLR-generated parsers build a parse tree that records how the parse recognized the input sentence.
  • 10. By producing a parse tree, a parser delivers a handy data structure to be used by the rest of the language translation application. Trees are easy to process in subsequent steps and are well understood by programmers. Better yet, the parser can generate parse trees automatically.
  • 11. The ANTLR tool generates recursive-descent parsers from grammar rules. Recursive-descent parsers are really just a collection of recursive methods, one per rule. The descent term refers to the fact that parsing begins at the root of a parse tree and proceeds toward the leaves (tokens).
  • 12. To get an idea of what recursive-descent parsers look like, next some (slightly cleaned up) methods that ANTLR generates from grammar rules: assign : ID '=' expr ';' ; / / match an assignment statement like "sp = 100;" / / assign : ID '=' expr ';' ; void assign() { / / method generated from rule assign match(ID); / / compare ID to current input symbol then consume match('='); expr(); / / match an expression by calling expr() match(';'); }
  • 13. /** Match any kind of statement starting at the current input position */ stat: assign / / First alternative ('|' is alternative separator) | ifstat / / Second alternative | whilestat ... ; The parser will generate: void stat() { switch ( Ā«current input tokenĀ» ) { CASE ID : assign(); break; CASE IF : ifstat(); break; / / IF is token type for keyword 'if' CASE WHILE : whilestat(); break; ... default : Ā«raise no viable alternative exceptionĀ» } }
  • 14. In the example on the previous slide: Method stat() has to make a parsing decision or prediction by examining the next input token. Parsing decisions predict which alternative will be successful. In this case, seeing a WHILE keyword predicts the third alternative of rule(). A lookahead token is any token that the parser sniffs before matching and consuming it. Sometimes, the parser needs lots of lookahead tokens to predict which alternative will succeed. ANTLR silently handles all of this for you.
  • 15. Ambiguous Grammars stat: ID '=' expr ';' / / match an assignment; can match "f();" | ID '=' expr ';' / / oops! an exact duplicate of previous alternative ; expr: INT ; stat: expr ';' / / expression statement | ID '(' ')' ';' / / function call statement ; expr: ID '(' ')' | INT ; ANTLR resolves the ambiguity by choosing the ļ¬rst alternative involved in the decision.
  • 16. Ambiguities can occur in the lexer as well as the parser. ANTLR resolves lexical ambiguities by matching the input string to the rule speciļ¬ed ļ¬rst in the grammar. BEGIN : 'begin' ; / / match b-e-g-i-n sequence; ambiguity resolves to BEGIN ID : [a-z]+ ; / / match one or more of any lowercase letter
  • 17. Building Language Applications Using Parse Trees Lexers process characters and pass tokens to the parser, which in turn checks syntax and creates a parse tree. The corresponding ANTLR classes are CharStream, Lexer, Token, Parser, and ParseTree. The ā€œpipeā€ connecting the lexer and parser is called a TokenStream.
  • 18. ANTLR uses context objects which knows the start and stop tokens for a recognized phrase and provides access to all of the elements of that phrase. For example, AssignContext provides methods ID() and expr() to access the identiļ¬er node and expression subtree.
  • 19. Parse-Tree Listeners and Visitors By default, ANTLR generates a parse-tree listener interface that responds to events triggered by the built-in tree walker. To walk a tree and trigger calls into a listener, ANTLRā€™s runtime provides the class ParseTreeWalker. To make a language application, we write a ParseTreeListener. The beauty of the listener mechanism is that itā€™s all automatic. We donā€™t have to write a parse-tree walker, and our listener methods donā€™t have to explicitly visit their children.
  • 21. Parse-Tree Visitors There are situations, however, where we want to control the walk itself, explicitly calling methods to visit children. Option -visitor asks ANTLR to generate a visitor interface from a grammar with a visit method per rule. ParseTree tree = ... ; / / tree is result of parsing MyVisitor v = new MyVisitor(); v.visit(tree);
  • 22. A STATER ANTLR PROJECT Letā€™s build a grammar to recognize integers in, possibly nested, curly braces like {1, 2, 3} and {1, {2, 3}, 4}. grammar ArrayInit; /** A rule called init that matches comma-separated values between {...}. */ init : '{' value (',' value)* '}' ; / / must match at least one value /** A value can be either a nested array/struct or a simple integer (INT) */ value : init | INT; / / parser rules start with lowercase letters, lexer rules with uppercase INT : [0-9]+ ; / / Deļ¬ne token INT as one or more digits WS : [ trn]+ -> skip ; / / Deļ¬ne whitespace rule, toss it out
  • 23. From the grammar ArrayInit.g4, ANTLR generates the following ļ¬les:
  • 24. ArrayInitParser.java This ļ¬le contains the parser class deļ¬nition speciļ¬c to grammar ArrayInit that recognizes our array language syntax. ArrayInitLexer.java ANTLR automatically extracts a separate parser and lexer speciļ¬cation from our grammar. ArrayInit.tokens ANTLR assigns a token type number to each token we deļ¬ne and stores these values in this ļ¬le. ArrayInitListener.java, ArrayInitBaseListener.java By default, ANTLR parsers build a tree from the input. By walking that tree, a tree walker can ļ¬re ā€œeventsā€ (callbacks) to a listener object that we provide. ArrayInitListener is the interface that describes the callbacks we can implement. ArrayInitBaseListener is a set of empty default implementations.
  • 26. Integrating a Generated Parser into a Java Program / / import ANTLR's runtime libraries import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; public class Test { public static void main(String[] args) throws Exception { / / create a CharStream that reads from standard input ANTLRInputStream input = new ANTLRInputStream(System.in); / / create a lexer that feeds off of input CharStream ArrayInitLexer lexer = new ArrayInitLexer(input); / / create a buffer of tokens pulled from the lexer CommonTokenStream tokens = new CommonTokenStream(lexer); / / create a parser that feeds off the tokens buffer ArrayInitParser parser = new ArrayInitParser(tokens); ParseTree tree = parser.init(); / / begin parsing at init rule System.out.println(tree.toStringTree(parser)); / / print LISP-style tree } }
  • 27. Building a Language Application using ArrayInitBaseListener /** Convert short array inits like {1,2,3} to "u0001u0002u0003" */ public class ShortToUnicodeString extends ArrayInitBaseListener { /** Translate { to " */ @Override public void enterInit(ArrayInitParser.InitContext ctx) {System.out.print(' " '); } /** Translate } to " */ @Override public void exitInit(ArrayInitParser.InitContext ctx) {System.out.print(' " '); } /** Convert short array inits like {1,2,3} to "u0001u0002u0003" */ @Override public void enterValue(ArrayInitParser.ValueContext ctx) { / / Assumes no nested array initializers int value = Integer.valueOf(ctx.INT().getText()); System.out.printf("u%04x", value); } } }
  • 28. Driver program for ArrayInitBaseListener public class Translate { public static void main(String[] args) throws Exception { / / create a CharStream that reads from standard input ANTLRInputStream input = new ANTLRInputStream(System.in); / / create a lexer that feeds off of input CharStream ArrayInitLexer lexer = new ArrayInitLexer(input); / / create a buffer of tokens pulled from the lexer CommonTokenStream tokens = new CommonTokenStream(lexer); / / create a parser that feeds off the tokens buffer ArrayInitParser parser = new ArrayInitParser(tokens); ParseTree tree = parser.init(); / / begin parsing at init rule / / Create a generic parse tree walker that can trigger callbacks ParseTreeWalker walker = new ParseTreeWalker(); / / Walk the tree created during the parse, trigger callbacks walker.walk(new ShortToUnicodeString(), tree); System.out.println(); / / print a n after translation } }
  • 29. Building a Calculator Using a Visitor grammar LabeledExpr; prog: stat+ ; stat: expr NEWLINE # printExpr | ID '=' expr NEWLINE # assign | NEWLINE # blank ; expr: expr op=('*'|'/') expr # MulDiv | expr op=('+'|'-') expr # AddSub | INT # int | ID # id | '(' expr ')' # parens ; MUL : '*' ; / / assigns token name to '*' used above in grammar DIV : '/' ; ADD : '+' ; SUB : '-' ; ID : [a-zA-Z]+ ; / / match identiļ¬ers INT : [0-9]+ ; / / match integers
  • 30. Driver class: Calc.java LabeledExprLexer lexer = new LabeledExprLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); LabeledExprParser parser = new LabeledExprParser(tokens); ParseTree tree = parser.prog(); / / parse EvalVisitor eval = new EvalVisitor(); eval.visit(tree);
  • 31. Use ANTLR to generate a visitor interface with a method for each labeled $ antlr4 -no-listener -visitor LabeledExpr.g4 public interface LabeledExprVisitor<T> { T visitId(LabeledExprParser.IdContext ctx); T visitAssign(LabeledExprParser.AssignContext ctx); T visitMulDiv(LabeledExprParser.MulDivContext ctx); ... } To implement the calculator, we override the methods associated with statement and expression alternatives.
  • 32. import java.util.HashMap; import java.util.Map; public class EvalVisitor extends LabeledExprBaseVisitor<Integer> { /** "memory" for our calculator; variable/value pairs go here */ Map<String, Integer> memory = new HashMap<String, Integer>(); /** ID '=' expr NEWLINE */ @Override public Integer visitAssign(LabeledExprParser.AssignContext ctx) { String id = ctx.ID().getText(); / / id is left-hand side of '=' int value = visit(ctx.expr()); memory.put(id, value); return value; } etc.
  • 33. Building a Translator with a Listener Imagine you want to build a tool that generates a Java interface ļ¬le from the methods in a Java class deļ¬nition. Sample Input: import java.util.List; import java.util.Map; public class Demo { void f(int x, String y) {...} int[ ] g( ) { return null; } List<Map<String, Integer>>[ ] h( ) { return null; } } Output: interface IDemo { void f(int x, String y); int[ ] g( ); List<Map<String, Integer>>[ ] h( ); }
  • 34. The key ā€œinterfaceā€ between the grammar and our listener object is called JavaListener, and ANTLR automatically generates it for us. It deļ¬nes all of the methods that the class ParseTreeWalker from ANTLRā€™s runtime can trigger as it traverses the parse tree. Here are the relevant methods from the generated listener interface: public interface JavaListener extends ParseTreeListener { void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx); void exitClassDeclaration(JavaParser.ClassDeclarationContext ctx); void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx); ... }
  • 35. Listener methods are called by the ANTLR-provided walker object, whereas visitor methods must walk their children with explicit visit calls. Forgetting to invoke visit() on a nodeā€™s children means those subtrees donā€™t get visited. ANTLR generates a default implementation called JavaBaseListener. Our interface extractor can then subclass JavaBaseListener and override the methods of interest.
  • 36. public class ExtractInterfaceListener extends JavaBaseListener { JavaParser parser; public ExtractInterfaceListener(JavaParser parser) {this.parser = parser;} /** Listen to matches of classDeclaration */ @Override public void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx){ System.out.println("interface I"+ctx.Identiļ¬er()+" {"); } @Override public void exitClassDeclaration(JavaParser.ClassDeclarationContext ctx) { System.out.println("}"); } /** Listen to matches of methodDeclaration */ @Override public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { / / need parser to get tokens TokenStream tokens = parser.getTokenStream(); String type = "void"; if ( ctx.type()!=null ) { type = tokens.getText(ctx.type()); } String args = tokens.getText(ctx.formalParameters()); System.out.println("t"+type+" "+ctx.Identiļ¬er()+args+";"); } }
  • 37. Homework 6 Will be added on homepage tomorrow. Due: 31 May