Skip to content

Instantly share code, notes, and snippets.

@JnBrymn
Created April 29, 2013 16:23
Show Gist options
  • Save JnBrymn/5482725 to your computer and use it in GitHub Desktop.
Save JnBrymn/5482725 to your computer and use it in GitHub Desktop.
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