【问题标题】:How to bring along the children of a node in ANTLR rewrite?如何在 ANTLR 重写中带上节点的子节点?
【发布时间】:2012-08-06 11:57:46
【问题描述】:

我想拆分一条规则,因为我也想在其他规则中重复使用相同的子规则。原始版本运行良好:

type
  : ( basicType -> basicType )
  ( '*' -> ^(TYPE_POINTER basicType)
  | '[' ']' -> ^(TYPE_DYN_ARRAY basicType)
  | '[' IntegerLiteral ']' -> ^(TYPE_STATIC_ARRAY IntegerLiteral basicType)
  | '[' IntegerLiteral '..' IntegerLiteral ']' -> ^(REF_TYPE_SLICE IntegerLiteral IntegerLiteral basicType)
  | '[' type ']' -> ^(TYPE_MAP_ARRAY type basicType)
  )?
  ;

这条规则可以将一个普通类型(basicType,可以是引用或主要类型,如 int、char 等)放在不同的 AST 节点下,使其成为指针、数组、或者。这在类似 C 的语言中很常见。

但是,如果我这样拆分:

basicType2
  : '*' -> ^(TYPE_POINTER)
  | '[' ']' -> ^(TYPE_DYN_ARRAY)
  | '[' IntegerLiteral ']' -> ^(TYPE_STATIC_ARRAY IntegerLiteral)
  | '[' IntegerLiteral '..' IntegerLiteral ']' -> ^(REF_TYPE_SLICE IntegerLiteral IntegerLiteral)
  | '[' type ']' -> ^(TYPE_MAP_ARRAY type)
  ;

type
  : ( basicType -> basicType )
    ( basicType2 -> ^(basicType2 basicType) )?
  ;

一切看起来都很好,解析不会受到影响,但是在 AST 中,basicType2 的孩子完全丢失了。在 TYPE_STATIC_ARRAY、REF_TYPE_SLICE 或 TYPE_MAP_ARRAY 的情况下,只会将根复制到类型之上,但缺少子节点。

我调试了解析器代码,在我看来,CommonTree 类的复制构造函数在不复制子项时调用,只有令牌和源范围信息。有没有办法通过重写规则将 CommonTree 节点及其子节点带到另一个节点的顶​​部?

【问题讨论】:

    标签: java parsing antlr antlr3 abstract-syntax-tree


    【解决方案1】:

    始终使用单个标记作为树的根:而不是另一棵树,就像您在 basicType2 中所做的那样:

    type
      : ( basicType -> basicType )
        ( basicType2 -> ^(basicType2 basicType) )?
      ;
    

    试试这个:

    grammar ...
    
    options { ... }
    
    tokens { T2; }
    
    ...
    
    type
      : ( basicType -> basicType )
        ( basicType2 -> ^(T2 basicType2 basicType) )?
      ;
    
    ...
    

    【讨论】:

    • 虽然我知道这是如何工作的,但不幸的是,这不会产生与第一个(正常运行的)规则相同的 AST。它将生成一个 T2 节点,以 basicType2 和 basicType 作为子节点。我想要的是,如果 basicType2 存在,那么 basicType 应该是子节点,basicNode2 的一个新的附加子节点。但是谢谢...我想到了这一点,因为在第二种形式中,它将 basicType2 视为只有令牌的节点,而不是子树。
    • @progician,是的,我知道它会改变你的树,但是,因为 basicType2 可以是一个带有根节点和子节点的 AST,^(basicType2 basicType) 将不起作用。如果basicType2 总是产生一个单一的令牌,^(basicType2 basicType) 工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多