java - Antlr4 RPN Calc; final result on stack missing -



java - Antlr4 RPN Calc; final result on stack missing -

disclaimer: course of study work , first post questions have been asked before

after brief crash course of study on antlr i've done best figure out how best tackle problem of creating rpn calculator supports numerical, logical , relational operations. int , boolean accepted.

now, while code not near standard antlr quality, working except when 'start' rule matches. want print out result stack, reason stack empty after matching.

e.g. 2 3 + ; print debug statements see pushed, popped , result of 5 pushed expected. stack empty 1 time terminating ';' matched 'start' rule.

i'm sure i'm missing fundamental here, we've spent day antlr in class, cannot figure out. haven't had luck finding debuggers antlr4 allow me step through code runs, did print out inputs, popped items , pushed items went along , seems until 'start'

below sample of code add-on operation , no boolean inputs:

grammar rpn; @header { import java.util.stack; } @members { stack<string> s = new stack<string>(); int first; int second; int parseinteger(string value) { if(tryparseint(value)) { system.out.println("integer parsed stack: " + value + "\n"); homecoming integer.parseint(value); } else { system.out.println("error: invalid integer value; unable parse\n"); homecoming 0; } } boolean tryparseint(string value) { seek { integer.parseint(value); homecoming true; } catch(numberformatexception nfe) { homecoming false; } } boolean stackcheck(stack st, int size) { if(st.size() >= size) { homecoming true; } else { system.out.println("error: operation needs " + integer.tostring(size) + " values\n"); homecoming false; } } } // parser rules start : ( expr+ ';')+ eof { if(stackcheck(s, 1)) { system.out.println("result: " + s.pop() + ';'); } if(s.size() > 0) { system.out.println("too many operands supplied\n"); } }; expr : atom+ operation; atom : int; // lexer rules int : [0-9]+ { s.push(gettext()); }; operation : '+' { if(stackcheck(s, 2)) { sec = parseinteger(s.pop()); first = parseinteger(s.pop()); s.push(integer.tostring(first + second)); } }; ws : ( ' ' | '\t' | '\r' | '\n' )+ {skip();};

i have solved problem. still don't have total understanding of why, seems parser rules ran before lexer rules. hence altered programme parser rules ones have actions pushing new input , performing operations.

if can help me understand why is, appreciate it. in mind, parser rules made of other parser rules , lexer rules. lexer rules made of regex rules. beingness lexer lowest mutual denominator, assumed lexer rule invoked first, in playing antlr found false.

java antlr4 rpn

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -