@Override public TypeMirror getTypeMirror(TreePath arg0) { Tree tree = arg0.getLeaf(); if (tree.getKind() == Tree.Kind.IDENTIFIER) { Map<String, ObjectVariable> map = null; try { // [TODO] add JPDADebuggerImpl.getAllLabels() to API Method method = debugger.getClass().getMethod("getAllLabels"); // NOI18N map = (Map<String, ObjectVariable>) method.invoke(debugger); } catch (Exception ex) { Exceptions.printStackTrace(ex); } if (map != null) { String name = ((IdentifierTree)tree).getName().toString(); ObjectVariable var = map.get(name); if (var != null) { Elements elements = controller.getElements(); TypeElement typeElem = elements.getTypeElement(var.getClassType().getName()); if (typeElem != null) { return typeElem.asType(); } } } } return trees.getTypeMirror(arg0); }
private Map<String, Element> getUsedImplicitlyImportedClasses() { if (usedImplicitlyImportedClassesCache != null) { return usedImplicitlyImportedClassesCache; } usedImplicitlyImportedClassesCache = new HashMap<String, Element>(); new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void p) { Element e = overlay.wrap(model, elements, model.getElement(node)); //javaLang might be null for broken platforms if (e != null && ((javaLang != null && javaLang.equals(e.getEnclosingElement())) || (pack != null && pack.equals(e.getEnclosingElement())))) { usedImplicitlyImportedClassesCache.put(e.getSimpleName().toString(), e); } return null; } }.scan(cut, null); return usedImplicitlyImportedClassesCache; }
public Boolean visitIdentifier(IdentifierTree node, TreePath p) { if (p == null) return super.visitIdentifier(node, p); switch (verifyElements(getCurrentPath(), p)) { case MATCH_CHECK_DEEPER: if (node.getKind() == p.getLeaf().getKind()) { return true; } return deepVerifyIdentifier2MemberSelect(getCurrentPath(), p); case MATCH: return true; default: case NO_MATCH: case NO_MATCH_CONTINUE: return false; } }
private void addSyntheticTrees(DiffContext diffContext, Tree node) { if (node == null) return ; if (((JCTree) node).pos == (-1)) { diffContext.syntheticTrees.add(node); return ; } if (node.getKind() == Kind.EXPRESSION_STATEMENT) { ExpressionTree est = ((ExpressionStatementTree) node).getExpression(); if (est.getKind() == Kind.METHOD_INVOCATION) { ExpressionTree select = ((MethodInvocationTree) est).getMethodSelect(); if (select.getKind() == Kind.IDENTIFIER && ((IdentifierTree) select).getName().contentEquals("super")) { if (getTreeUtilities().isSynthetic(diffContext.origUnit, node)) { diffContext.syntheticTrees.add(node); } } } } }
/** */ private List<IdentifierTree> createIdentifiers( TreeMaker maker, List<VariableTree> variables) { List<IdentifierTree> identifiers; if (variables == null) { identifiers = new ArrayList<IdentifierTree>(1); identifiers.add(maker.Identifier("null".toString())); } else if (variables.isEmpty()) { identifiers = Collections.<IdentifierTree>emptyList(); } else { identifiers = new ArrayList<IdentifierTree>(variables.size()); for (VariableTree var : variables) { identifiers.add(maker.Identifier(var.getName().toString())); } } return identifiers; }
@Override public Void visitAssignment(AssignmentTree tree, EnumSet<UseTypes> d) { handlePossibleIdentifier(new TreePath(getCurrentPath(), tree.getVariable()), EnumSet.of(UseTypes.WRITE)); Tree expr = tree.getExpression(); if (expr instanceof IdentifierTree) { TreePath tp = new TreePath(getCurrentPath(), expr); handlePossibleIdentifier(tp, EnumSet.of(UseTypes.READ)); } scan(tree.getVariable(), EnumSet.of(UseTypes.WRITE)); scan(tree.getExpression(), EnumSet.of(UseTypes.READ)); return null; }
@Override public Void visitCompoundAssignment(CompoundAssignmentTree tree, EnumSet<UseTypes> d) { Set<UseTypes> useTypes = EnumSet.of(UseTypes.WRITE); if (d != null) { useTypes.addAll(d); } handlePossibleIdentifier(new TreePath(getCurrentPath(), tree.getVariable()), useTypes); Tree expr = tree.getExpression(); if (expr instanceof IdentifierTree) { TreePath tp = new TreePath(getCurrentPath(), expr); handlePossibleIdentifier(tp, EnumSet.of(UseTypes.READ)); } scan(tree.getVariable(), EnumSet.of(UseTypes.WRITE)); scan(tree.getExpression(), EnumSet.of(UseTypes.READ)); return null; }
@Override public Void visitInstanceOf(InstanceOfTree tree, EnumSet<UseTypes> d) { Tree expr = tree.getExpression(); if (expr instanceof IdentifierTree) { handlePossibleIdentifier(new TreePath(getCurrentPath(), expr), EnumSet.of(UseTypes.READ)); } TreePath tp = new TreePath(getCurrentPath(), tree.getType()); handlePossibleIdentifier(tp, EnumSet.of(UseTypes.CLASS_USE)); super.visitInstanceOf(tree, null); //TODO: should be considered return null; }
@SuppressWarnings("unused") private int depth(ExpressionTree expression) { switch (expression.getKind()) { case MEMBER_SELECT: MemberSelectTree selectTree = (MemberSelectTree) expression; return 1 + depth(selectTree.getExpression()); case METHOD_INVOCATION: MethodInvocationTree invTree = (MethodInvocationTree) expression; return depth(invTree.getMethodSelect()); case IDENTIFIER: IdentifierTree varTree = (IdentifierTree) expression; Symbol symbol = ASTHelpers.getSymbol(varTree); return (symbol.getKind().equals(ElementKind.FIELD)) ? 2 : 1; default: return 0; } }
private static Token<JavaTokenId> findTokenWithText(CompilationInfo info, String text, int start, int end) { TokenHierarchy<?> th = info.getTokenHierarchy(); TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language()).subSequence(start, end); while (ts.moveNext()) { Token<JavaTokenId> t = ts.token(); if (t.id() == JavaTokenId.IDENTIFIER) { boolean nameMatches; if (!(nameMatches = text.equals(info.getTreeUtilities().decodeIdentifier(t.text()).toString()))) { ExpressionTree expr = info.getTreeUtilities().parseExpression(t.text().toString(), new SourcePositions[1]); nameMatches = expr.getKind() == Kind.IDENTIFIER && text.contentEquals(((IdentifierTree) expr).getName()); } if (nameMatches) { return t; } } } return null; }
private static Token<JavaTokenId> findIdentifierSpanImpl(CompilationInfo info, IdentifierTree tree, CompilationUnitTree cu, SourcePositions positions) { int start = (int)positions.getStartPosition(cu, tree); int endPosition = (int)positions.getEndPosition(cu, tree); if (start == (-1) || endPosition == (-1)) return null; TokenHierarchy<?> th = info.getTokenHierarchy(); TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language()); if (ts.move(start) == Integer.MAX_VALUE) { return null; } if (ts.moveNext()) { if (ts.offset() >= start) { Token<JavaTokenId> t = ts.token(); return t; } } return null; }
public static ExpressionTree findValue(AnnotationTree m, String name) { for (ExpressionTree et : m.getArguments()) { if (et.getKind() == Kind.ASSIGNMENT) { AssignmentTree at = (AssignmentTree) et; String varName = ((IdentifierTree) at.getVariable()).getName().toString(); if (varName.equals(name)) { return at.getExpression(); } } if (et instanceof LiteralTree/*XXX*/ && "value".equals(name)) { return et; } } return null; }
@Override public Number visitIdentifier(IdentifierTree node, Void p) { String name = node.getName().toString(); Tree newNode = handleIdentifier(name, node); if (newNode != null) { rewrite(node, newNode); if (NUMBER_LITERAL_KINDS.contains(newNode.getKind())) { return (Number) ((LiteralTree) newNode).getValue(); } } Element e = info.getTrees().getElement(getCurrentPath()); if (e != null && isStaticElement(e) && !inImport) { rewrite(node, make.QualIdent(e)); } return super.visitIdentifier(node, p); }
@Override public DocTree visitIdentifier(com.sun.source.doctree.IdentifierTree node, Element p) { DocTrees trees = info.getDocTrees(); Element el = trees.getElement(getCurrentPath()); if (el != null && el.equals(toFind)) { DocSourcePositions sp = trees.getSourcePositions(); CompilationUnitTree cut = info.getCompilationUnit(); DocCommentTree docComment = getCurrentPath().getDocComment(); long start = sp.getStartPosition(cut, docComment, node); long end = sp.getEndPosition(cut, docComment, node); if(start != Diagnostic.NOPOS && end != Diagnostic.NOPOS) { try { MutablePositionRegion region = createRegion(doc, (int)start, (int)end); usages.add(region); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } } return super.visitIdentifier(node, p); }
private void dotExpressionUpToArgs(ExpressionTree expression, Optional<BreakTag> tyargTag) { expression = getArrayBase(expression); switch (expression.getKind()) { case MEMBER_SELECT: MemberSelectTree fieldAccess = (MemberSelectTree) expression; visit(fieldAccess.getIdentifier()); break; case METHOD_INVOCATION: MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; if (!methodInvocation.getTypeArguments().isEmpty()) { builder.open(plusFour); addTypeArguments(methodInvocation.getTypeArguments(), ZERO); // TODO(jdd): Should indent the name -4. builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, tyargTag); builder.close(); } visit(getMethodName(methodInvocation)); break; case IDENTIFIER: visit(((IdentifierTree) expression).getName()); break; default: scan(expression, null); break; } }
private static Collection<? extends TreePath> findResourceUsages( final VariableElement resource, final Collection<? extends TreePath> statements, final Trees trees) { final List<TreePath> usages = new LinkedList<>(); if (statements != null) { final ErrorAwareTreePathScanner<List<TreePath>,List<TreePath>> scanner = new ErrorAwareTreePathScanner<List<TreePath>, List<TreePath>>() { @Override public List<TreePath> visitIdentifier(IdentifierTree node, List<TreePath> p) { final TreePath path = getCurrentPath(); final Element element = trees.getElement(path); if (element == resource) { usages.add(path); } return super.visitIdentifier(node, p); } }; for (TreePath st : statements) { scanner.scan(st, usages); } } return usages; }
private void checkIfRefactorableMutation(TreePath currentTreePath, IdentifierTree that) { Tree parent = currentTreePath.getParentPath().getLeaf(); TreePath parentOfParentPath = currentTreePath.getParentPath().getParentPath(); Tree parentOfParent = parentOfParentPath.getLeaf(); if ((isStatementPreOrPostfix(parent, parentOfParent) || isLeftHandSideOfCompoundAssignement(parent, that)) && isPureMutator(parentOfParentPath)) { if (this.hasOneNEFReducer) { this.hasNonEffectivelyFinalVars = true; } else { this.hasOneNEFReducer = true; this.reducerStatement = currentTreePath.getParentPath().getParentPath().getLeaf(); this.mutatedVariable = that; } } else { this.hasNonEffectivelyFinalVars = true; } }
private void beautifyAssignement(Tree currentTree, Set<Name> needed) { AssignmentTree assigned = (AssignmentTree) ((ExpressionStatementTree) currentTree).getExpression(); ExpressionTree variable = assigned.getVariable(); if (variable.getKind() == Tree.Kind.IDENTIFIER) { IdentifierTree id = (IdentifierTree) variable; if (needed.contains(id.getName())) { this.correspondingTree = treeMaker.ExpressionStatement(assigned.getExpression()); } else { this.correspondingTree = this.addReturn(castToStatementTree(currentTree), getOneFromSet(needed)); } } else { this.correspondingTree = this.addReturn(castToStatementTree(currentTree), getOneFromSet(needed)); } }
@Override public Void visitMethodInvocation(MethodInvocationTree node, Void p) { if (!node.getArguments().isEmpty()) { return null; } final ExpressionTree et = node.getMethodSelect(); if (et.getKind() != Tree.Kind.MEMBER_SELECT) { return null; } final MemberSelectTree mst = (MemberSelectTree) et; if (!FINALIZE.contentEquals(mst.getIdentifier())) { return null; } if (mst.getExpression().getKind() != Tree.Kind.IDENTIFIER) { return null; } if (!SUPER.contentEquals(((IdentifierTree)mst.getExpression()).getName())) { return null; } found = true; return null; }
static boolean checkConstantExpression(final CompilationInfo info, TreePath path) { InstanceRefFinder finder = new InstanceRefFinder(info, path) { @Override public Object visitIdentifier(IdentifierTree node, Object p) { Element el = info.getTrees().getElement(getCurrentPath()); if (el == null || el.asType() == null || el.asType().getKind() == TypeKind.ERROR) { return null; } if (el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.PARAMETER) { throw new StopProcessing(); } else if (el.getKind() == ElementKind.FIELD) { if (!el.getModifiers().contains(Modifier.FINAL)) { throw new StopProcessing(); } } return super.visitIdentifier(node, p); } }; try { finder.process(); return !(finder.containsInstanceReferences() || finder.containsLocalReferences() || finder.containsReferencesToSuper()); } catch (StopProcessing e) { return false; } }
@Override public Void visitMethodInvocation(MethodInvocationTree node, Void p) { if (node.getArguments().isEmpty()) { if (node.getMethodSelect().getKind() == Kind.MEMBER_SELECT) { MemberSelectTree mst = (MemberSelectTree) node.getMethodSelect(); Element e = info.getTrees().getElement(new TreePath(new TreePath(getCurrentPath(), mst), mst.getExpression())); if (parameter.equals(e) && mst.getIdentifier().contentEquals("getClass")) { // NOI18N throw new Found(); } } else if (node.getMethodSelect().getKind() == Kind.IDENTIFIER) { IdentifierTree it = (IdentifierTree) node.getMethodSelect(); if (it.getName().contentEquals("getClass")) { // NOI18N throw new Found(); } } } return super.visitMethodInvocation(node, p); }
/** * If we're assigning to an identifier then we see if this identifier has the same name as one of the * non-final params in scope. We only care about assignments to an identifier. * * Thus, a = 5; would be flagged by array[0] = "foo" would not be flagged. The left hand side of the assignment * operation must be an identifier in order for us to flag it. * * @param assignmentTree assignment AST node * @param nonFinalParamsInScope params to check against the LHS of the assignment */ @Override public Void visitAssignment(AssignmentTree assignmentTree, Set<Name> nonFinalParamsInScope) { if (nonFinalParamsInScope != null && !nonFinalParamsInScope.isEmpty()) { ExpressionTree variable = assignmentTree.getVariable(); variable.accept(new SimpleTreeVisitor<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void aVoid) { if (nonFinalParamsInScope.contains(node.getName())) { // printing a message of type error counts as a compilation error trees.printMessage(Diagnostic.Kind.ERROR, String.format("EFFECTIVELY_FINAL: Assignment to param in `%s`", assignmentTree), node, compilationUnitTree); } return null; } }, null); } return null; }
@Override public String visitAnnotation(AnnotationTree node, Void p) { for (ExpressionTree expressionTree : node.getArguments()) { if (expressionTree instanceof AssignmentTree) { AssignmentTree assignmentTree = (AssignmentTree) expressionTree; ExpressionTree variable = assignmentTree.getVariable(); if (variable instanceof IdentifierTree && ((IdentifierTree) variable).getName().contentEquals(annotationFieldName)) { return scan(expressionTree, p); } } } return null; }
private void resolveResourceVariable(final WorkingCopy wc, TreePath tp, TreeMaker make, TypeMirror proposedType) { final String name = ((IdentifierTree) tp.getLeaf()).getName().toString(); final Element el = wc.getTrees().getElement(tp); if (el == null) { return; } if (tp.getParentPath().getLeaf().getKind() != Kind.ASSIGNMENT) { //? return ; } AssignmentTree at = (AssignmentTree) tp.getParentPath().getLeaf(); VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(proposedType), at.getExpression()); wc.rewrite(at, vt); }
@Override protected boolean perform() { TreePath replacePath = replacePathHandle.resolve(copy); if (replacePath == null) { Logger.getAnonymousLogger().warning(String.format("Attempt to change import for FQN: %s, but the import cannot be resolved in the current context", fqn)); return false; } Element el = toImport.resolve(copy); if (el == null) { return false; } CharSequence elFQN = copy.getElementUtilities().getElementName(el, true); IdentifierTree id = copy.getTreeMaker().Identifier(elFQN); copy.rewrite(replacePath.getLeaf(), id); for (TreePathHandle tph : additionalLocations) { replacePath = tph.resolve(copy); if (replacePath == null) { continue; } copy.rewrite(replacePath.getLeaf(), id); } return false; }
private static boolean invocationOnThis(MethodInvocationTree mit) { Tree select = mit.getMethodSelect(); switch (select.getKind()) { case IDENTIFIER: return true; case MEMBER_SELECT: if (((MemberSelectTree) select).getExpression().getKind() == Kind.IDENTIFIER) { IdentifierTree ident = (IdentifierTree) ((MemberSelectTree) select).getExpression(); return ident.getName().contentEquals("this"); } } return false; }
@TriggerPattern(value="synchronized ($this) { $stmts$; }") public static ErrorDescription hint(HintContext ctx) { TreePath thisVariable = ctx.getVariables().get("$this"); if (thisVariable.getLeaf().getKind() != Kind.IDENTIFIER || !((IdentifierTree) thisVariable.getLeaf()).getName().contentEquals(THIS_KEYWORD)) { return null; } TreePath anonClassTP = getParentClass(ctx.getPath()); Element annonClass = ctx.getInfo().getTrees().getElement(anonClassTP); String key = getKey(annonClass); if (key != null) { Element parent = ctx.getInfo().getTrees().getElement(getParentClass(anonClassTP.getParentPath())); if (parent == null || (!parent.getKind().isClass() && !parent.getKind().isInterface())) { return null; } Fix fix = new FixImpl(TreePathHandle.create(thisVariable, ctx.getInfo()), ElementHandle.create((TypeElement) parent)).toEditorFix(); String displayName = NbBundle.getMessage(ThisInAnonymous.class, key); return ErrorDescriptionFactory.forName(ctx, thisVariable, displayName, fix); } return null; }
/** */ private List<IdentifierTree> createIdentifiers( TreeMaker maker, List<VariableTree> variables) { List<IdentifierTree> identifiers; if (variables.isEmpty()) { identifiers = Collections.<IdentifierTree>emptyList(); } else { identifiers = new ArrayList<IdentifierTree>(variables.size()); for (VariableTree var : variables) { identifiers.add(maker.Identifier(var.getName().toString())); } } return identifiers; }
private StatementTree generateEJBCleanUpCode(TreeMaker maker) { IdentifierTree container = maker.Identifier(CONTAINER_VAR_NAME); MethodInvocationTree invocation = maker.MethodInvocation( Collections.<ExpressionTree>emptyList(), maker.MemberSelect(container, "close"), // NOI18N Collections.<ExpressionTree>emptyList() ); return maker.ExpressionStatement(invocation); }
@Override public Tree visitIdentifier(IdentifierTree tree, Void p) { IdentifierTree n = make.Identifier(tree.getName()); model.setElement(n, model.getElement(tree)); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
protected void doModification(ResultIterator resultIterator) throws Exception { WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult()); copy.toPhase(Phase.RESOLVED); TreeMaker tm = copy.getTreeMaker(); GeneratorUtilities gu = GeneratorUtilities.get(copy); CompilationUnitTree cut = copy.getCompilationUnit(); ClassTree ct = (ClassTree) cut.getTypeDecls().get(0); VariableTree field = (VariableTree)ct.getMembers().get(1); List<Tree> members = new ArrayList<Tree>(); AssignmentTree stat = tm.Assignment(tm.Identifier("name"), tm.Literal("Name")); //NOI18N BlockTree init = tm.Block(Collections.singletonList(tm.ExpressionStatement(stat)), false); members.add(init); members.add(gu.createConstructor(ct, Collections.<VariableTree>emptyList())); members.add(gu.createGetter(field)); ModifiersTree mods = tm.Modifiers(EnumSet.of(Modifier.PRIVATE)); ClassTree inner = tm.Class(mods, "Inner", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList()); //NOI18N members.add(inner); mods = tm.Modifiers(EnumSet.of(Modifier.PRIVATE, Modifier.STATIC)); ClassTree nested = tm.Class(mods, "Nested", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList()); //NOI18N members.add(nested); IdentifierTree nestedId = tm.Identifier("Nested"); //NOI18N VariableTree staticField = tm.Variable(mods, "instance", nestedId, null); //NOI18N members.add(staticField); NewClassTree nct = tm.NewClass(null, Collections.<ExpressionTree>emptyList(), nestedId, Collections.<ExpressionTree>emptyList(), null); stat = tm.Assignment(tm.Identifier("instance"), nct); //NOI18N BlockTree staticInit = tm.Block(Collections.singletonList(tm.ExpressionStatement(stat)), true); members.add(staticInit); members.add(gu.createGetter(staticField)); ClassTree newCT = gu.insertClassMembers(ct, members); copy.rewrite(ct, newCT); }
private static Name getSimpleName(Tree t) { if (t.getKind() == Kind.IDENTIFIER) { return ((IdentifierTree) t).getName(); } if (t.getKind() == Kind.MEMBER_SELECT) { return ((MemberSelectTree) t).getIdentifier(); } throw new UnsupportedOperationException(); }
private boolean fillFirstArgument( ExpressionTree e, List<ExpressionTree> items, Indent indent) { // is there a trailing dereference? if (items.size() < 2) { return false; } // don't special-case calls nested inside expressions if (e.getKind() != METHOD_INVOCATION) { return false; } MethodInvocationTree methodInvocation = (MethodInvocationTree) e; Name name = getMethodName(methodInvocation); if (!(methodInvocation.getMethodSelect() instanceof IdentifierTree) || name.length() > 4 || !methodInvocation.getTypeArguments().isEmpty() || methodInvocation.getArguments().size() != 1) { return false; } builder.open(ZERO); builder.open(indent); visit(name); token("("); ExpressionTree arg = getOnlyElement(methodInvocation.getArguments()); scan(arg, null); builder.close(); token(")"); builder.close(); return true; }
@Override public Object visitIdentifier(IdentifierTree node, Object p) { if (!fieldNames.contains(node.getName())) { return null; } // TODO do not track dependencies for method refs boolean ok = false; Tree parent = getCurrentPath().getParentPath().getLeaf(); switch (parent.getKind()) { case MEMBER_SELECT: // dependency is only introduced by dereferencing the identifier. ok = ((MemberSelectTree)parent).getExpression() != node; break; case ASSIGNMENT: ok = ((AssignmentTree)parent).getVariable() == node; break; } if (ok) { return null; } if (!ok) { if (collectNames) { if (node.getName().equals(insertedName)) { revDependencies.add(member); } } else { addDependency(node.getName()); } } return null; }
private static String name(Tree tree) { switch (tree.getKind()) { case VARIABLE: return ((VariableTree)tree).getName().toString(); case METHOD: return ((MethodTree)tree).getName().toString(); case CLASS: return ((ClassTree)tree).getSimpleName().toString(); case IDENTIFIER: return ((IdentifierTree)tree).getName().toString(); case MEMBER_SELECT: return name(((MemberSelectTree)tree).getExpression()) + '.' + ((MemberSelectTree)tree).getIdentifier(); } return ""; //NOI18N }
private static VariableTree createLoggerField(TreeMaker make, ClassTree cls, CharSequence name, Set<Modifier> mods) { ModifiersTree modifiers = make.Modifiers(mods, Collections.<AnnotationTree>emptyList()); final List<ExpressionTree> none = Collections.<ExpressionTree>emptyList(); IdentifierTree className = make.Identifier(cls.getSimpleName()); MemberSelectTree classType = make.MemberSelect(className, "class"); // NOI18N MemberSelectTree getName = make.MemberSelect(classType, "getName"); // NOI18N MethodInvocationTree initClass = make.MethodInvocation(none, getName, none); final ExpressionTree logger = make.QualIdent(Logger.class.getName()); MemberSelectTree getLogger = make.MemberSelect(logger, "getLogger"); // NOI18N MethodInvocationTree initField = make.MethodInvocation(none, getLogger, Collections.nCopies(1, initClass)); return make.Variable(modifiers, name, logger, initField); // NOI18N }
public Void visitIdentifier(IdentifierTree node, Object p) { System.err.println("visitIdentifier: " + node.getName()); super.visitIdentifier(node, p); System.err.println("I: " + node); IdentifierTree copy = make.setLabel(node, node.getName() + "0"); this.copy.rewrite(node, copy); return null; }
public void testRewriteRewrittenTree2() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " String a;\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " Object a;\n" + "}\n"; JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile)); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws java.io.IOException { workingCopy.toPhase(Phase.RESOLVED); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0); VariableTree var = (VariableTree) clazz.getMembers().get(1); IdentifierTree i = make.Identifier("Test"); workingCopy.rewrite(var.getType(), i); workingCopy.rewrite(i, make.Identifier("Object")); } }; testSource.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
public void testRenameInImpl() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "import java.util.*;\n\n" + "public class Test<E> extends Object implements List {\n" + " public void taragui() {\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "import java.util.*;\n\n" + "public class Test<E> extends Object implements Seznam {\n" + " public void taragui() {\n" + " }\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); for (Tree typeDecl : cut.getTypeDecls()) { // should check kind, here we can be sure! ClassTree clazz = (ClassTree) typeDecl; IdentifierTree ident = (IdentifierTree) clazz.getImplementsClause().get(0); workingCopy.rewrite(ident, make.setLabel(ident, "Seznam")); } } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
public void testRenameInImpl2() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "import java.util.*;\n\n" + "public class Test<E> extends Object implements PropertyChangeListener, List {\n" + " public void taragui() {\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "import java.util.*;\n\n" + "public class Test<E> extends Object implements PropertyChangeListener, Seznam {\n" + " public void taragui() {\n" + " }\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); for (Tree typeDecl : cut.getTypeDecls()) { // should check kind, here we can be sure! ClassTree clazz = (ClassTree) typeDecl; IdentifierTree ident = (IdentifierTree) clazz.getImplementsClause().get(1); workingCopy.rewrite(ident, make.setLabel(ident, "Seznam")); } } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }