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
;
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
}
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