ANTLR duplicate a tree

后端 未结 2 895
小蘑菇
小蘑菇 2020-12-18 13:05

I use ANTLR to build a tree (CommonTree) like follwing (language: JAVA):

  Parser.prog_return r = parser.prog();
  CommonTree t = (CommonTree) r.getTree();
<         


        
2条回答
  •  没有蜡笔的小新
    2020-12-18 13:58

    I had the same issue stumbling over dupTree(), which seemed to be deprecated and then Bart's posting, which steered me into the right direction. I finally ended up with the following, which is using the constructor of CommonTree accepting a CommonTree - abstracting it from the need to copy the individual fields.

      private static CommonTree copyTreeRecursive(CommonTree original) {
    
        CommonTree copy = new CommonTree(original); // Leverage constructor
    
        if(original.getChildren() != null) {
          for(Object o : original.getChildren()) {
            CommonTree childCopy  = copyTreeRecursive((CommonTree)o);
            childCopy.setParent(copy);
            copy.addChild(childCopy);
          }
        };
        return copy;
      }
    

    NB: I stuck with Bart's naming convention.

提交回复
热议问题