SlideShare a Scribd company logo
1 of 21
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

What's hot

Unit 5
Unit 5Unit 5
Unit 5
siddr
ย 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
Pierre de Lacaze
ย 
Code Generation Cambridge 2013 Introduction to Parsing with ANTLR4
Code Generation Cambridge 2013  Introduction to Parsing with ANTLR4Code Generation Cambridge 2013  Introduction to Parsing with ANTLR4
Code Generation Cambridge 2013 Introduction to Parsing with ANTLR4
Oliver Zeigermann
ย 
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
Ray Toal
ย 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
Donal Fellows
ย 

What's hot (20)

Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
ย 
C language updated
C language updatedC language updated
C language updated
ย 
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
ย 
Java best practices
Java best practicesJava best practices
Java best practices
ย 
Unit 5
Unit 5Unit 5
Unit 5
ย 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
ย 
Lazy java
Lazy javaLazy java
Lazy java
ย 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
ย 
Code Generation Cambridge 2013 Introduction to Parsing with ANTLR4
Code Generation Cambridge 2013  Introduction to Parsing with ANTLR4Code Generation Cambridge 2013  Introduction to Parsing with ANTLR4
Code Generation Cambridge 2013 Introduction to Parsing with ANTLR4
ย 
Interpreter Design Pattern
Interpreter Design PatternInterpreter Design Pattern
Interpreter Design Pattern
ย 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
ย 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
ย 
Adventures in TclOO
Adventures in TclOOAdventures in TclOO
Adventures in TclOO
ย 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
ย 
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
ย 
OOP and FP
OOP and FPOOP and FP
OOP and FP
ย 
Sour Pickles
Sour PicklesSour Pickles
Sour Pickles
ย 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
ย 
Python
PythonPython
Python
ย 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
ย 

Viewers also liked

Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
eShikshak
ย 
Chapter 7 review questions
Chapter 7 review questionsChapter 7 review questions
Chapter 7 review questions
loayshabaneh
ย 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
bajiajugal
ย 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
vishaljot_kaur
ย 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressions
vinay arora
ย 

Viewers also liked (15)

Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
ย 
2 2. operators
2 2. operators2 2. operators
2 2. operators
ย 
Chapter 7 review questions
Chapter 7 review questionsChapter 7 review questions
Chapter 7 review questions
ย 
Lecture03(c expressions & operators)
Lecture03(c expressions & operators)Lecture03(c expressions & operators)
Lecture03(c expressions & operators)
ย 
Activities on Operator Precedence and Associativity
Activities on Operator Precedence and AssociativityActivities on Operator Precedence and Associativity
Activities on Operator Precedence and Associativity
ย 
Operator Precedence and Associativity
Operator Precedence and AssociativityOperator Precedence and Associativity
Operator Precedence and Associativity
ย 
Chap 3(operator expression)
Chap 3(operator expression)Chap 3(operator expression)
Chap 3(operator expression)
ย 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
ย 
Operator precedence
Operator precedenceOperator precedence
Operator precedence
ย 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
ย 
C Programming Language Part 5
C Programming Language Part 5C Programming Language Part 5
C Programming Language Part 5
ย 
Chapter 07
Chapter 07 Chapter 07
Chapter 07
ย 
C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5
ย 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
ย 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressions
ย 

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

Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)
ujihisa
ย 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
ujihisa
ย 
Unit 4
Unit 4Unit 4
Unit 4
siddr
ย 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
ย 
Anti patterns
Anti patternsAnti patterns
Anti patterns
Alex Tumanoff
ย 
Java Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfJava Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdf
adinathassociates
ย 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docx
janettjz6sfehrle
ย 

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

Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
ย 
Swift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolSwift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : Protocol
ย 
Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)
ย 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
ย 
Chapter 2
Chapter 2Chapter 2
Chapter 2
ย 
Unit 4
Unit 4Unit 4
Unit 4
ย 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
ย 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
ย 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
ย 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012
ย 
Anti patterns
Anti patternsAnti patterns
Anti patterns
ย 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
ย 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
ย 
Java Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfJava Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdf
ย 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
ย 
Parboiled explained
Parboiled explainedParboiled explained
Parboiled explained
ย 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
ย 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
ย 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docx
ย 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
ย 

More from Binary Studio

More from Binary Studio (20)

Academy PRO: D3, part 3
Academy PRO: D3, part 3Academy PRO: D3, part 3
Academy PRO: D3, part 3
ย 
Academy PRO: D3, part 1
Academy PRO: D3, part 1Academy PRO: D3, part 1
Academy PRO: D3, part 1
ย 
Academy PRO: Cryptography 3
Academy PRO: Cryptography 3Academy PRO: Cryptography 3
Academy PRO: Cryptography 3
ย 
Academy PRO: Cryptography 1
Academy PRO: Cryptography 1Academy PRO: Cryptography 1
Academy PRO: Cryptography 1
ย 
Academy PRO: Advanced React Ecosystem. MobX
Academy PRO: Advanced React Ecosystem. MobXAcademy PRO: Advanced React Ecosystem. MobX
Academy PRO: Advanced React Ecosystem. MobX
ย 
Academy PRO: Docker. Part 4
Academy PRO: Docker. Part 4Academy PRO: Docker. Part 4
Academy PRO: Docker. Part 4
ย 
Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2
ย 
Academy PRO: Docker. Part 1
Academy PRO: Docker. Part 1Academy PRO: Docker. Part 1
Academy PRO: Docker. Part 1
ย 
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio Academy 2017: JS team project - OrderlyBinary Studio Academy 2017: JS team project - Orderly
Binary Studio Academy 2017: JS team project - Orderly
ย 
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio Academy 2017: .NET team project - UnicornBinary Studio Academy 2017: .NET team project - Unicorn
Binary Studio Academy 2017: .NET team project - Unicorn
ย 
Academy PRO: React native - miscellaneous
Academy PRO: React native - miscellaneousAcademy PRO: React native - miscellaneous
Academy PRO: React native - miscellaneous
ย 
Academy PRO: React native - publish
Academy PRO: React native - publishAcademy PRO: React native - publish
Academy PRO: React native - publish
ย 
Academy PRO: React native - navigation
Academy PRO: React native - navigationAcademy PRO: React native - navigation
Academy PRO: React native - navigation
ย 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenesAcademy PRO: React native - building first scenes
Academy PRO: React native - building first scenes
ย 
Academy PRO: React Native - introduction
Academy PRO: React Native - introductionAcademy PRO: React Native - introduction
Academy PRO: React Native - introduction
ย 
Academy PRO: Push notifications. Denis Beketsky
Academy PRO: Push notifications. Denis BeketskyAcademy PRO: Push notifications. Denis Beketsky
Academy PRO: Push notifications. Denis Beketsky
ย 
Academy PRO: Docker. Lecture 4
Academy PRO: Docker. Lecture 4Academy PRO: Docker. Lecture 4
Academy PRO: Docker. Lecture 4
ย 
Academy PRO: Docker. Lecture 3
Academy PRO: Docker. Lecture 3Academy PRO: Docker. Lecture 3
Academy PRO: Docker. Lecture 3
ย 
Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2
ย 
Academy PRO: Docker. Lecture 1
Academy PRO: Docker. Lecture 1Academy PRO: Docker. Lecture 1
Academy PRO: Docker. Lecture 1
ย 

Recently uploaded

CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
anilsa9823
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
ย 

Recently uploaded (20)

CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
ย 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
ย 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
ย 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
ย 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
ย 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
ย 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
ย 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
ย 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
ย 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
ย 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
ย 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
ย 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
ย 
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธcall girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
ย 
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
ย 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
ย 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
ย 

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

  1. Semantic predicates Recursive rules Attributes Grammar commands Options