private static ErrorDescription compute(HintContext ctx, String methodName) { TreePath message = ctx.getVariables().get("$message"); List<List<TreePath>> sorted = Utilities.splitStringConcatenationToElements(ctx.getInfo(), message); if (sorted.size() <= 1) { return null; } //check for erroneous trees: for (List<TreePath> tps : sorted) for (TreePath tp : tps) if (tp.getLeaf().getKind() == Kind.ERRONEOUS) return null; FixImpl fix = new FixImpl(NbBundle.getMessage(LoggerStringConcat.class, "MSG_LoggerStringConcat_fix"), methodName, TreePathHandle.create(ctx.getPath(), ctx.getInfo()), TreePathHandle.create(message, ctx.getInfo())); return ErrorDescriptionFactory.forTree(ctx, message, NbBundle.getMessage(LoggerStringConcat.class, "MSG_LoggerStringConcat"), fix.toEditorFix()); }
private void typeUsed(Element decl, TreePath expr, boolean methodInvocation) { if (decl != null && (expr == null || expr.getLeaf().getKind() == Kind.IDENTIFIER || expr.getLeaf().getKind() == Kind.PARAMETERIZED_TYPE)) { if (!isErroneous(decl)) { ImportTree imp = element2Import.get(decl); if (imp != null) { addUsage(imp); if (isStar(imp)) { //TODO: explain handleUnresolvableImports(decl, methodInvocation, false); } } } else { handleUnresolvableImports(decl, methodInvocation, true); for (Entry<Element, ImportTree> e : element2Import.entrySet()) { if (importedBySingleImport.contains(e.getKey())) continue; if (e.getKey().getSimpleName().equals(decl.getSimpleName())) { import2Highlight.remove(e.getValue()); } } } } }
@Hint(displayName = "#LBL_Empty_BLOCK", description = "#DSC_Empty_BLOCK", category = "empty", hintKind = Hint.Kind.INSPECTION, severity = Severity.VERIFIER, suppressWarnings = SUPPRESS_WARNINGS_KEY, id = "EmptyStatements_BLOCK") @TriggerTreeKind(Tree.Kind.EMPTY_STATEMENT) @NbBundle.Messages({"ERR_EmptyBLOCK=Remove semicolon"}) public static ErrorDescription forBLOCK(HintContext ctx) { Tree parent = ctx.getPath().getParentPath().getLeaf(); if (!EnumSet.of(Kind.BLOCK).contains(parent.getKind())) { return null; } final List<Fix> fixes = new ArrayList<>(); fixes.add(FixFactory.createSuppressWarningsFix(ctx.getInfo(), ctx.getPath(), SUPPRESS_WARNINGS_KEY)); fixes.add(JavaFixUtilities.removeFromParent(ctx, Bundle.ERR_EmptyBLOCK(), ctx.getPath())); return createErrorDescription(ctx, ctx.getPath().getLeaf(), fixes, Kind.BLOCK); }
private String fqnFor(Tree t) { Element el = ASTService.getElementImpl(t); if (el != null) { if (el.getKind().isClass() || el.getKind().isInterface() || el.getKind() == ElementKind.PACKAGE) { return ((QualifiedNameable) el).getQualifiedName().toString(); } else { Logger.getLogger(ElementOverlay.class.getName()).log(Level.SEVERE, "Not a QualifiedNameable: {0}", el); return null; } } else if (t instanceof QualIdentTree) { return ((QualIdentTree) t).getFQN(); } else if (t.getKind() == Kind.PARAMETERIZED_TYPE) { return fqnFor(((ParameterizedTypeTree) t).getType()); } else { Logger.getLogger(ElementOverlay.class.getName()).log(Level.FINE, "No element and no QualIdent"); return null; } }
protected int diffDoLoop(JCDoWhileLoop oldT, JCDoWhileLoop newT, int[] bounds) { int localPointer = bounds[0]; int[] bodyBounds = new int[] { localPointer, endPos(oldT.body) }; int oldIndent = newT.body.hasTag(Tag.BLOCK) ? -1 : printer.indent(); localPointer = diffTree(oldT.body, newT.body, bodyBounds, oldT.getKind()); if (!newT.body.hasTag(Tag.BLOCK)) printer.undent(oldIndent); int[] condBounds = getBounds(oldT.cond); if (oldT.body.getKind() != Kind.BLOCK && newT.body.getKind() == Kind.BLOCK) { moveBackToToken(tokenSequence, condBounds[0], JavaTokenId.WHILE); localPointer = tokenSequence.offset(); } else { copyTo(localPointer, condBounds[0]); localPointer = diffTree(oldT.cond, newT.cond, condBounds); } copyTo(localPointer, bounds[1]); return bounds[1]; }
public Kind getKindLiteral() { switch (this) { case INT: return Kind.INT_LITERAL; case LONG: return Kind.LONG_LITERAL; case FLOAT: return Kind.FLOAT_LITERAL; case DOUBLE: return Kind.DOUBLE_LITERAL; case BOOLEAN: return Kind.BOOLEAN_LITERAL; case CHAR: return Kind.CHAR_LITERAL; case CLASS: return Kind.STRING_LITERAL; case BOT: return Kind.NULL_LITERAL; default: throw new AssertionError("unknown literal kind " + this); } }
@Override protected void performRewrite(TransformationContext ctx) { WorkingCopy wc = ctx.getWorkingCopy(); TreePath path = ctx.getPath(); TypeCastTree tct = (TypeCastTree) path.getLeaf(); ExpressionTree expression = tct.getExpression(); while (expression.getKind() == Kind.PARENTHESIZED && !JavaFixUtilities.requiresParenthesis(((ParenthesizedTree) expression).getExpression(), tct, path.getParentPath().getLeaf())) { expression = ((ParenthesizedTree) expression).getExpression(); } while (path.getParentPath().getLeaf().getKind() == Kind.PARENTHESIZED && !JavaFixUtilities.requiresParenthesis(expression, path.getLeaf(), path.getParentPath().getParentPath().getLeaf())) { path = path.getParentPath(); } wc.rewrite(path.getLeaf(), expression); }
protected boolean generateClassBody(TreePath p) throws Exception { Element e = copy.getTrees().getElement(p); boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface()); if (isUsableElement) { return true; } if (e.getKind() == ElementKind.ENUM_CONSTANT) { VariableTree var = (VariableTree) p.getLeaf(); if (var.getInitializer() != null && var.getInitializer().getKind() == Kind.NEW_CLASS) { NewClassTree nct = (NewClassTree) var.getInitializer(); if (nct.getClassBody() != null) { return true; } } } return !generateClassBody2(copy, p); }
@Override protected void performRewrite(TransformationContext ctx) throws Exception { WorkingCopy wc = ctx.getWorkingCopy(); Tree.Kind k = ctx.getPath().getLeaf().getKind(); if (!TreeUtilities.CLASS_TREE_KINDS.contains(k)) { // TODO: report return; } ClassTree ct = (ClassTree)ctx.getPath().getLeaf(); ModifiersTree mt = ct.getModifiers(); Set<Modifier> mods = new HashSet<>(mt.getFlags()); mods.remove(Modifier.FINAL); mods.add(Modifier.ABSTRACT); ModifiersTree newMt = wc.getTreeMaker().Modifiers(mods, mt.getAnnotations()); wc.rewrite(mt, newMt); }
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", description = "#DESC_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", category = "assignment_issues", enabled = false, suppressWarnings = "AssignmentToCatchBlockParameter", options=Options.QUERY) //NOI18N @TriggerTreeKind(Kind.CATCH) public static List<ErrorDescription> assignmentToCatchBlockParameter(HintContext context) { final Trees trees = context.getInfo().getTrees(); final TreePath catchPath = context.getPath(); final Element param = trees.getElement(TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getParameter())); if (param == null || param.getKind() != ElementKind.EXCEPTION_PARAMETER) { return null; } final TreePath block = TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getBlock()); final List<TreePath> paths = new LinkedList<TreePath>(); new AssignmentFinder(trees, param).scan(block, paths); final List<ErrorDescription> ret = new ArrayList<ErrorDescription>(paths.size()); for (TreePath path : paths) { ret.add(ErrorDescriptionFactory.forTree(context, path, NbBundle.getMessage(AssignmentIssues.class, "MSG_AssignmentToCatchBlockParameter", param.getSimpleName()))); //NOI18N } return ret; }
@Override public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) { if (treePath.getLeaf().getKind() == Kind.METHOD) { MethodTree mt = (MethodTree) treePath.getLeaf(); TreePath parentPath = treePath.getParentPath(); ClassTree ct = (ClassTree) parentPath.getLeaf(); Trees trees = compilationInfo.getTrees(); Types types = compilationInfo.getTypes(); TreeUtilities tu = compilationInfo.getTreeUtilities(); TypeMirror type = types.erasure(trees.getTypeMirror(treePath)); if (!Utilities.isValidType(type)) { return null; } for (Tree member : ct.getMembers()) { TreePath memberPath = new TreePath(parentPath, member); if (member.getKind() == Kind.METHOD && "<init>".contentEquals(((MethodTree)member).getName()) //NOI18N && !tu.isSynthetic(memberPath) && types.isSameType(types.erasure(trees.getTypeMirror(memberPath)), type)) { return null; } } RenameConstructorFix fix = new RenameConstructorFix(compilationInfo.getSnapshot().getSource(), TreePathHandle.create(treePath, compilationInfo), offset, mt.getName(), ct.getSimpleName()); return Collections.<Fix>singletonList(fix); } return null; }
private static TreePath findOuterIf(HintContext ctx, TreePath treePath) { while (!ctx.isCanceled()) { treePath = treePath.getParentPath(); if (treePath == null) { break; } Tree leaf = treePath.getLeaf(); if (leaf.getKind() == Kind.IF) { return treePath; } if (leaf.getKind() == Kind.BLOCK) { BlockTree b = (BlockTree)leaf; if (b.getStatements().size() == 1) { // ok, empty blocks can be around synchronized(this) // statements continue; } } return null; } return null; }
public CompoundAssignmentTree CompoundAssignment(Kind operator, ExpressionTree variable, ExpressionTree expression) { final Tag op; switch (operator) { case MULTIPLY_ASSIGNMENT: op = JCTree.Tag.MUL_ASG; break; case DIVIDE_ASSIGNMENT: op = JCTree.Tag.DIV_ASG; break; case REMAINDER_ASSIGNMENT: op = JCTree.Tag.MOD_ASG; break; case PLUS_ASSIGNMENT: op = JCTree.Tag.PLUS_ASG; break; case MINUS_ASSIGNMENT: op = JCTree.Tag.MINUS_ASG; break; case LEFT_SHIFT_ASSIGNMENT: op = JCTree.Tag.SL_ASG; break; case RIGHT_SHIFT_ASSIGNMENT: op = JCTree.Tag.SR_ASG; break; case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: op = JCTree.Tag.USR_ASG; break; case AND_ASSIGNMENT: op = JCTree.Tag.BITAND_ASG; break; case XOR_ASSIGNMENT: op = JCTree.Tag.BITXOR_ASG; break; case OR_ASSIGNMENT: op = JCTree.Tag.BITOR_ASG; break; default: throw new IllegalArgumentException("Illegal binary operator: " + operator); } return make.at(NOPOS).Assignop(op, (JCExpression)variable, (JCExpression)expression); }
public UnaryTree Unary(Kind operator, ExpressionTree arg) { final Tag op; switch (operator) { case POSTFIX_INCREMENT: op = JCTree.Tag.POSTINC; break; case POSTFIX_DECREMENT: op = JCTree.Tag.POSTDEC; break; case PREFIX_INCREMENT: op = JCTree.Tag.PREINC; break; case PREFIX_DECREMENT: op = JCTree.Tag.PREDEC; break; case UNARY_PLUS: op = JCTree.Tag.POS; break; case UNARY_MINUS: op = JCTree.Tag.NEG; break; case BITWISE_COMPLEMENT: op = JCTree.Tag.COMPL; break; case LOGICAL_COMPLEMENT: op = JCTree.Tag.NOT; break; default: throw new IllegalArgumentException("Illegal unary operator: " + operator); } return make.at(NOPOS).Unary(op, (JCExpression)arg); }
public WildcardTree Wildcard(Kind kind, Tree type) { final BoundKind boundKind; switch (kind) { case UNBOUNDED_WILDCARD: boundKind = BoundKind.UNBOUND; break; case EXTENDS_WILDCARD: boundKind = BoundKind.EXTENDS; break; case SUPER_WILDCARD: boundKind = BoundKind.SUPER; break; default: throw new IllegalArgumentException("Unknown wildcard bound " + kind); } TypeBoundKind tbk = make.at(NOPOS).TypeBoundKind(boundKind); return make.at(NOPOS).Wildcard(tbk, (JCExpression)type); }
public void testParseAndAttributeMultipleStatementsWithBefore() throws Exception { prepareTest("test/Test.java", "package test; public class Test{}"); Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap()); Tree result = Utilities.parseAndAttribute(info, "$before$; String $2 = $1; int $l = $2.length(); System.err.println($l);", s); assertTrue(result.getKind().name(), result.getKind() == Kind.BLOCK); String golden = "{\n" + " $before$;\n" + " String $2 = $1;\n" + " int $l = $2.length();\n" + " System.err.println($l);\n" + " $$2$;\n" + "}"; assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " ")); }
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; }
private boolean checkAssignmentInsideExpression() { Tree exp1 = getCurrentPath().getLeaf(); Tree parent = getCurrentPath().getParentPath().getLeaf(); if (parent.getKind() != Tree.Kind.EXPRESSION_STATEMENT) { // XXX would be useful if Problems support HTML // String code = parent.toString(); // String replace = exp1.toString(); // code = code.replace(replace, "<b>" + replace + "</b>"); problem = createProblem( problem, false, NbBundle.getMessage( EncapsulateFieldRefactoringPlugin.class, "ERR_EncapsulateInsideAssignment", // NOI18N exp1.toString(), parent.toString(), FileUtil.getFileDisplayName(workingCopy.getFileObject()))); return false; } return true; }
@Hint(displayName="#DN_memberReference2Lambda", description="#DESC_memberReference2Lambda", category="suggestions", hintKind=Hint.Kind.ACTION) @Messages({ "DN_memberReference2Lambda=Convert Member Reference to Lambda Expression", "DESC_memberReference2Lambda=Converts member references to lambda expressions", "ERR_memberReference2Lambda=", "FIX_memberReference2Lambda=Use lambda expression" }) @TriggerTreeKind(Kind.MEMBER_REFERENCE) public static ErrorDescription reference2Lambda(HintContext ctx) { Element refered = ctx.getInfo().getTrees().getElement(ctx.getPath()); if (refered == null || refered.getKind() != ElementKind.METHOD) { return null;//XXX: constructors! } return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.ERR_memberReference2Lambda(), new MemberReference2Lambda(ctx.getInfo(), ctx.getPath()).toEditorFix()); }
@Hint(displayName = "#LBL_Empty_IF", description = "#DSC_Empty_IF", category = "empty", hintKind = Hint.Kind.INSPECTION, severity = Severity.VERIFIER, suppressWarnings = SUPPRESS_WARNINGS_KEY, id = "EmptyStatements_IF", enabled = false) @TriggerTreeKind(Tree.Kind.EMPTY_STATEMENT) public static ErrorDescription forIF(HintContext ctx) { final TreePath treePath = ctx.getPath(); Tree parent = treePath.getParentPath().getLeaf(); if (!EnumSet.of(Kind.IF).contains(parent.getKind())) { return null; } TreePath treePathForWarning = treePath; IfTree it = (IfTree) parent; if (it.getThenStatement() != null && it.getThenStatement().getKind() == Tree.Kind.EMPTY_STATEMENT) { treePathForWarning = treePath.getParentPath(); } if (it.getElseStatement() != null && it.getElseStatement().getKind() == Tree.Kind.EMPTY_STATEMENT) { treePathForWarning = treePath; } final List<Fix> fixes = new ArrayList<>(); fixes.add(FixFactory.createSuppressWarningsFix(ctx.getInfo(), treePathForWarning, SUPPRESS_WARNINGS_KEY)); return createErrorDescription(ctx, parent, fixes, parent.getKind()); }
public void testParseAndAttributeMultipleStatementsWithAfter() throws Exception { prepareTest("test/Test.java", "package test; public class Test{}"); Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap()); Tree result = Utilities.parseAndAttribute(info, "String $2 = $1; int $l = $2.length(); System.err.println($l); $after$;", s); assertTrue(result.getKind().name(), result.getKind() == Kind.BLOCK); String golden = "{\n" + " $$1$;\n" + " String $2 = $1;\n" + " int $l = $2.length();\n" + " System.err.println($l);\n" + " $after$;\n" + "}"; assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " ")); }
/** * Works as TreeUtilities.isSynthetic, but treats implicit annotation parameter (value) as * non-synthetic. See defect #270036 */ public static boolean isSyntheticPath(CompilationInfo ci, TreePath path) { TreeUtilities tu = ci.getTreeUtilities(); if (path == null) throw new NullPointerException(); while (path != null) { SYNT: if (isSynthetic(ci, path.getCompilationUnit(), path.getLeaf())) { if (path.getLeaf().getKind() == Tree.Kind.ASSIGNMENT && path.getParentPath() != null && path.getParentPath().getLeaf().getKind() == Tree.Kind.ANNOTATION) { AssignmentTree aTree = (AssignmentTree)path.getLeaf(); if (aTree.getVariable().getKind() == Tree.Kind.IDENTIFIER && ((IdentifierTree)aTree.getVariable()).getName().contentEquals("value")) { // implicit value is not synthetic break SYNT; } } return true; } path = path.getParentPath(); } return false; }
@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; }
@Override public Void scan(TreePath path, Map<HintDescription, List<ErrorDescription>> p) { Kind k = path.getLeaf().getKind(); boolean b = pushSuppressWarrnings(path); try { runAndAdd(path, hints.get(k), p); if (isCanceled()) { return null; } return super.scan(path, p); } finally { if (b) { suppresWarnings.pop(); } } }
private static ExecutableElement resolveMethodElement(CompilationInfo info, int caret) { TreePath path = info.getTreeUtilities().pathFor(caret); while (path != null && path.getLeaf().getKind() != Kind.METHOD) { path = path.getParentPath(); } if (path == null) { return null; } Element resolved = info.getTrees().getElement(path); if (resolved == null || resolved.getKind() != ElementKind.METHOD) { return null; } return (ExecutableElement) resolved; }
static void prepareTypeVars(TreePath method, CompilationInfo info, Map<TypeMirror, TreePathHandle> typeVar2Def, List<TreePathHandle> typeVars) throws IllegalArgumentException { if (method.getLeaf().getKind() == Kind.METHOD) { MethodTree mt = (MethodTree) method.getLeaf(); for (TypeParameterTree tv : mt.getTypeParameters()) { TreePath def = new TreePath(method, tv); TypeMirror type = info.getTrees().getTypeMirror(def); if (type != null && type.getKind() == TypeKind.TYPEVAR) { TreePathHandle tph = TreePathHandle.create(def, info); typeVar2Def.put(type, tph); typeVars.add(tph); } } } }
@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; }
@TriggerTreeKind(Kind.MEMBER_SELECT) public static List<ErrorDescription> run(HintContext ctx) { CompilationInfo compilationInfo = ctx.getInfo(); TreePath treePath = ctx.getPath(); int[] span = new int[2]; int[] kind = new int[1]; String[] simpleName = new String[1]; Fix fix = computeFixes(compilationInfo, treePath, span, kind, simpleName); if (fix == null) { return null; } ErrorDescription ed = ErrorDescriptionFactory.forName( ctx, ctx.getPath(), NbBundle.getMessage(StaticAccess.class, "MSG_StaticAccess", kind[0], simpleName[0]), // NOI18N fix ); return Collections.singletonList(ed); }
public void testGetterNamingConvention0() throws Exception {//#165241 performTest("package test;\npublic class Test {\nprivate int eMai;\npublic Test(){\n}\n }\n", new GetterSetterTask(34, false), new Validator() { public void validate(CompilationInfo info) { ClassTree ct = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0); for (Tree member : ct.getMembers()) { if (member.getKind() == Kind.METHOD) { String name = ((MethodTree) member).getName().toString(); if (!name.equals("<init>")) { assertEquals(name, "seteMai"); } } } } }); }
@Override protected void performRewrite(JavaFix.TransformationContext ctx) throws Exception { Tree t = ctx.getPath().getLeaf(); if (t.getKind() != Tree.Kind.METHOD_INVOCATION) { return; } MethodInvocationTree mi = (MethodInvocationTree)t; if (mi.getMethodSelect().getKind() != Tree.Kind.MEMBER_SELECT) { return; } MemberSelectTree selector = ((MemberSelectTree)mi.getMethodSelect()); TreeMaker maker = ctx.getWorkingCopy().getTreeMaker(); ExpressionTree ms = maker.MemberSelect(maker.QualIdent("java.util.Arrays"), deep ? "deepHashCode" : "hashCode"); // NOI18N Tree nue = maker.MethodInvocation( Collections.<ExpressionTree>emptyList(), ms, Collections.singletonList(selector.getExpression()) ); ctx.getWorkingCopy().rewrite(t, nue); }
public static boolean isInConstructor(TreePath path) { TreePath method = findOwningExecutable(path, false); if (method == null || method.getLeaf().getKind() != Tree.Kind.METHOD) { return false; } return ((MethodTree)method.getLeaf()).getName().contentEquals("<init>"); // NOI18N }
private static boolean isErroneousExpression(StatementTree statement) { if ( statement instanceof ExpressionStatementTree ) { if ( ((ExpressionStatementTree)statement).getExpression().getKind() == Kind.ERRONEOUS ) { return true; } } return false; }
/** * special treatment for anonymous classes to resolve the proper constructor * of extended class instead of the synthetic one. * @see <a href="https://netbeans.org/bugzilla/show_bug.cgi?id=168775">#168775</a> */ private Element resolveAnonymousClassConstructor(Element el, NewClassTree tree, final Trees trees) { if (el != null && tree.getClassBody() != null) { Tree t = trees.getTree(el); if (t != null && t.getKind() == Tree.Kind.METHOD) { MethodTree constructorTree = (MethodTree) t; Tree superCall = constructorTree.getBody().getStatements().get(0); TreePath superCallPath = trees.getPath( getCurrentPath().getCompilationUnit(), ((ExpressionStatementTree) superCall).getExpression()); el = trees.getElement(superCallPath); } } return el; }
@Override protected boolean executeRound(Element el, int round) throws Exception { if (el.getKind() != ElementKind.ENUM) { return false; } ClassTree ct = (ClassTree)path.getLeaf(); for (ListIterator<? extends Tree> it = ct.getMembers().listIterator(ct.getMembers().size()); it.hasPrevious(); ) { Tree t = it.previous(); if (t.getKind() != Tree.Kind.VARIABLE) { continue; } TreePath p = new TreePath(path, t); Element e = copy.getTrees().getElement(p); if (e == null || e.getKind() != ElementKind.ENUM_CONSTANT) { continue; } switch (round) { case 0: if (!generateClassBody(p)) { return false; } break; case 1: if (!generateImplementation(el, p)) { return false; } break; default: throw new IllegalStateException(); } } return true; }
public void testParseAndAttributeMethodDeclarationWithMultiparameters() throws Exception { prepareTest("test/Test.java", "package test; public class Test{}"); Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap()); Tree result = Utilities.parseAndAttribute(info, "public void t($params$) {}", s); assertTrue(result.getKind().name(), result.getKind() == Kind.METHOD); String golden = " public void t($params$) { }"; assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " ")); }
public void testParseAndAttributeVariable() throws Exception { prepareTest("test/Test.java", "package test; public class Test{}"); Scope s = Utilities.constructScope(info, Collections.singletonMap("$1", info.getTreeUtilities().parseType("int", info.getTopLevelElements().get(0)))); Tree result = Utilities.parseAndAttribute(info, "int $2 = $1;", s); assertTrue(result.getKind().name(), result.getKind() == Kind.VARIABLE); }
@Override public Boolean visitAnnotation(AnnotationTree node, TreePath p) { if (p == null) return super.visitAnnotation(node, p); AnnotationTree t = (AnnotationTree) p.getLeaf(); List<? extends ExpressionTree> arguments = t.getArguments(); if (arguments.size() == 1) { ExpressionTree arg = arguments.get(0); if (arg.getKind() == Kind.ASSIGNMENT) { AssignmentTree at = (AssignmentTree) arg; if ( at.getVariable().getKind() == Kind.IDENTIFIER && isMultistatementWildcardTree(at.getExpression()) && ((IdentifierTree) at.getVariable()).getName().contentEquals("value")) { arguments = Collections.singletonList(at.getExpression()); } } } if (!checkLists(node.getArguments(), arguments, p)) return false; return scan(node.getAnnotationType(), t.getAnnotationType(), p); }
@Override public Void visitWildcard(WildcardTree node, EnumSet<UseTypes> p) { if (node.getBound() != null && node.getBound().getKind() == Kind.IDENTIFIER) { handlePossibleIdentifier(new TreePath(getCurrentPath(), node.getBound()), EnumSet.of(UseTypes.CLASS_USE)); } return super.visitWildcard(node, p); }
private TreePath findStatement(TreePath tp) { TreePath statement = tp; while (statement.getLeaf().getKind() != Kind.COMPILATION_UNIT) { if (isStatement(statement.getLeaf())) { return statement; } statement = statement.getParentPath(); } return null; }