Skip to content

Instantly share code, notes, and snippets.

@thosakwe
Last active January 24, 2017 22:17
Show Gist options
  • Select an option

  • Save thosakwe/7d5c2d67c61e3a161afb2b0b8c47e275 to your computer and use it in GitHub Desktop.

Select an option

Save thosakwe/7d5c2d67c61e3a161afb2b0b8c47e275 to your computer and use it in GitHub Desktop.
Dart-specific parser generator.
options {
prefix: 'MyAmazingCalculatorGrammar',
mixins: {
ExampleMixin: 'example_mixin.dart'
}
}
lexer {
// Tags for grouping tokens separately, i.e. comments
#comment {
'//' (!'\n')*
}
#skip => /[ \r\n\t]+/;
LPAREN => '[';
RPAREN => ']';
CARET => '^';
PLUS => '+';
MINUS => '-';
TIMES => '*';
SLASH => '/';
EQUALS => '=';
NUMBER => '-'? /[0-9]+/ ('.' /[0-9]+/)?;
}
parser {
Expr(int pr) {
:LiteralExpr() => NUMBER;
:ParenthesisExpr() => LPAREN Expr RPAREN;
:ExponentialExpr() if <pr >= 1> => Expr<0> #left CARET Expr<0>#right;
:MultiplicationExpr() if <pr >= 2> => Expr<0> #left TIMES Expr<0>#right;
:DivisionExpr() if <pr >= 3> => Expr<0> #left SLASH Expr<0>#right;
:AdditionExpr() if <pr >= 4> => Expr<0> #left PLUS Expr<0>#right;
:SubtractionExpr() if <pr >= 5> => Expr<0> #left MINUS Expr<0>#right;
}
}
class ExampleMixin {
void foo() => print('Hello, world!');
}
main(List<String> args) async {
var lexer = new MyAmazingCalculatorGrammarLexer();
var parser = new MyAmazingCalculatorGrammarParser();
if (args.isEmpty) {
// ...
}
// Will work asynchronously :)
await new File(args.first).openRead().transform(lexer).pipe(parser);
// Streaming parser to siphon events
parser.onExpr.first.then((expr) {
if (expr is MultiplicationExpr) {
// ...
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment