Java Code Examples for com.sun.source.tree.Tree.Kind#METHOD
The following examples show how to use
com.sun.source.tree.Tree.Kind#METHOD .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utilities.java From netbeans with Apache License 2.0 | 6 votes |
public static TreePath findOwningExecutable(TreePath from, boolean lambdaOrInitializer) { Tree.Kind k = null; OUTER: while (from != null && !(TreeUtilities.CLASS_TREE_KINDS.contains(k = from.getLeaf().getKind()))) { switch (k) { case METHOD: break OUTER; case LAMBDA_EXPRESSION: return lambdaOrInitializer ? from : null; case BLOCK: { TreePath par = from.getParentPath(); Tree l = par.getLeaf(); if (TreeUtilities.CLASS_TREE_KINDS.contains(l.getKind())) { return lambdaOrInitializer ? from : null; } } } from = from.getParentPath(); } return (from == null || k != Kind.METHOD) ? null : from; }
Example 2
Source File: GoToSuperTypeAction.java From netbeans with Apache License 2.0 | 6 votes |
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; }
Example 3
Source File: UtilityClass.java From netbeans with Apache License 2.0 | 6 votes |
@Hint(id="org.netbeans.modules.java.hints.UtilityClass_2", displayName="#MSG_PublicConstructor", description="#HINT_PublicConstructor", category="api", enabled=false, severity=Severity.HINT, suppressWarnings="UtilityClassWithPublicConstructor") @TriggerTreeKind(Kind.METHOD) public static ErrorDescription constructor(HintContext ctx) { CompilationInfo compilationInfo = ctx.getInfo(); TreePath treePath = ctx.getPath(); Element e = compilationInfo.getTrees().getElement(treePath); if (e == null) { return null; } if ( e.getKind() != ElementKind.CONSTRUCTOR || compilationInfo.getElementUtilities().isSynthetic(e) || (!e.getModifiers().contains(Modifier.PROTECTED) && !e.getModifiers().contains(Modifier.PUBLIC))) { return null; } if (!isUtilityClass(compilationInfo, e.getEnclosingElement())) return null; return ErrorDescriptionFactory.forName(ctx, treePath, NbBundle.getMessage(UtilityClass.class, "MSG_PublicConstructor"), new FixImpl(false, TreePathHandle.create(e, compilationInfo) ).toEditorFix()); }
Example 4
Source File: IntroduceHint.java From netbeans with Apache License 2.0 | 6 votes |
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); } } } }
Example 5
Source File: ClassStructure.java From netbeans with Apache License 2.0 | 5 votes |
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.protectedMemberInFinalClass", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.protectedMemberInFinalClass", category = "class_structure", enabled = false, suppressWarnings = {"ProtectedMemberInFinalClass"}) //NOI18N @TriggerTreeKind({Kind.METHOD, Kind.VARIABLE}) public static ErrorDescription protectedMemberInFinalClass(HintContext context) { final Tree tree = context.getPath().getLeaf(); final Tree parent = context.getPath().getParentPath().getLeaf(); if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind())) { if (tree.getKind() == Kind.METHOD) { final MethodTree mth = (MethodTree) tree; if (mth.getModifiers().getFlags().contains(Modifier.PROTECTED) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.FINAL)) { Element el = context.getInfo().getTrees().getElement(context.getPath()); if (el == null || el.getKind() != ElementKind.METHOD) { return null; } List<ElementDescription> overrides = new LinkedList<ElementDescription>(); ComputeOverriding.detectOverrides(context.getInfo(), (TypeElement) el.getEnclosingElement(), (ExecutableElement) el, overrides); for (ElementDescription ed : overrides) { Element res = ed.getHandle().resolve(context.getInfo()); if (res == null) { continue; //XXX: log } if ( res.getModifiers().contains(Modifier.PROTECTED) || /*to prevent reports for broken sources:*/ res.getModifiers().contains(Modifier.PUBLIC)) { return null; } } return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_ProtectedMethodInFinalClass", mth.getName()), //NOI18N FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), mth.getModifiers()), EnumSet.of(Modifier.PROTECTED), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveProtectedFromMethod", mth.getName()))); //NOI18N } } else { final VariableTree var = (VariableTree) tree; if (var.getModifiers().getFlags().contains(Modifier.PROTECTED) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.FINAL)) { return ErrorDescriptionFactory.forName(context, var, NbBundle.getMessage(ClassStructure.class, "MSG_ProtectedFieldInFinalClass", var.getName()), //NOI18N FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), var.getModifiers()), EnumSet.of(Modifier.PROTECTED), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveProtectedFromField", var.getName()))); //NOI18N } } } return null; }
Example 6
Source File: AbstractMethodCannotHaveBody.java From netbeans with Apache License 2.0 | 5 votes |
@Override public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) { if (treePath.getLeaf().getKind() != Kind.METHOD) return null; MethodTree mt = (MethodTree) treePath.getLeaf(); Fix removeAbstractFix = FixFactory.removeModifiersFix(compilationInfo, new TreePath(treePath, mt.getModifiers()), EnumSet.of(Modifier.ABSTRACT), Bundle.FIX_AbstractMethodCannotHaveBodyRemoveAbstract()); //TODO: would be better to reused JavaFixUtilities.removeFromParent, but that requires HintContext: Fix removeBodyFix = new RemoveBodyFix(compilationInfo, treePath).toEditorFix(); return Arrays.asList(removeAbstractFix, removeBodyFix); }
Example 7
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
/** * Finds the top-level block or expression that contains the 'from' path. * The result could be a * <ul> * <li>BlockTree representing method body * <li>ExpressionTree representing field initializer * <li>BlockTree representing class initializer * <li>ExpressionTree representing lambda expression * <li>BlockTree representing lambda expression * </ul> * @param from start from * @return nearest enclosing top-level block/expression as defined above. */ public static TreePath findTopLevelBlock(TreePath from) { if (from.getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) { return null; } TreePath save = null; while (from != null) { Tree.Kind k = from.getParentPath().getLeaf().getKind(); if (k == Kind.METHOD || k == Kind.LAMBDA_EXPRESSION) { return from; } else if (k == Kind.VARIABLE) { save = from; } else if (TreeUtilities.CLASS_TREE_KINDS.contains(k)) { if (save != null) { // variable initializer from the previous iteration return save; } if (from.getLeaf().getKind() == Kind.BLOCK) { // parent is class, from is block -> initializer return from; } return null; } else { save = null; } from = from.getParentPath(); } return null; }
Example 8
Source File: JSNI2JavaScriptBody.java From netbeans with Apache License 2.0 | 5 votes |
@TriggerTreeKind(Kind.METHOD) @Messages("ERR_JSNI2JavaScriptBody=Can convert JSNI to @JavaScriptBody") public static ErrorDescription computeWarning(final HintContext ctx) { Token<JavaTokenId> token = findBlockToken(ctx.getInfo(), ctx.getPath(), ctx); if (token == null) { return null; } Fix fix = new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix(); return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_JSNI2JavaScriptBody(), fix); }
Example 9
Source File: TreeConverter.java From j2objc with Apache License 2.0 | 5 votes |
private TreeNode convertAnnotationTypeDeclaration(ClassTree node, TreePath parent) { AnnotationTypeDeclaration newNode = new AnnotationTypeDeclaration(); TreePath path = getTreePath(parent, node); Element element = getElement(path); convertBodyDeclaration(node, path, node.getModifiers(), newNode); for (Tree bodyDecl : node.getMembers()) { if (bodyDecl.getKind() == Kind.METHOD) { MethodTree methodTree = (MethodTree) bodyDecl; TreePath methodPath = getTreePath(path, methodTree); ExecutableElement methodElement = (ExecutableElement) getElement(methodPath); Tree defaultValue = methodTree.getDefaultValue(); ModifiersTree modifiers = methodTree.getModifiers(); AnnotationTypeMemberDeclaration newMember = new AnnotationTypeMemberDeclaration() .setDefault((Expression) convert(defaultValue, methodPath)) .setExecutableElement(methodElement); newMember .setModifiers((int) ((JCModifiers) modifiers).flags) .setAnnotations(convertAnnotations(modifiers, getTreePath(methodPath, modifiers))) .setJavadoc((Javadoc) getAssociatedJavaDoc(methodTree, methodPath)); newNode.addBodyDeclaration(newMember); } else { newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl, path)); } } return newNode .setName(convertSimpleName(element, getTypeMirror(path), getNamePosition(node))) .setTypeElement((TypeElement) element); }
Example 10
Source File: MagicSurroundWithTryCatchFix.java From netbeans with Apache License 2.0 | 5 votes |
public @Override Void visitBlock(BlockTree bt, Void p) { List<CatchTree> catches = createCatches(info, make, thandles, statement); //#89379: if inside a constructor, do not wrap the "super"/"this" call: //please note that the "super" or "this" call is supposed to be always //in the constructor body BlockTree toUse = bt; StatementTree toKeep = null; Tree parent = getCurrentPath().getParentPath().getLeaf(); if (parent.getKind() == Kind.METHOD && bt.getStatements().size() > 0) { MethodTree mt = (MethodTree) parent; if (mt.getReturnType() == null) { toKeep = bt.getStatements().get(0); toUse = make.Block(bt.getStatements().subList(1, bt.getStatements().size()), false); } } if (!streamAlike) { info.rewrite(bt, createBlock(bt.isStatic(), toKeep, make.Try(toUse, catches, null))); } else { VariableTree originalDeclaration = (VariableTree) statement.getLeaf(); VariableTree declaration = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), originalDeclaration.getName(), originalDeclaration.getType(), make.Identifier("null")); StatementTree assignment = make.ExpressionStatement(make.Assignment(make.Identifier(originalDeclaration.getName()), originalDeclaration.getInitializer())); BlockTree finallyTree = make.Block(Collections.singletonList(createFinallyCloseBlockStatement(originalDeclaration)), false); info.rewrite(originalDeclaration, assignment); info.rewrite(bt, createBlock(bt.isStatic(), toKeep, declaration, make.Try(toUse, catches, finallyTree))); } return null; }
Example 11
Source File: TreePathHandle.java From netbeans with Apache License 2.0 | 5 votes |
public Kind getKind() { switch (el.getKind()) { case PACKAGE: return Kind.COMPILATION_UNIT; case ENUM: case CLASS: case ANNOTATION_TYPE: case INTERFACE: return Kind.CLASS; case ENUM_CONSTANT: case FIELD: case PARAMETER: case LOCAL_VARIABLE: case RESOURCE_VARIABLE: case EXCEPTION_PARAMETER: return Kind.VARIABLE; case METHOD: case CONSTRUCTOR: return Kind.METHOD; case STATIC_INIT: case INSTANCE_INIT: return Kind.BLOCK; case TYPE_PARAMETER: return Kind.TYPE_PARAMETER; case OTHER: default: return Kind.OTHER; } }
Example 12
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
private static boolean isSynthetic(CompilationUnitTree cut, Tree leaf) throws NullPointerException { JCTree tree = (JCTree) leaf; if (tree.pos == (-1)) return true; if (leaf.getKind() == Kind.METHOD) { //check for synthetic constructor: return (((JCMethodDecl)leaf).mods.flags & Flags.GENERATEDCONSTR) != 0L; } //check for synthetic superconstructor call: if (cut != null && leaf.getKind() == Kind.EXPRESSION_STATEMENT) { ExpressionStatementTree est = (ExpressionStatementTree) leaf; if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) { MethodInvocationTree mit = (MethodInvocationTree) est.getExpression(); if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) { IdentifierTree it = (IdentifierTree) mit.getMethodSelect(); if ("super".equals(it.getName().toString())) { return ((JCCompilationUnit) cut).endPositions.getEndPos(tree) == (-1); } } } } return false; }
Example 13
Source File: Utilities.java From netbeans with Apache License 2.0 | 5 votes |
public static int findBodyStart(final CompilationInfo info, final Tree cltree, final CompilationUnitTree cu, final SourcePositions positions, final Document doc) { Kind kind = cltree.getKind(); if (!TreeUtilities.CLASS_TREE_KINDS.contains(kind) && kind != Kind.METHOD && !cltree.getKind().toString().equals("RECORD")) throw new IllegalArgumentException("Unsupported kind: "+ kind); final int[] result = new int[1]; doc.render(new Runnable() { public void run() { result[0] = findBodyStartImpl(info, cltree, cu, positions, doc); } }); return result[0]; }
Example 14
Source File: AddParameterOrLocalFix.java From netbeans with Apache License 2.0 | 5 votes |
private TreePath findMethod(TreePath tp) { TreePath method = tp; while (method != null) { if (method.getLeaf().getKind() == Kind.METHOD) { return method; } method = method.getParentPath(); } return null; }
Example 15
Source File: JavadocCompletionUtils.java From netbeans with Apache License 2.0 | 5 votes |
public static TreePath findJavadoc(CompilationInfo javac, int offset) { TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(javac.getTokenHierarchy(), offset); if (ts == null || !movedToJavadocToken(ts, offset)) { return null; } int offsetBehindJavadoc = ts.offset() + ts.token().length(); while (ts.moveNext()) { TokenId tid = ts.token().id(); if (tid == JavaTokenId.BLOCK_COMMENT) { if ("/**/".contentEquals(ts.token().text())) { // NOI18N // see #147533 return null; } } else if (tid == JavaTokenId.JAVADOC_COMMENT) { if (ts.token().partType() == PartType.COMPLETE) { return null; } } else if (!IGNORE_TOKES.contains(tid)) { offsetBehindJavadoc = ts.offset(); // it is magic for TreeUtilities.pathFor ++offsetBehindJavadoc; break; } } TreePath tp = javac.getTreeUtilities().pathFor(offsetBehindJavadoc); while (!TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind()) && tp.getLeaf().getKind() != Kind.METHOD && tp.getLeaf().getKind() != Kind.VARIABLE && tp.getLeaf().getKind() != Kind.COMPILATION_UNIT) { tp = tp.getParentPath(); if (tp == null) { break; } } return tp; }
Example 16
Source File: SpringRenamePlugin.java From netbeans with Apache License 2.0 | 5 votes |
public Problem prepare(RefactoringElementsBag refactoringElements) { TreePathHandle treePathHandle = refactoring.getRefactoringSource().lookup(TreePathHandle.class); if (treePathHandle != null && treePathHandle.getKind() == Kind.METHOD) { return prepareMethodRefactoring(refactoringElements, treePathHandle); } return prepareClassRefactoring(refactoringElements, treePathHandle); }
Example 17
Source File: JavadocHint.java From netbeans with Apache License 2.0 | 5 votes |
@Hint(id = "error-in-javadoc", category = "JavaDoc", description = "#DESC_ERROR_IN_JAVADOC_HINT", displayName = "#DN_ERROR_IN_JAVADOC_HINT", hintKind = Hint.Kind.INSPECTION, severity = Severity.WARNING, customizerProvider = JavadocHint.CustomizerProviderImplError.class) @TriggerTreeKind({Kind.METHOD, Kind.ANNOTATION_TYPE, Kind.CLASS, Kind.ENUM, Kind.INTERFACE, Kind.VARIABLE}) public static List<ErrorDescription> errorHint(final HintContext ctx) { Preferences pref = ctx.getPreferences(); boolean correctJavadocForNonPublic = pref.getBoolean(AVAILABILITY_KEY + false, false); CompilationInfo javac = ctx.getInfo(); Boolean publiclyAccessible = AccessibilityQuery.isPubliclyAccessible(javac.getFileObject().getParent()); boolean isPubliclyA11e = publiclyAccessible == null ? true : publiclyAccessible; if (!isPubliclyA11e && !correctJavadocForNonPublic) { return null; } if (javac.getElements().getTypeElement("java.lang.Object") == null) { // NOI18N // broken java platform return Collections.<ErrorDescription>emptyList(); } TreePath path = ctx.getPath(); { Document doc = null; try { doc = javac.getDocument(); } catch (IOException e) { Exceptions.printStackTrace(e); } if (doc != null && isGuarded(path.getLeaf(), javac, doc)) { return null; } } Access access = Access.resolve(pref.get(SCOPE_KEY, SCOPE_DEFAULT)); Analyzer a = new Analyzer(javac, path, access, ctx); return a.analyze(); }
Example 18
Source File: SourceCodeAnalysisImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
private boolean isThrowsClause(TreePath tp) { Tree parent = tp.getParentPath().getLeaf(); return parent.getKind() == Kind.METHOD && ((MethodTree)parent).getThrows().contains(tp.getLeaf()); }
Example 19
Source File: HideFieldByVar.java From netbeans with Apache License 2.0 | 4 votes |
@Override protected List<Fix> computeFixes(CompilationInfo compilationInfo, TreePath treePath, int[] bounds) { if (treePath.getLeaf().getKind() != Kind.VARIABLE) { return null; } VariableTree vt = (VariableTree)treePath.getLeaf(); Element el = compilationInfo.getTrees().getElement(treePath); if (el == null) { return null; } if (el.getKind() == ElementKind.FIELD) { return null; } boolean isStatic = false; while (el != null && !(el instanceof TypeElement)) { isStatic = el.getModifiers().contains(Modifier.STATIC); el = el.getEnclosingElement(); } if (el == null) { return null; } if (treePath.getParentPath().getLeaf().getKind() == Kind.METHOD) { // skip method values return null; } Element hidden = null; for (Element e : getAllMembers(compilationInfo, (TypeElement)el)) { if (stop) { return null; } if (e.getKind() != ElementKind.FIELD) { continue; } if (isStatic && !e.getModifiers().contains(Modifier.STATIC)) { continue; } if (e.getSimpleName() == vt.getName()) { hidden = e; break; } } if (hidden == null) { return null; } int[] span = compilationInfo.getTreeUtilities().findNameSpan(vt); if (span == null) { return null; } List<Fix> fixes = Collections.<Fix>singletonList(new FixImpl( (span[1] + span[0]) / 2, compilationInfo.getFileObject(), true )); bounds[0] = span[0]; bounds[1] = span[1]; return fixes; }
Example 20
Source File: DeclarationForInstanceOf.java From netbeans with Apache License 2.0 | 4 votes |
List<ErrorDescription> run(CompilationInfo info, TreePath treePath, int offset) { TreePath ifPath = treePath; while (ifPath != null) { Kind lk = ifPath.getLeaf().getKind(); if (lk == Kind.IF) { break; } if (lk == Kind.METHOD || TreeUtilities.CLASS_TREE_KINDS.contains(lk)) { return null; } ifPath = ifPath.getParentPath(); } if (ifPath == null) { return null; } InstanceOfTree leaf = (InstanceOfTree) treePath.getLeaf(); if (leaf.getType() == null || leaf.getType().getKind() == Kind.ERRONEOUS) { return null; } TypeMirror castTo = info.getTrees().getTypeMirror(new TreePath(treePath, leaf.getType())); TreePath expression = new TreePath(treePath, leaf.getExpression()); TypeMirror expressionType = info.getTrees().getTypeMirror(expression); if (!(Utilities.isValidType(castTo) && Utilities.isValidType(expressionType)) || !info.getTypeUtilities().isCastable(expressionType, castTo)) { return null; } List<Fix> fix = Collections.<Fix>singletonList(new FixImpl(info.getJavaSource(), TreePathHandle.create(ifPath, info), TreePathHandle.create(expression, info), TypeMirrorHandle.create(castTo), Utilities.getName(castTo))); String displayName = NbBundle.getMessage(DeclarationForInstanceOf.class, "ERR_DeclarationForInstanceof"); ErrorDescription err = ErrorDescriptionFactory.createErrorDescription(Severity.HINT, displayName, fix, info.getFileObject(), offset, offset); return Collections.singletonList(err); }