Java Code Examples for com.sun.source.tree.Tree.Kind#CLASS

The following examples show how to use com.sun.source.tree.Tree.Kind#CLASS . 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: UtilityClass.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(id="org.netbeans.modules.java.hints.UtilityClass_1", displayName="#MSG_UtilityClass", description="#HINT_UtilityClass", category="api", enabled=false, severity=Severity.VERIFIER, suppressWarnings="UtilityClassWithoutPrivateConstructor")
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription utilityClass(HintContext ctx) {
    CompilationInfo compilationInfo = ctx.getInfo();
    TreePath treePath = ctx.getPath();
    Element e = compilationInfo.getTrees().getElement(treePath);
    if (e == null) {
        return null;
    }
    
    if (!isUtilityClass(compilationInfo, e)) return null;
    
    for (ExecutableElement c : ElementFilter.constructorsIn(e.getEnclosedElements())) {
        if (!compilationInfo.getElementUtilities().isSynthetic(c)) {
            return null;
        }
    }

    return ErrorDescriptionFactory.forName(ctx,
                                           treePath,
                                           NbBundle.getMessage(UtilityClass.class, "MSG_UtilityClass"),
                                           new FixImpl(true,
                                                       TreePathHandle.create(e, compilationInfo)
                                           ).toEditorFix());
}
 
Example 2
Source File: TreeConverter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private SourcePosition getNamePosition(Tree node) {
  int start = (int) sourcePositions.getStartPosition(unit, node);
  if (start == -1) {
    return SourcePosition.NO_POSITION;
  }
  String src = newUnit.getSource();
  Kind kind = node.getKind();
  if (kind == Kind.ANNOTATION_TYPE
      || kind == Kind.CLASS
      || kind == Kind.ENUM
      || kind == Kind.INTERFACE) {
    // Skip the class/enum/interface token.
    while (src.charAt(start++) != ' ') {}
  } else if (kind != Kind.METHOD && kind != Kind.VARIABLE) {
    return getPosition(node);
  }
  if (!Character.isJavaIdentifierStart(src.charAt(start))) {
    return getPosition(node);
  }
  int endPos = start + 1;
  while (Character.isJavaIdentifierPart(src.charAt(endPos))) {
    endPos++;
  }
  return getSourcePosition(start, endPos);
}
 
Example 3
Source File: TreePathHandle.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 4
Source File: AnnotationProcessors.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName="#DN_AnnotationProcessors.overridingGetSupportedAnnotations",
      description="#DESC_AnnotationProcessors.overridingGetSupportedAnnotations",
      category="rules15")
@Messages({/*"DN_AnnotationProcessors.overridingGetSupportedAnnotations=AbstractProcessor.getSupportedAnnotations() is overridden",
           "DESC_AnnotationProcessors.overridingGetSupportedAnnotations=Overriding Processor.getSupportedAnnotations() may lead to " +
                                                                       "unnecessary classloading during development, and may prevent important optimalizations. " +
                                                                       "consider using @javax.annotation.processing.SupportedAnnotationTypes",*/
           "ERR_AnnotationProcessors.overridingGetSupportedAnnotations=AbstractProcessor.getSupportedAnnotationTypes() overridden, may cause performance problems during development"})
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription oGSA(HintContext ctx) {
    Element clazz = ctx.getInfo().getTrees().getElement(ctx.getPath());

    if (clazz == null || !clazz.getKind().isClass()) return null;

    TypeElement ap = ctx.getInfo().getElements().getTypeElement("javax.annotation.processing.AbstractProcessor");

    if (ap == null) return null;

    Types types = ctx.getInfo().getTypes();

    if (!types.isSubtype(types.erasure(clazz.asType()), types.erasure(ap.asType()))) return null;

    for (ExecutableElement ee : ElementFilter.methodsIn(clazz.getEnclosedElements())) {
        if (ee.getSimpleName().contentEquals("getSupportedAnnotationTypes") && ee.getParameters().isEmpty()) {
            Tree t = ctx.getInfo().getTrees().getTree(ee);

            if (t != null) {
                return ErrorDescriptionFactory.forName(ctx, t, Bundle.ERR_AnnotationProcessors_overridingGetSupportedAnnotations());
            }
        }
    }

    return null;
}
 
Example 5
Source File: CollectionRemove.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ExecutableElement findEnclosingMethod(CompilationInfo info, TreePath path) {
    while (path != null && path.getLeaf().getKind() != Kind.CLASS && path.getLeaf().getKind() != Kind.METHOD) {
        path = path.getParentPath();
    }

    if (path != null && path.getLeaf().getKind() == Kind.METHOD) {
        Element el = info.getTrees().getElement(path);

        if (el != null && el.getKind() == ElementKind.METHOD) {
            return (ExecutableElement) el;
        }
    }

    return null;
}
 
Example 6
Source File: JavadocHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: HintTestTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription hint(HintContext ctx) {
    if (ctx.getInfo().getClasspathInfo().getClassPath(PathKind.SOURCE).findOwnerRoot(ctx.getInfo().getFileObject()) == null) {
        return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), "Broken Source Path");
    }

    return null;
}
 
Example 8
Source File: HintTestTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription hint(HintContext ctx) {
    FileObject clazz = ctx.getInfo().getClasspathInfo().getClassPath(PathKind.COMPILE).findResource("org/netbeans/api/java/source/JavaSource.class");

    if (clazz == null) {
        return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), "Broken Compilation ClassPath");
    }

    return null;
}
 
Example 9
Source File: HintTestTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription hint(HintContext ctx) {
    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), "Test", new Fix() {
        @Override public String getText() {
            return "Fix";
        }
        @Override public ChangeInfo implement() throws Exception {
            return null;
        }
    });
}
 
Example 10
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private SourcePosition getNamePosition(String name, JCTree node) {
  int start = node.getPreferredPosition();
  if (start == -1) {
    return null;
  }

  try {
    String src = javacUnit.sourcefile.getCharContent(true).toString();
    Kind kind = node.getKind();
    if (kind == Kind.ANNOTATION_TYPE
        || kind == Kind.CLASS
        || kind == Kind.ENUM
        || kind == Kind.INTERFACE) {
      // Skip the class/enum/interface token.
      while (src.charAt(start++) != ' ') {}
    } else if (kind != Kind.METHOD && kind != Kind.VARIABLE) {
      return getSourcePosition(node);
    }
    if (!Character.isJavaIdentifierStart(src.charAt(start))) {
      return getSourcePosition(node);
    }
    int endPos = start + 1;
    while (Character.isJavaIdentifierPart(src.charAt(endPos))) {
      endPos++;
    }
    return getSourcePosition(name, start, endPos);
  } catch (IOException e) {
    throw internalCompilerError(e, "Error getting name Position for: %s.", node);
  }
}
 
Example 11
Source File: Translator.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
private CompilationUnitTree getDefaultGroovyMethodCompilationUnitTree(Iterable<? extends CompilationUnitTree> parsed, String fqcn) {
    for (CompilationUnitTree cut : parsed) {
        for (Tree t : cut.getTypeDecls()) {
            if (t.getKind() == Kind.CLASS) {
                ClassTree ct = (ClassTree)t;
                if (ct.getSimpleName().toString().equals(fqcn.replaceFirst("^.+[.]", ""))) { // TODO how do we get the FQCN of a ClassTree?
                    return cut;
                }
            }
        }
    }
    throw new IllegalStateException(fqcn + " wasn't parsed");
}
 
Example 12
Source File: OrganizeMembers.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription checkMembers(final HintContext context) {
    for (Diagnostic<?> d : context.getInfo().getDiagnostics()) {
        if (Hacks.isSyntaxError(d)) {
            return null;
        }
    }
    Source source = context.getInfo().getSnapshot().getSource();
    try {
        ModificationResult result = ModificationResult.runModificationTask(Collections.singleton(source), new UserTask() {
            @Override
            public void run(ResultIterator resultIterator) throws Exception {
                WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult());
                copy.toPhase(Phase.RESOLVED);
                doOrganizeMembers(copy, context.getPath());
            }
        });
        List<? extends Difference> diffs = result.getDifferences(source.getFileObject());
        if (diffs != null && !diffs.isEmpty() && !checkGuarded(context.getInfo().getDocument(), diffs)) {
            Fix fix = new OrganizeMembersFix(context.getInfo(), context.getPath()).toEditorFix();
            SourcePositions sp = context.getInfo().getTrees().getSourcePositions();
            int offset = diffs.get(0).getStartPosition().getOffset();
            LineMap lm = context.getInfo().getCompilationUnit().getLineMap();
            long lno = lm.getLineNumber(offset);
            if (lno >= 1) {
                offset = (int)lm.getStartPosition(lno);
            }
            CompilationUnitTree cut = context.getPath().getCompilationUnit();
            ClassTree clazz = (ClassTree) context.getPath().getLeaf();
            for (Tree member : clazz.getMembers()) {
                if (context.getInfo().getTreeUtilities().isSynthetic(new TreePath(context.getPath(), member))) continue;
                if (sp.getStartPosition(cut, member) >= offset) {
                    return ErrorDescriptionFactory.forTree(context, member, NbBundle.getMessage(OrganizeMembers.class, "MSG_OragnizeMembers"), fix); //NOI18N
                }
            }
            return ErrorDescriptionFactory.forTree(context, clazz, NbBundle.getMessage(OrganizeMembers.class, "MSG_OragnizeMembers"), fix); //NOI18N
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example 13
Source File: MissingHashCode.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static List<ErrorDescription> run(HintContext ctx) {
    CompilationInfo compilationInfo = ctx.getInfo();
    TreePath treePath = ctx.getPath();
    Element clazz = compilationInfo.getTrees().getElement(treePath);
    if (clazz == null || !clazz.getKind().isClass()) {
        return null;
    }

    ExecutableElement[] ret = EqualsHashCodeGenerator.overridesHashCodeAndEquals(compilationInfo, clazz, new EqualsHashCodeGenerator.Cancel() {
        @Override public boolean isCanceled() {
            return false;
        }
    });
    ExecutableElement warningToElement = null;

    String addHint = null;
    if (ret[0] == null && ret[1] != null) {
        addHint = "MSG_GenEquals"; // NOI18N
        warningToElement = ret[1];
    }
    if (ret[1] == null && ret[0] != null) {
        addHint = "MSG_GenHashCode"; // NOI18N
        warningToElement = ret[0];
    }

    if (addHint != null) {
        assert warningToElement != null;

        TreePath warningTo = compilationInfo.getTrees().getPath(warningToElement);

        if (warningTo == null || warningTo.getLeaf().getKind() != Kind.METHOD) {
            //XXX: should not happen, log
            return null;
        }
        
        List<Fix> fixes = Collections.<Fix>singletonList(new FixImpl(
            addHint, 
            TreePathHandle.create(clazz, compilationInfo),
            compilationInfo.getFileObject()
        ));

        int[] span = compilationInfo.getTreeUtilities().findNameSpan((MethodTree) warningTo.getLeaf());

        if (span != null) {
            ErrorDescription ed = ErrorDescriptionFactory.forName(
                ctx,
                warningTo,
                NbBundle.getMessage(MissingHashCode.class, addHint), 
                fixes.toArray(new Fix[0])
            );

            return Collections.singletonList(ed);
        }
    }
    
    return null;
}
 
Example 14
Source File: ImplementMethods.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
@Messages({
    "# {0} - the FQN of the type whose methods will be implemented",
    "ERR_ImplementMethods=Implement unimplemented abstract methods of {0}"
})
public static ErrorDescription implementMethods(HintContext ctx) {
    ClassTree clazz = (ClassTree) ctx.getPath().getLeaf();
    Element typeEl = ctx.getInfo().getTrees().getElement(ctx.getPath());
    
    if (typeEl == null || !typeEl.getKind().isClass())
        return null;
    
    List<Tree> candidate = new ArrayList<Tree>(clazz.getImplementsClause());
    
    candidate.add(clazz.getExtendsClause());
    
    Tree found = null;
    
    for (Tree cand : candidate) {
        if (   ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getInfo().getCompilationUnit(), cand) <= ctx.getCaretLocation()
            && ctx.getCaretLocation() <= ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getInfo().getCompilationUnit(), cand)) {
            found = cand;
            break;
        }
    }
    
    if (found == null) return null;
    
    TreePath foundPath = new TreePath(ctx.getPath(), found);
    Element supertype = ctx.getInfo().getTrees().getElement(foundPath);
    
    if (supertype == null || (!supertype.getKind().isClass() && !supertype.getKind().isInterface()))
        return null;
    
    List<ExecutableElement> unimplemented = computeUnimplemented(ctx.getInfo(), typeEl, supertype);
    
    if (!unimplemented.isEmpty()) {
        return ErrorDescriptionFactory.forName(ctx, foundPath, Bundle.ERR_ImplementMethods(((TypeElement) supertype).getQualifiedName().toString()), new ImplementFix(ctx.getInfo(), ctx.getPath(), (TypeElement) typeEl, (TypeElement) supertype).toEditorFix());
    }
    
    return null;
}
 
Example 15
Source File: HintTestTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription hint(HintContext ctx) {
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), "Test", new TestingNonJavaChangesFix(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
 
Example 16
Source File: HintTestTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription hint(HintContext ctx) {
    throw new NullPointerException("a");
}