Parser / ANTLR

Writing a Parser in Go with ANTLR 4

Generate a Go parser from an EBNF grammar, then use a visitor to turn its parse tree into arithmetic expressions you can evaluate.

· 4 min read· EN中文

Before we start

ANTLR is an open-source parser generator written in Java.

A compiler does quite a bit of work. It tokenizes the input, parses it, checks what it means, generates intermediate code, and so on.

That’s for a full programming language. Sometimes all I want is a little DSL or a format for a config file. A lexer and a parser can be all I need.

Give ANTLR a grammar in its EBNF-like notation and it will generate a lexer and a parser that builds a parse tree. You can walk that tree with a listener or a visitor. Compared with the old lex and yacc combination, I find the generated code fairly pleasant to work with. I can do without another expedition through a few thousand lines of .y.

I’m using ANTLR 4 here, the current major version as I write this, with Go as the target language.

Installing ANTLR 4

I’ll leave this bit to the getting-started guide.

A little arithmetic grammar

EBNF stands for Extended Backus–Naur Form. It’s a notation for writing context-free grammars, and you’ll see it in plenty of programming language specifications.

Let’s start with a grammar for the four basic arithmetic operations.

grammar Math;
math : expr EOF;
expr : op=('+'|'-') expr # unaryExpr
| left=expr op=('*'|'/') right=expr # infixExpr
| left=expr op=('+'|'-') right=expr # infixExpr
| value=NUM # numberExpr
;
ADD: '+';
SUB: '-';
MUL: '*';
DIV: '/';
NUM : [0-9]+ ('.' [0-9]+)? ([eE] [+-]? [0-9]+)?;
WS : [ \t\r\n] -> channel(HIDDEN);

Save this as Math.g4. The filename has to match the grammar name.

Now generate the Go code.

Terminal window
$ antlr -Dlanguage=Go -visitor -o . Math.g4

Here’s what turns up in the current directory.

Terminal window
.
├── Math.g4
├── Math.tokens
├── MathLexer.tokens
├── math_base_listener.go
├── math_base_visitor.go
├── math_lexer.go
├── math_listener.go
├── math_parser.go
└── math_visitor.go

math_parser.go defines the generated parse-tree nodes. The listener and visitor interfaces live in math_listener.go and math_visitor.go, respectively.

The difference is who gets to steer. With a listener, ANTLR’s walker picks the route and calls your code when it reaches a node you care about. With a visitor, you decide which children to visit and when.

What I’d like to get out of this is a small AST that can evaluate itself.

type NodeType int
const (
NodeExpr NodeType = iota
NodeValue
)
type OpType int
const (
OpAdd OpType = iota
OpSub
OpMul
OpDiv
)
type Node struct {
Type NodeType
Left *Node
Right *Node
Op OpType
Val float64
}
func (n *Node) Evaluate() float64 {
if n.Type == NodeExpr {
switch n.Op {
case OpAdd:
return n.Left.Evaluate() + n.Right.Evaluate()
case OpSub:
return n.Left.Evaluate() - n.Right.Evaluate()
case OpMul:
return n.Left.Evaluate() * n.Right.Evaluate()
case OpDiv:
return n.Left.Evaluate() / n.Right.Evaluate()
}
}
return n.Val
}

So how do we get from the tree ANTLR gives us to one of these?

I’ll use a visitor to build the AST as it walks the parse tree. Each of the three labels in the grammar gets its own method.

type convertVisitor struct {
BaseMathVisitor
}
func (v *convertVisitor) Visit(tree antlr.ParseTree) interface{} {
return tree.Accept(v)
}
func (v *convertVisitor) VisitMath(ctx *MathContext) interface{} {
return ctx.Expr().Accept(v)
}
func (v *convertVisitor) VisitNumberExpr(ctx *NumberExprContext) interface{} {
value, _ := strconv.ParseFloat(ctx.GetValue().GetText(), 64)
return &Node{Type: NodeValue, Val: value}
}
func (v *convertVisitor) VisitUnaryExpr(ctx *UnaryExprContext) interface{} {
op := OpAdd
if ctx.GetOp().GetTokenType() == MathLexerSUB {
op = OpSub
}
return &Node{
Type: NodeExpr, Op: op,
Left: &Node{Type: NodeValue, Val: 0},
Right: ctx.Expr().Accept(v).(*Node),
}
}
func (v *convertVisitor) VisitInfixExpr(ctx *InfixExprContext) interface{} {
var op OpType
switch ctx.GetOp().GetTokenType() {
case MathLexerADD:
op = OpAdd
case MathLexerSUB:
op = OpSub
case MathLexerMUL:
op = OpMul
case MathLexerDIV:
op = OpDiv
}
return &Node{
Type: NodeExpr, Op: op,
Left: ctx.GetLeft().Accept(v).(*Node),
Right: ctx.GetRight().Accept(v).(*Node),
}
}
func Parse(expr string) *Node {
input := antlr.NewInputStream(expr)
lexer := NewMathLexer(input)
tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
parser := NewMathParser(tokenStream)
tree := parser.Math()
v := &convertVisitor{}
return v.Visit(tree).(*Node)
}

Now Parse takes a string containing an arithmetic expression and hands back our root Node.