SlideShare a Scribd company logo
ANTLR 4 
Cool Features 
by Alexander Vasiltsov
What features? 
● Recursive rules 
● Precedence 
● Associativity 
● Actions 
● Attributes 
● Semantic predicates 
● Commands
Recursive rules 
expr : expr ‘*’ expr 
| expr ‘+’ expr 
| INT 
| ‘(‘ expr ‘)’ 
; 
expr : addExpr; 
addExpr : multExpr (‘+’ multExpr)*; 
multExpr : atom (‘*’ atom)*; 
atom : INT;
Precedence 
Rule or alternative described earlier has higher 
priority than others
Associativity 
By default, ANTLR 
associates operators left to 
right 
It’s possible to change the 
direction of associativity 
expr : <assoc=right> expr ‘^’ expr 
| INT 
; 
expr : expr ‘^’ expr 
| INT 
;
assoc option 
expr : <assoc=right> expr ‘^’ expr 
| expr ‘*’ expr 
| expr ‘+’ expr 
| INT 
| ‘(‘ expr ‘)’ 
;
Actions 
rule : subrule {<some code in target language> } 
; 
rule2 : alternative1 {<some code for alternative1> } 
| alternative2 {<some code for alternative2> } 
; 
rule3 : subrule1 {<some code after subrule1 matched> } 
TOKEN {<some code after TOKEN matched> } 
subrule2 {<some code after whole rule matched> } 
;
Actions and attributes 
<rulename> [<arguments list>] 
returns [<return values>] 
locals [<local members>] 
@init { 
<init code> 
} 
@after { 
<finalization code> 
} 
: <rule description> 
;
Actions and attributes (2) 
rule [int i, string s] 
returns [string[] vals, int max] 
locals [int loc=0] 
@init { 
//some init code here 
} 
@after { 
//some post-processing code 
} 
: 'TOKENS'+ 
; 
public partial class RuleContext : ParserRuleContext { 
public int i; 
public string s; 
public string[] vals; 
public int max; 
public int loc; 
public RuleContext(ParserRuleContext parent, int 
invokingState, int i, string s) : base(parent, 
invokingState) 
{ 
this.i = i; 
this.s = s; 
} 
... 
} 
public RuleContext rule(int i, string s) { 
//some init code here 
... //parsing logic here 
//some post-processing code 
}
Custom attributes 
parent_rule : rule[0, "test"] {Console.WriteLine("max: "+ $rule.max);} 
; 
rule [int i, string s] 
returns [string[] vals, int max] 
locals [int loc=0] 
@init { 
$ctx.vals = new[] {s}; 
$ctx.loc = i + 10; 
} 
@after { 
$ctx.max *= 10; 
} 
: (TOKEN { if ($ctx.loc > $TOKEN.text.Length) $ctx.max++;})+ 
;
Predefined token attributes 
Attribute Typ 
e 
Description 
text string Text matched 
type int Token type 
line int Line number (counting from 1) 
pos int Position in line (counting from 0) 
index int Overall token offset inside input stream 
channel int Channel where token was emited 
int int Token integer value
Predefined rule attributes 
Attribute Type Description 
$ctx ParserRuleContext Context object 
$ctx.GetText() string Text matched 
$ctx.start IToken First token 
$ctx.stop IToken Last token
Where else to place code 
grammar MyGrammar; 
@header { 
using System; 
} 
lexer::header { ... } 
@parser::header { ... } 
@lexer::members members { 
{ ... } 
private int myField; 
@public parser::int members MyProperty { ... {get; } 
set;} 
public void MyMethod() { 
//do something 
} 
} 
rule : subrule TOKEN+ ;
Bonus for C# 
● MyGrammar.g4.lexer.cs 
namespace MyNamespace 
{ 
partial class SimpleLexer 
{ 
} 
} 
● MyGrammar.g4.parser.cs 
namespace MyNamespace 
{ 
partial class SimpleParser 
{ 
} 
}
Semantic predicates
Lexer commands 
TokenName: alternative -> command-name[(parameter)] ; 
skip Skips token, doesn’t send it to parser 
type(T) Set type T to token 
channel(C) Send token in channel C 
mode(M) Switch lexer to mode M 
pushMode(M) Switch lexer to mode M, put current mode to the 
stack 
popMode Switch lexer to mode taken from the stack’s top 
more Match token but continue searching
type(T) 
Sets required type to the token
channel(C) 
Sends token in desired channel 
Predefined channels: 
● Token.DEFAULT_CHANNEL 
● Token.HIDDEN_CHANNEL
mode(M), pushMode(M), popMode 
Switch lexer to defined mode. 
Each mode contains its own set of rules 
Default mode: DEFAULT_MODE
more 
Matches token but continues searching
For those who like hardcore 
It’s possible to override any method in generated lexer and parser classes. Chose one that fits your 
needs and act!

More Related Content

PPTX
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 3)
Binary Studio
 
PPTX
CLTL presentation: training an opinion mining system from KAF files using CRF
Rubén Izquierdo Beviá
 
PPTX
KafNafParserPy: a python library for parsing/creating KAF and NAF files
Rubén Izquierdo Beviá
 
PPT
Introduction to Intermediate Java
Philip Johnson
 
PDF
Generating parsers using Ragel and Lemon
Tristan Penman
 
PDF
Java 8 features
NexThoughts Technologies
 
PDF
IO Streams, Files and Directories
Krasimir Berov (Красимир Беров)
 
PDF
Java 8
Robert Bachmann
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 3)
Binary Studio
 
CLTL presentation: training an opinion mining system from KAF files using CRF
Rubén Izquierdo Beviá
 
KafNafParserPy: a python library for parsing/creating KAF and NAF files
Rubén Izquierdo Beviá
 
Introduction to Intermediate Java
Philip Johnson
 
Generating parsers using Ragel and Lemon
Tristan Penman
 
Java 8 features
NexThoughts Technologies
 
IO Streams, Files and Directories
Krasimir Berov (Красимир Беров)
 

What's hot (20)

PPTX
Clojure 7-Languages
Pierre de Lacaze
 
PPTX
C language updated
Arafat Bin Reza
 
PDF
Protocols with Associated Types, and How They Got That Way
Alexis Gallagher
 
PPTX
Java best practices
Ray Toal
 
PPT
Unit 5
siddr
 
PPTX
Meta Object Protocols
Pierre de Lacaze
 
PDF
Lazy java
Mario Fusco
 
ODP
Domain Specific Languages In Scala Duse3
Peter Maas
 
PDF
Code Generation Cambridge 2013 Introduction to Parsing with ANTLR4
Oliver Zeigermann
 
PPTX
Interpreter Design Pattern
sreymoch
 
PDF
File Handling in C Programming
RavindraSalunke3
 
PPTX
File Handling and Command Line Arguments in C
Mahendra Yadav
 
PPTX
Adventures in TclOO
Donal Fellows
 
PPTX
Actors model in gpars
NexThoughts Technologies
 
PPT
An Annotation Framework for Statically-Typed Syntax Trees
Ray Toal
 
PDF
OOP and FP
Mario Fusco
 
PPTX
Sour Pickles
SensePost
 
PPTX
TclOO: Past Present Future
Donal Fellows
 
PPTX
Python
Gagandeep Nanda
 
PDF
The Swift Compiler and Standard Library
Santosh Rajan
 
Clojure 7-Languages
Pierre de Lacaze
 
C language updated
Arafat Bin Reza
 
Protocols with Associated Types, and How They Got That Way
Alexis Gallagher
 
Java best practices
Ray Toal
 
Unit 5
siddr
 
Meta Object Protocols
Pierre de Lacaze
 
Lazy java
Mario Fusco
 
Domain Specific Languages In Scala Duse3
Peter Maas
 
Code Generation Cambridge 2013 Introduction to Parsing with ANTLR4
Oliver Zeigermann
 
Interpreter Design Pattern
sreymoch
 
File Handling in C Programming
RavindraSalunke3
 
File Handling and Command Line Arguments in C
Mahendra Yadav
 
Adventures in TclOO
Donal Fellows
 
Actors model in gpars
NexThoughts Technologies
 
An Annotation Framework for Statically-Typed Syntax Trees
Ray Toal
 
OOP and FP
Mario Fusco
 
Sour Pickles
SensePost
 
TclOO: Past Present Future
Donal Fellows
 
The Swift Compiler and Standard Library
Santosh Rajan
 
Ad

Viewers also liked (15)

PPT
Mesics lecture 4 c operators and experssions
eShikshak
 
PDF
2 2. operators
웅식 전
 
DOCX
Chapter 7 review questions
loayshabaneh
 
PDF
Lecture03(c expressions & operators)
Dhaka University of Engineering & Technology(DUET)
 
PPTX
Activities on Operator Precedence and Associativity
Nicole Ynne Estabillo
 
PPTX
Operator Precedence and Associativity
Nicole Ynne Estabillo
 
PPT
Operator & Expression in c++
bajiajugal
 
PDF
Operator precedence
Akshaya Arunan
 
PPTX
Type Conversion, Precedence and Associativity
Aakash Singh
 
PPTX
C Programming Language Part 5
Rumman Ansari
 
PPSX
Chapter 07
wantedwahab
 
PPTX
C Programming Language Step by Step Part 5
Rumman Ansari
 
PPTX
Operators and expressions
vishaljot_kaur
 
PPT
C Prog. - Operators and Expressions
vinay arora
 
Mesics lecture 4 c operators and experssions
eShikshak
 
2 2. operators
웅식 전
 
Chapter 7 review questions
loayshabaneh
 
Lecture03(c expressions & operators)
Dhaka University of Engineering & Technology(DUET)
 
Activities on Operator Precedence and Associativity
Nicole Ynne Estabillo
 
Operator Precedence and Associativity
Nicole Ynne Estabillo
 
Operator & Expression in c++
bajiajugal
 
Operator precedence
Akshaya Arunan
 
Type Conversion, Precedence and Associativity
Aakash Singh
 
C Programming Language Part 5
Rumman Ansari
 
Chapter 07
wantedwahab
 
C Programming Language Step by Step Part 5
Rumman Ansari
 
Operators and expressions
vishaljot_kaur
 
C Prog. - Operators and Expressions
vinay arora
 
Ad

Similar to Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4) (20)

PPT
introduction_to_antlr 3.ppt
TathagatoBose
 
PDF
Generative programming (mostly parser generation)
Ralf Laemmel
 
PDF
Antlr
Arlene Smith
 
ODP
ANTLR4 in depth
Владимир Кожаев
 
PPT
Lexical analysis, syntax analysis, semantic analysis. Ppt
ovidlivi91
 
PPT
Antlr V3
guest5024494
 
PDF
Lecture10 syntax analysis_6
Mahesh Kumar Chelimilla
 
PPTX
A simple approach of lexical analyzers
Archana Gopinath
 
PPTX
Unitiv 111206005201-phpapp01
riddhi viradiya
 
PDF
Control structure
baran19901990
 
PPTX
6-Practice Problems - LL(1) parser-16-05-2023.pptx
venkatapranaykumarGa
 
PPT
Integrated Fundamental and Technical Analysis of Select Public Sector Oil Com...
nakshpub
 
PPTX
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 2)
Binary Studio
 
PPTX
C# Natural Language Engine
Ian Mercer
 
PDF
lalr. fo engineering student those who to
HjJordTzong
 
PPTX
ANTLR - Writing Parsers the Easy Way
Michael Yarichuk
 
PPT
Top_down_Parsing_ full_detail_explanation
RushikeshKadam34
 
PPTX
An Introduction to ANTLR
Morteza Zakeri
 
DOCX
How do you learn Bottom-up Parsing Algorithm.docx
Tri AB Refardi
 
introduction_to_antlr 3.ppt
TathagatoBose
 
Generative programming (mostly parser generation)
Ralf Laemmel
 
Lexical analysis, syntax analysis, semantic analysis. Ppt
ovidlivi91
 
Antlr V3
guest5024494
 
Lecture10 syntax analysis_6
Mahesh Kumar Chelimilla
 
A simple approach of lexical analyzers
Archana Gopinath
 
Unitiv 111206005201-phpapp01
riddhi viradiya
 
Control structure
baran19901990
 
6-Practice Problems - LL(1) parser-16-05-2023.pptx
venkatapranaykumarGa
 
Integrated Fundamental and Technical Analysis of Select Public Sector Oil Com...
nakshpub
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 2)
Binary Studio
 
C# Natural Language Engine
Ian Mercer
 
lalr. fo engineering student those who to
HjJordTzong
 
ANTLR - Writing Parsers the Easy Way
Michael Yarichuk
 
Top_down_Parsing_ full_detail_explanation
RushikeshKadam34
 
An Introduction to ANTLR
Morteza Zakeri
 
How do you learn Bottom-up Parsing Algorithm.docx
Tri AB Refardi
 

More from Binary Studio (20)

PPTX
Academy PRO: D3, part 3
Binary Studio
 
PPTX
Academy PRO: D3, part 1
Binary Studio
 
PPTX
Academy PRO: Cryptography 3
Binary Studio
 
PPTX
Academy PRO: Cryptography 1
Binary Studio
 
PPTX
Academy PRO: Advanced React Ecosystem. MobX
Binary Studio
 
PPTX
Academy PRO: Docker. Part 4
Binary Studio
 
PPTX
Academy PRO: Docker. Part 2
Binary Studio
 
PPTX
Academy PRO: Docker. Part 1
Binary Studio
 
PPTX
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio
 
PPTX
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio
 
PPTX
Academy PRO: React native - miscellaneous
Binary Studio
 
PPTX
Academy PRO: React native - publish
Binary Studio
 
PPTX
Academy PRO: React native - navigation
Binary Studio
 
PPTX
Academy PRO: React native - building first scenes
Binary Studio
 
PPTX
Academy PRO: React Native - introduction
Binary Studio
 
PPTX
Academy PRO: Push notifications. Denis Beketsky
Binary Studio
 
PPTX
Academy PRO: Docker. Lecture 4
Binary Studio
 
PPTX
Academy PRO: Docker. Lecture 3
Binary Studio
 
PPTX
Academy PRO: Docker. Lecture 2
Binary Studio
 
PPTX
Academy PRO: Docker. Lecture 1
Binary Studio
 
Academy PRO: D3, part 3
Binary Studio
 
Academy PRO: D3, part 1
Binary Studio
 
Academy PRO: Cryptography 3
Binary Studio
 
Academy PRO: Cryptography 1
Binary Studio
 
Academy PRO: Advanced React Ecosystem. MobX
Binary Studio
 
Academy PRO: Docker. Part 4
Binary Studio
 
Academy PRO: Docker. Part 2
Binary Studio
 
Academy PRO: Docker. Part 1
Binary Studio
 
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio
 
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio
 
Academy PRO: React native - miscellaneous
Binary Studio
 
Academy PRO: React native - publish
Binary Studio
 
Academy PRO: React native - navigation
Binary Studio
 
Academy PRO: React native - building first scenes
Binary Studio
 
Academy PRO: React Native - introduction
Binary Studio
 
Academy PRO: Push notifications. Denis Beketsky
Binary Studio
 
Academy PRO: Docker. Lecture 4
Binary Studio
 
Academy PRO: Docker. Lecture 3
Binary Studio
 
Academy PRO: Docker. Lecture 2
Binary Studio
 
Academy PRO: Docker. Lecture 1
Binary Studio
 

Recently uploaded (20)

PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
Immersive experiences: what Pharo users do!
ESUG
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Immersive experiences: what Pharo users do!
ESUG
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
Exploring AI Agents in Process Industries
amoreira6
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Presentation about variables and constant.pptx
kr2589474
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 

Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)

  • 1. ANTLR 4 Cool Features by Alexander Vasiltsov
  • 2. What features? ● Recursive rules ● Precedence ● Associativity ● Actions ● Attributes ● Semantic predicates ● Commands
  • 3. Recursive rules expr : expr ‘*’ expr | expr ‘+’ expr | INT | ‘(‘ expr ‘)’ ; expr : addExpr; addExpr : multExpr (‘+’ multExpr)*; multExpr : atom (‘*’ atom)*; atom : INT;
  • 4. Precedence Rule or alternative described earlier has higher priority than others
  • 5. Associativity By default, ANTLR associates operators left to right It’s possible to change the direction of associativity expr : <assoc=right> expr ‘^’ expr | INT ; expr : expr ‘^’ expr | INT ;
  • 6. assoc option expr : <assoc=right> expr ‘^’ expr | expr ‘*’ expr | expr ‘+’ expr | INT | ‘(‘ expr ‘)’ ;
  • 7. Actions rule : subrule {<some code in target language> } ; rule2 : alternative1 {<some code for alternative1> } | alternative2 {<some code for alternative2> } ; rule3 : subrule1 {<some code after subrule1 matched> } TOKEN {<some code after TOKEN matched> } subrule2 {<some code after whole rule matched> } ;
  • 8. Actions and attributes <rulename> [<arguments list>] returns [<return values>] locals [<local members>] @init { <init code> } @after { <finalization code> } : <rule description> ;
  • 9. Actions and attributes (2) rule [int i, string s] returns [string[] vals, int max] locals [int loc=0] @init { //some init code here } @after { //some post-processing code } : 'TOKENS'+ ; public partial class RuleContext : ParserRuleContext { public int i; public string s; public string[] vals; public int max; public int loc; public RuleContext(ParserRuleContext parent, int invokingState, int i, string s) : base(parent, invokingState) { this.i = i; this.s = s; } ... } public RuleContext rule(int i, string s) { //some init code here ... //parsing logic here //some post-processing code }
  • 10. Custom attributes parent_rule : rule[0, "test"] {Console.WriteLine("max: "+ $rule.max);} ; rule [int i, string s] returns [string[] vals, int max] locals [int loc=0] @init { $ctx.vals = new[] {s}; $ctx.loc = i + 10; } @after { $ctx.max *= 10; } : (TOKEN { if ($ctx.loc > $TOKEN.text.Length) $ctx.max++;})+ ;
  • 11. Predefined token attributes Attribute Typ e Description text string Text matched type int Token type line int Line number (counting from 1) pos int Position in line (counting from 0) index int Overall token offset inside input stream channel int Channel where token was emited int int Token integer value
  • 12. Predefined rule attributes Attribute Type Description $ctx ParserRuleContext Context object $ctx.GetText() string Text matched $ctx.start IToken First token $ctx.stop IToken Last token
  • 13. Where else to place code grammar MyGrammar; @header { using System; } lexer::header { ... } @parser::header { ... } @lexer::members members { { ... } private int myField; @public parser::int members MyProperty { ... {get; } set;} public void MyMethod() { //do something } } rule : subrule TOKEN+ ;
  • 14. Bonus for C# ● MyGrammar.g4.lexer.cs namespace MyNamespace { partial class SimpleLexer { } } ● MyGrammar.g4.parser.cs namespace MyNamespace { partial class SimpleParser { } }
  • 16. Lexer commands TokenName: alternative -> command-name[(parameter)] ; skip Skips token, doesn’t send it to parser type(T) Set type T to token channel(C) Send token in channel C mode(M) Switch lexer to mode M pushMode(M) Switch lexer to mode M, put current mode to the stack popMode Switch lexer to mode taken from the stack’s top more Match token but continue searching
  • 17. type(T) Sets required type to the token
  • 18. channel(C) Sends token in desired channel Predefined channels: ● Token.DEFAULT_CHANNEL ● Token.HIDDEN_CHANNEL
  • 19. mode(M), pushMode(M), popMode Switch lexer to defined mode. Each mode contains its own set of rules Default mode: DEFAULT_MODE
  • 20. more Matches token but continues searching
  • 21. For those who like hardcore It’s possible to override any method in generated lexer and parser classes. Chose one that fits your needs and act!

Editor's Notes

  • #2: Semantic predicates Recursive rules Attributes Grammar commands Options