KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lsmp > djep > xjep > RewriteVisitor


1    
2 package org.lsmp.djep.xjep;
3 //import org.lsmp.djep.matrixParser.*;
4
import org.nfunk.jep.*;
5
6 /**
7  * Simplifies an expression.
8  * To use
9  * <pre>
10  * JEP j = ...; Node in = ...;
11  * SimplificationVisitor sv = new SimplificationVisitor(tu);
12  * Node out = sv.simplify(in);
13  * </pre>
14  *
15  * <p>
16  * Its intended to completly rewrite this class to that simplification
17  * rules can be specified by strings in a way similar to DiffRulesI.
18  * It also would be nice to change the rules depending on the type of
19  * arguments, for example matrix multiplication is not commutative.
20  * But some of the in built rules exploit commutativity.
21  *
22  * @author Rich Morris
23  * Created on 20-Jun-2003
24  */

25
26 public class RewriteVisitor extends DoNothingVisitor
27 {
28   private NodeFactory nf;
29   private OperatorSet opSet;
30   private TreeUtils tu;
31   private XJep xj;
32   private RewriteRuleI rules[];
33   private boolean simp=false;
34   public RewriteVisitor()
35   {
36   }
37
38   /** must be implemented for subclasses. **/
39   public Node rewrite(Node node,XJep xjep,RewriteRuleI rules[],boolean simplify) throws ParseException,IllegalArgumentException JavaDoc
40   {
41     xj = xjep;
42     nf = xjep.getNodeFactory();
43     opSet = xjep.getOperatorSet();
44     tu = xjep.getTreeUtils();
45     this.rules = rules;
46     this.simp = simplify;
47     if(this.rules.length==0) return node;
48     
49     if (node == null)
50         throw new IllegalArgumentException JavaDoc(
51             "topNode parameter is null");
52     Node res = (Node) node.jjtAccept(this,null);
53     return res;
54   }
55
56     
57     public Object JavaDoc visit(ASTFunNode node, Object JavaDoc data) throws ParseException
58     {
59         Node children[] = acceptChildrenAsArray(node,data);
60         TreeUtils.copyChildrenIfNeeded(node,children);
61         for(int i=0;i<rules.length;++i)
62         {
63             if(rules[i].test(node,children))
64             {
65                 Node newNode = rules[i].apply(node,children);
66                 if(simp)
67                     newNode = xj.simplify(newNode);
68                 return newNode.jjtAccept(this,data);
69             }
70         }
71         return node;
72     }
73 }
74
Popular Tags