/dsl-by-antrl

try to create a DSL by antrl

Primary LanguageGo

Antlr generate calculation

  • simple calculation
  • support bracket to change the priority
  • support variable definition

simple calculation

  1. write a naive Calc.g4, support very simple calculation
grammar Calc;

// Tokens
MUL: '*';
DIV: '/';
ADD: '+';
SUB: '-';
NUMBER: [0-9]+;
WHITESPACE: [ \r\n\t]+ -> skip;

// Rules
start : expression EOF;

expression
   : expression op=('*'|'/') expression # MulDiv
   | expression op=('+'|'-') expression # AddSub
   | NUMBER                             # Number
   ;
  1. compile it

it generate all parser code under parser folder by default, and use parameter -package to specific target package

$ antlr -Dlanguage=Go -o parser Calc.g4
$ antlr -Dlanguage=Go -package mypackage -o parser Calc.g4
$ antlr -Dlanguage=Go -package apiparser -o apiparser ApiParser.g4

support bracket to change priority

expression
   : left='(' expression right=')' #LeftRightBracket
   | expression op=('*'|'/') expression # MulDiv
   | expression op=('+'|'-') expression # AddSub
   | NUMBER                             # Number
   ;

support variables