kendal.api.impl.AstUtilsImpl Maven / Gradle / Ivy
The newest version!
package kendal.api.impl;
import java.util.Collections;
import java.util.stream.Collectors;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import kendal.api.AstUtils;
import kendal.model.Node;
public class AstUtilsImpl implements AstUtils {
private final Context context;
AstUtilsImpl(Context context) {
this.context = context;
}
@Override
public Name nameFromString(String name) {
return Names.instance(context).fromString(name);
}
@Override
public List toJCList(java.util.List list) {
return com.sun.tools.javac.util.List.from(list);
}
@Override
public List toJCList(T element) {
return toJCList(Collections.singletonList(element));
}
@Override
public List mapNodesToJCListOfObjects(java.util.List> listOfNodes) {
java.util.List list = listOfNodes.stream()
.map(Node::getObject)
.collect(Collectors.toList());
return com.sun.tools.javac.util.List.from(list);
}
@Override
@SuppressWarnings("unchecked")
public T deepClone(TreeMaker treeMaker, T tree) {
if (tree == null) {
return null;
}
if (tree instanceof JCTree.JCAnnotation) {
T annotation = (T) treeMaker.Annotation(deepClone(treeMaker, ((JCTree.JCAnnotation) tree).annotationType),
toJCList(((JCTree.JCAnnotation) tree).args.stream()
.map(arg -> deepClone(treeMaker, arg)).collect(Collectors.toList())));
annotation.setType(tree.type);
return annotation;
}
if (tree instanceof JCTree.JCNewArray) {
T array = (T) treeMaker.NewArray(((JCTree.JCNewArray) tree).elemtype,
((JCTree.JCNewArray) tree).dims,
toJCList(((JCTree.JCNewArray) tree).elems.stream()
.map(elem -> deepClone(treeMaker, elem)).collect(Collectors.toList())));
array.setType(tree.type);
return array;
}
if (tree instanceof JCTree.JCAssign) {
T assign = (T) treeMaker.Assign(deepClone(treeMaker, ((JCTree.JCAssign) tree).lhs), deepClone(treeMaker, ((JCTree.JCAssign) tree).rhs));
assign.setType(tree.type);
return assign;
}
if (tree instanceof JCTree.JCLiteral) {
T literal = (T) treeMaker.Literal(((JCTree.JCLiteral) tree).typetag, ((JCTree.JCLiteral) tree).value);
literal.setType(tree.type);
return literal;
}
if (tree instanceof JCTree.JCIdent) {
T ident = (T) treeMaker.Ident(((JCTree.JCIdent) tree).name);
ident.setType(tree.type);
return ident;
}
if (tree instanceof JCTree.JCFieldAccess) {
T select = (T) treeMaker.Select(deepClone(treeMaker, ((JCTree.JCFieldAccess) tree).selected), ((JCTree.JCFieldAccess) tree).name);
select.setType(tree.type);
return select;
}
// for objects that we do not need to clone
return tree;
}
}