implement ast deepcopy

This commit is contained in:
ChUrl
2020-12-15 16:21:40 +01:00
parent b606ba5593
commit 643a1c0e51
2 changed files with 20 additions and 10 deletions

View File

@ -25,6 +25,10 @@ public class AST {
ASTBalancer.balance(this); ASTBalancer.balance(this);
} }
public AST deepCopy() {
return new AST(this.root.deepCopy());
}
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof AST) { if (obj instanceof AST) {

View File

@ -5,6 +5,7 @@ import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors;
public class ASTNode { public class ASTNode {
@ -68,7 +69,7 @@ public class ASTNode {
// toString() und print() von hier: https://stackoverflow.com/a/8948691 // toString() und print() von hier: https://stackoverflow.com/a/8948691
@Override @Override
public String toString() { public String toString() {
StringBuilder buffer = new StringBuilder(50); final StringBuilder buffer = new StringBuilder(50);
this.print(buffer, "", ""); this.print(buffer, "", "");
return buffer.toString(); return buffer.toString();
} }
@ -90,8 +91,8 @@ public class ASTNode {
} }
buffer.append('\n'); buffer.append('\n');
for (Iterator<ASTNode> it = this.children.listIterator(); it.hasNext(); ) { for (final Iterator<ASTNode> it = this.children.listIterator(); it.hasNext(); ) {
ASTNode next = it.next(); final ASTNode next = it.next();
if (it.hasNext()) { if (it.hasNext()) {
next.print(buffer, childrenPrefix + "├── ", childrenPrefix + ""); next.print(buffer, childrenPrefix + "├── ", childrenPrefix + "");
} else { } else {
@ -101,16 +102,21 @@ public class ASTNode {
} }
public long size() { public long size() {
int s = 0; return 1 + this.children.stream().mapToLong(ASTNode::size).sum();
for (ASTNode child : this.children) {
s += child.size();
}
return s + 1;
} }
public int getLine() { public int getLine() {
return this.line; return this.line;
} }
public ASTNode deepCopy() {
final ASTNode newNode = new ASTNode(this.name, this.line);
newNode.value = this.value;
newNode.children = this.children.stream()
.map(ASTNode::deepCopy)
.collect(Collectors.toList());
return newNode;
}
} }