You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Suppose you want to clone CtMethod m1 to get CtMethod m2. clone() does it well, but all local variable references from m2 refer to variable declarations from m1. Is it convenient to fix that in clone() method implementation?
Code that sets reference declarations to correct variables:
public <T extends CtElement> T repairLocals(T element) {
class Scope {
private final Scope parent;
private ArrayList<CtVariable> variables;
public Scope(Scope parent) {
this.parent = parent;
}
public void add(CtVariable var) {
if (variables == null) {
variables = new ArrayList<>(1);
}
variables.add(var);
}
public CtVariable get(String name) {
if (variables != null) {
for (CtVariable var : variables) {
if (name.equals(var.getSimpleName())) {
return var;
}
}
}
return parent == null ? null : parent.get(name);
}
}
CtScanner scanner = new CtScanner() {
private final Stack<Scope> scopes;
{
scopes = new Stack<>();
scopes.add(new Scope(null));
}
@Override
protected void enter(CtElement e) {
scopes.push(new Scope(scopes.peek()));
}
@Override
protected void exit(CtElement e) {
scopes.pop();
}
@Override
public <T> void visitCtCatchVariable(CtCatchVariable<T> catchVariable) {
super.visitCtCatchVariable(catchVariable);
scopes.peek().add(catchVariable);
}
@Override
public <T> void visitCtCatchVariableReference(CtCatchVariableReference<T> reference) {
super.visitCtCatchVariableReference(reference);
CtVariable var = scopes.peek().get(reference.getSimpleName());
if (var != null) {
reference.setDeclaration((CtCatchVariable<T>) var);
}
}
@Override
public <T> void visitCtLocalVariable(CtLocalVariable<T> localVariable) {
super.visitCtLocalVariable(localVariable);
scopes.peek().add(localVariable);
}
@Override
public <T> void visitCtLocalVariableReference(CtLocalVariableReference<T> reference) {
super.visitCtLocalVariableReference(reference);
CtVariable var = scopes.peek().get(reference.getSimpleName());
if (var != null) {
reference.setDeclaration((CtLocalVariable<T>) var);
}
}
};
element.accept(scanner);
return element;
}
The text was updated successfully, but these errors were encountered:
Suppose you want to clone
CtMethod m1
to getCtMethod m2
.clone()
does it well, but all local variable references fromm2
refer to variable declarations fromm1
. Is it convenient to fix that inclone()
method implementation?Code that sets reference declarations to correct variables:
The text was updated successfully, but these errors were encountered: