Created
April 29, 2013 16:23
-
-
Save JnBrymn/5482725 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CalculatorParser extends BaseParser<Integer> { | |
public Rule Expression() { | |
return Sequence( | |
Term(), | |
ZeroOrMore( | |
FirstOf( | |
Sequence('+', Term(), push(pop() + pop())), | |
Sequence('-', Term(), push(pop(1) - pop())) | |
) | |
), | |
EOI | |
); | |
} | |
public Rule Term() { | |
return Sequence( | |
Number(), | |
ZeroOrMore( | |
FirstOf( | |
Sequence('*', Number(), push(pop() * pop())), | |
Sequence('/', Number(), push(pop(1) / pop())) | |
) | |
) | |
); | |
} | |
public Rule Number() { | |
return Sequence( | |
OneOrMore(Digit()), | |
push(Integer.parseInt( match() )) | |
); | |
} | |
public Rule Digit() { | |
return CharRange('0', '9'); | |
} | |
//**************** MAIN **************** | |
public static void main(String[] args) { | |
CalculatorParser<V> parser = Parboiled.createParser(CalculatorParser.class); | |
ParsingResult<?> result = new RecoveringParseRunner(parser.Expression()).run(args[0]); | |
System.out.println(result.parseTreeRoot.getValue().toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment