antlr - Proper way to use visitors in ANTLR4 (javascript target) -


i having trouble understanding how use visitors in antlr4, javascript target.

i have prepared basic grammar, accepts int + int or int - int operations.

grammar plusminus; int    : [0-9]+; ws     : [ \t\r]+ -> skip;  plus  : '+'; minus : '-';  input : plusorminus     ;  plusorminus     : numberleft plus numberright # plus     | numberleft minus numberright # minus     ;  numberleft : int; numberright : int; 

from grammar antlr generate visitor has these 3 functions, visitinput, visitplus , visitminus. start visitinput able fetch operation ctx doing operation = ctx.plusorminus().

this stuck, how know if operation of type plus or minus? in other words, pass ctx.plusorminux(), visitplus() or visitminus()?

i managed create visitor work, it's ugly, i posting here because perhaps better understand question. lines 20-29 problem is.

first of all... plus , minus lexer rules. don't visit tokens (the result of lexer rules).

it rather looks you're expecting work listener (where set function gets called when tree walker reaches node. can called on enter or exit node (depends on whether want node before or after you've processed it's children). visitors expect handle own tree navigation, useful, listeners cleaner suit purpose. nesting, you'll want listen after children nodes processed, you'll want implement exitplusormins() function on listener. i'd suggest stopping code in debugger inside function take @ objects have available (in ctx object).

(you need rethink numberleft , numberright parser rules. more like:

plusorminus: lexpr=int (op=plus | op=minus) rexpr=int;

would give pretty close equivalent have far. have work recursive descent parser antlr (so far example goes), you're headed in wrong direction making them different parse rules.)

to further adding or subtracting integers, though, you'll need lexpr , rexpr expressions (you should read on expression parsing in antlr book; it's covered nicely).

with rule, exitplusorminus can parse int values of lexpr , rexpr , evaluate value of op determine whether add or subtract.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -