r获取使用ExpressionBuilder创建的AST数据结构

r获取使用ExpressionBuilder创建的AST数据结构

本文介绍了Dart PetitParser获取使用ExpressionBuilder创建的AST数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我是petitparser的新手,但它看起来像是解析器的声音螺丝刀.

I'm new to petitparser, but it looks like it's the sonic screwdriver of parsers.

对于我的第一个项目,我正在构建代码以解析一个简单的表达式,该表达式将为Node对象构建一个AST树,然后使用一些规则遍历该树以最小化不必要的parens.我不知道传递给.parse()的输出(似乎是结果)以访问我定义的树,因此我可以在AST的顶部调用.visit().有什么想法吗?

For my first project, I'm building code to parse a simple expression that builds an AST tree of my Node objects, then walks that tree with a few rules to minimize the unneeded parens. I don't know what to pass to the output of .parse() (seems to be a Result) to get access to the tree I defined, so I can call .visit() on the top of the AST. Any ideas?

class RIPParser {
  Parser _make_parser() {
    final builder = ExpressionBuilder();

    // precedence 5
    builder.group()
      ..primitive(digit()
          .plus()
          .seq(char('.').seq(digit().plus()).optional())
          .flatten()
          .trim()
          .map((a) => Node(precedence: 5, value: a)))
      ..wrapper(char('(').trim(), char(')').trim(),
          (l, a, r) => Node(precedence: 5, left: l, value: a, right: r));
    // negation is a prefix operator
    // precedence 4
    builder.group()
      ..prefix(
          char('-').trim(), (op, a) => Node(precedence: 4, value: '$op$a'));

    // power is right-associative
    // precedence 3
    builder.group()
      ..right(char('^').trim(),
          (a, op, b) => Node(precedence: 3, left: a, value: op, right: b));

    // multiplication and addition are left-associative
    // precedence 2
    builder.group()
      ..left(char('*').trim(),
          (a, op, b) => Node(precedence: 2, left: a, value: op, right: b))
      ..left(char('/').trim(),
          (a, op, b) => Node(precedence: 2, left: a, value: op, right: b));
    // precedence 1
    builder.group()
      ..left(char('+').trim(),
          (a, op, b) => Node(precedence: 1, left: a, value: op, right: b))
      ..left(char('-').trim(),
          (a, op, b) => Node(precedence: 1, value: op, left: a, right: b));

    final parser = builder.build().end();

    return parser;
  }

  Result parse(String input) {
    var parser = _make_parser();
    var result = parser.parse(input);
    return result;
  }

推荐答案

简而言之,调用 result.value 可以获取您的解析树,或者在其中抛出 ParserException 错误的情况.

In short call result.value to get your parse-tree, or to throw a ParserException in case of an error.

有关更多详细信息,请参见结果,它是成功失败实例.在这两种情况下,对象都包含额外的信息,例如消耗了多少输入或发生错误的情况.

For more details have a look at the class documentation of Result, which is either a Success or a Failure instance. In both cases the objects contain extra information, such as how much input was consumed or in case of an error what went wrong.

更新:我已经尝试在 8698f91 .

这篇关于Dart PetitParser获取使用ExpressionBuilder创建的AST数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:03