Advertisement
Guest User

Untitled

a guest
May 26th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. package expression;
  2.  
  3. /*
  4.  * Seda klassi ei pea muutma, aga esita see ka siis, kui sa seda ei muutnud!
  5.  */
  6. public class ExprNode {
  7.    
  8.     public boolean containsVariable(String name) {
  9.         if (this instanceof BinOp) {
  10.             if (((BinOp)this).getLeft().containsVariable(name)) {
  11.                 return true;
  12.             }
  13.            
  14.             if (((BinOp)this).getRight().containsVariable(name)) {
  15.                 return true;
  16.             }
  17.         } else if (this instanceof Variable) {
  18.             if (((Variable)this).getName().equals(name)){
  19.                 return true;
  20.             }
  21.         }
  22.        
  23.         return false;
  24.     }
  25.     public ExprNode renameVariable(String oldName, String newName) {
  26.         if (this instanceof BinOp) {
  27.             BinOp oldNode = (BinOp) this;
  28.             return new BinOp(oldNode.getOperator(),
  29.                     oldNode.getLeft().renameVariable(oldName, newName),
  30.                     oldNode.getRight().renameVariable(oldName, newName));
  31.         }
  32.         if (this instanceof Variable) {
  33.             Variable oldNode = (Variable) this;
  34.             if (oldNode.getName().equals(oldName)) {
  35.                 return new Variable(newName);
  36.             } else {
  37.                 return new Variable(oldNode.getName());
  38.             }
  39.         }
  40.         if (this instanceof IntLiteral) {
  41.             IntLiteral oldNode = (IntLiteral) this;
  42.             return new IntLiteral(oldNode.getValue());
  43.         }
  44.        
  45.         throw new RuntimeException("Unknown node");
  46.     }
  47.    
  48.     public ExprNode renameVariableSafely(String oldName, String newName) {
  49.         String temp = newName;
  50.         while (this.containsVariable(temp)) {
  51.             temp += "a";
  52.         }
  53.         ExprNode unique = renameVariable(newName, temp);
  54.         return unique.renameVariable(oldName, newName);
  55.     }
  56.    
  57.     @Override
  58.     public boolean equals(Object that) {
  59.         return this.getClass().equals(that.getClass())
  60.                 && this.toString().equals(that.toString());
  61.     }
  62.  
  63.     @Override
  64.     public int hashCode() {
  65.         return this.toString().hashCode();
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement