1

I am creating an computer algebra system using ANTLR. So far I have been able to generate the tree and read information from the tree. Now I need to implement algebraic simplification by reading the leaf nodes of the tree, detecting if they can be simplified, and then simplifying them.

Are there methods to change the value of leaf nodes and delete them?

Here is my code and the output in generates:

import java.io.FileInputStream;
import java.io.IOException;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import org.omg.CORBA.portable.InputStream;

public class CAS {

    public static void main(String[] args) throws IOException {

        FileInputStream inputstream = new FileInputStream("d:\\input.txt");
        CharStream cs = CharStreams.fromStream(inputstream);

        HelloLexer lexer = new HelloLexer(cs);
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        System.out.println("Tokens:");
         tokens.fill();
         for (Token token : tokens.getTokens())
         {
             System.out.println(token.toString());
         }

         HelloParser parser = new HelloParser(tokens);
         ParseTree tree = parser.expr();

         System.out.println("\nParse tree (Lisp format):");
         System.out.println(tree.toStringTree(parser));
    }
}
//Output
Tokens:
[@0,0:0='2',<8>,1:0]
[@1,1:1='x',<9>,1:1]
[@2,2:2='+',<4>,1:2]
[@3,3:3='3',<8>,1:3]
[@4,4:3='<EOF>',<-1>,1:4]

Parse tree (Lisp format):
(expr (expr (factor (term 2) (factor (term x)))) + (expr (factor (term 3))))

1 Answers1

3

Don't manipulate the tree that was created by your parser. This represents the original input. Instead apply your simplification transformation and generate a new tree, possibly in a format that makes it easy to generate the new code from, instead of using the original tree structure.

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181
  • Mike, I get what you are saying. Could I simply used the ANTLR-generated context classes for the new tree? Or would I be stuck with an unmodifiable tree again? Is there a good alternative? I wish we could have an immutable parse tree that allows modifications by returning a new tree with structural sharing ... – ThomasH Feb 03 '20 at 15:21
  • 1
    Most of the classes used in a parse tree are mutable (e.g. the CommonToken, which contains a terminal node). You can of course use all the elements of the parse tree to create your new tree from, though I would design own classes for the new tree to carry only the information I need. Up to you. – Mike Lischke Feb 04 '20 at 07:50