Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package expression;
- /*
- * Seda klassi ei pea muutma, aga esita see ka siis, kui sa seda ei muutnud!
- */
- public class ExprNode {
- public boolean containsVariable(String name) {
- if (this instanceof BinOp) {
- if (((BinOp)this).getLeft().containsVariable(name)) {
- return true;
- }
- if (((BinOp)this).getRight().containsVariable(name)) {
- return true;
- }
- } else if (this instanceof Variable) {
- if (((Variable)this).getName().equals(name)){
- return true;
- }
- }
- return false;
- }
- public ExprNode renameVariable(String oldName, String newName) {
- if (this instanceof BinOp) {
- BinOp oldNode = (BinOp) this;
- return new BinOp(oldNode.getOperator(),
- oldNode.getLeft().renameVariable(oldName, newName),
- oldNode.getRight().renameVariable(oldName, newName));
- }
- if (this instanceof Variable) {
- Variable oldNode = (Variable) this;
- if (oldNode.getName().equals(oldName)) {
- return new Variable(newName);
- } else {
- return new Variable(oldNode.getName());
- }
- }
- if (this instanceof IntLiteral) {
- IntLiteral oldNode = (IntLiteral) this;
- return new IntLiteral(oldNode.getValue());
- }
- throw new RuntimeException("Unknown node");
- }
- public ExprNode renameVariableSafely(String oldName, String newName) {
- String temp = newName;
- while (this.containsVariable(temp)) {
- temp += "a";
- }
- ExprNode unique = renameVariable(newName, temp);
- return unique.renameVariable(oldName, newName);
- }
- @Override
- public boolean equals(Object that) {
- return this.getClass().equals(that.getClass())
- && this.toString().equals(that.toString());
- }
- @Override
- public int hashCode() {
- return this.toString().hashCode();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement