com.sun.source.tree.Tree.Kind Java Examples

The following examples show how to use com.sun.source.tree.Tree.Kind. 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 Project: netbeans   Author: apache   File: ClassStructure.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.multipleTopLevelClassesInFile", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.multipleTopLevelClassesInFile", category = "class_structure", enabled = false, suppressWarnings = {"MultipleTopLevelClassesInFile"}, options=Options.QUERY) //NOI18N
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static ErrorDescription multipleTopLevelClassesInFile(HintContext context) {
    final ClassTree cls = (ClassTree) context.getPath().getLeaf();
    final Tree parent = context.getPath().getParentPath().getLeaf();
    if (parent.getKind() == Kind.COMPILATION_UNIT) {
        final List<? extends Tree> typeDecls = new ArrayList<Tree>(((CompilationUnitTree) parent).getTypeDecls());
        for (Iterator<? extends Tree> it = typeDecls.iterator(); it.hasNext();) {
            if (it.next().getKind() == Kind.EMPTY_STATEMENT) it.remove();
        }
        if (typeDecls.size() > 1 && typeDecls.get(0) != cls) {
            return ErrorDescriptionFactory.forName(context, cls, NbBundle.getMessage(ClassStructure.class, "MSG_MultipleTopLevelClassesInFile")); //NOI18N
        }
    }
    return null;
}
 
Example #2
Source Project: netbeans   Author: apache   File: RemoveInvalidModifier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
   public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
       EnumSet<Kind> supportedKinds = EnumSet.of(Kind.ANNOTATION_TYPE, Kind.CLASS, Kind.ENUM, Kind.VARIABLE, Kind.INTERFACE, Kind.METHOD);
       boolean isSupported = (supportedKinds.contains(treePath.getLeaf().getKind()));
if (!isSupported) {
    return null;
}
       String invalidMod = getInvalidModifier(compilationInfo, treePath, CODES);
       if (null==invalidMod)
       {
           return null;
       }

       //support multiple invalid modifiers
       Collection<Modifier> modss=convertToModifiers(invalidMod.split(","));
       TreePath modifierTreePath = TreePath.getPath(treePath, getModifierTree(treePath));
       Fix removeModifiersFix = FixFactory.removeModifiersFix(compilationInfo, modifierTreePath, new HashSet<>(modss), NbBundle.getMessage(RemoveInvalidModifier.class, "FIX_RemoveInvalidModifier", invalidMod, modss.size()));
       return Arrays.asList(removeModifiersFix);
   }
 
Example #3
Source Project: netbeans   Author: apache   File: Ifs.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(id="org.netbeans.modules.java.hints.suggestions.InvertIf", displayName = "#DN_InvertIf", description = "#DESC_InvertIf", category = "suggestions", hintKind= Hint.Kind.ACTION)
@UseOptions(SHOW_ELSE_MISSING)
@TriggerPattern(value = "if ($cond) $then; else $else$;")
@Messages({"ERR_InvertIf=Invert If",
           "FIX_InvertIf=Invert If"})
public static ErrorDescription computeWarning(HintContext ctx) {
    TreePath cond = ctx.getVariables().get("$cond");
    long conditionEnd = ctx.getInfo().getTrees().getSourcePositions().getEndPosition(cond.getCompilationUnit(), cond.getParentPath().getLeaf());
    if (ctx.getCaretLocation() > conditionEnd) return null;

    // parenthesized, then if
    TreePath ifPath = cond.getParentPath().getParentPath();
    if (ifPath.getLeaf().getKind() != Tree.Kind.IF) {
        return null;
    }
    IfTree iv = (IfTree)ifPath.getLeaf();
    if (iv.getElseStatement() == null && 
        !ctx.getPreferences().getBoolean(SHOW_ELSE_MISSING, SHOW_ELSE_MISSING_DEFAULT)) {
        return null;
    }
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_InvertIf(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
 
Example #4
Source Project: netbeans   Author: apache   File: UtilitiesTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testPartialModifiers() 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, "$mods$ @Deprecated public $type $name;", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.VARIABLE);

    ModifiersTree mods = ((VariableTree) result).getModifiers();
    String golden1 = "$mods$,@Deprecated(), [public]";
    String golden2 = "$mods$,@Deprecated, [public]";
    String actual = mods.getAnnotations().toString() + ", " + mods.getFlags().toString();
    
    if (!golden1.equals(actual) && !golden2.equals(actual))
        assertEquals(golden1, actual);
}
 
Example #5
Source Project: piranha   Author: uber   File: XPFlagCleaner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }

  if (tree.getExpression().getKind().equals(Kind.METHOD_INVOCATION)) {
    MethodInvocationTree mit = (MethodInvocationTree) tree.getExpression();
    API api = getXPAPI(mit);
    if (api.equals(API.DELETE_METHOD)) {
      Description.Builder builder = buildDescription(tree);
      SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
      fixBuilder.delete(tree);
      decrementAllSymbolUsages(tree, state, fixBuilder);
      builder.addFix(fixBuilder.build());
      endPos = state.getEndPosition(tree);
      return builder.build();
    }
  }
  return Description.NO_MATCH;
}
 
Example #6
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TypeTag.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #7
Source Project: hottub   Author: dsrg-uoft   File: TypeTag.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source Project: netbeans   Author: apache   File: FinalizeDoesNotCallSuper.java    License: Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Tree.Kind.METHOD)
public static ErrorDescription hint(final HintContext ctx) {
    assert ctx != null;
    final TreePath tp = ctx.getPath();
    final MethodTree method = (MethodTree) tp.getLeaf();
    if (method.getBody() == null) return null;
    if (!Util.isFinalize(method)) {
        return null;
    }
    final FindSuper scanner = new FindSuper();
    scanner.scan(method, null);
    if (scanner.found) {
        return null;
    }
    return ErrorDescriptionFactory.forName(ctx, method, NbBundle.getMessage(FinalizeDoesNotCallSuper.class, "TXT_FinalizeDoesNotCallSuper"),
            new FixImpl(TreePathHandle.create(ctx.getPath(), ctx.getInfo())).toEditorFix());
}
 
Example #9
Source Project: netbeans   Author: apache   File: Tiny.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source Project: netbeans   Author: apache   File: Imports.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_Imports_EXCLUDED", description = "#DESC_Imports_EXCLUDED", category="imports", id="Imports_EXCLUDED", options=Options.QUERY)
@TriggerTreeKind(Kind.IMPORT)
public static ErrorDescription exlucded(HintContext ctx) throws IOException {
    ImportTree it = (ImportTree) ctx.getPath().getLeaf();

    if (it.isStatic() || !(it.getQualifiedIdentifier() instanceof MemberSelectTree)) {
        return null; // XXX
    }

    MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
    String pkg = ms.getExpression().toString();
    String klass = ms.getIdentifier().toString();
    String exp = pkg + "." + (!klass.equals("*") ? klass : ""); //NOI18N
    if (Utilities.isExcluded(exp)) {
        return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(Imports.class, "DN_Imports_EXCLUDED"));
    }

    return null;
}
 
Example #11
Source Project: netbeans   Author: apache   File: ImmutableTreeTranslator.java    License: Apache License 2.0 6 votes vote down vote up
protected final AnnotationTree rewriteChildren(AnnotationTree tree) {
       Tree annotationType = translate(tree.getAnnotationType());
List<? extends ExpressionTree> args = translate(tree.getArguments());
if (annotationType!=tree.getAnnotationType() || !args.equals(tree.getArguments())) {
           if (args != tree.getArguments())
               args = optimize(args);
    AnnotationTree n = tree.getKind() == Kind.ANNOTATION
                   ? make.Annotation(annotationType, args)
                   : make.TypeAnnotation(annotationType, args);
           model.setType(n, model.getType(tree));
    copyCommentTo(tree,n);
    tree = n;
           if (tree.getArguments().size() != args.size())
               model.setPos(tree, NOPOS);
           else
               copyPosTo(tree,n);
}
return tree;
   }
 
Example #12
Source Project: Refaster   Author: google   File: TemplatingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void forLoopNoCondition() {
  compile(
      "class ForLoopExample {",
      "  public void example(int from, int to) {",
      "     for (int i = from; ; i++) {",
      "     }",
      "  }",
      "}");
  assertEquals(
      BlockTemplate.create(
          ImmutableMap.of(
              "from", UPrimitiveType.INT,
              "to", UPrimitiveType.INT),
          UForLoop.create(
              ImmutableList.of(
                  UVariableDecl.create("i", UPrimitiveTypeTree.INT, UFreeIdent.create("from"))), 
              null, 
              ImmutableList.of(UExpressionStatement.create(
                  UUnary.create(Kind.POSTFIX_INCREMENT, ULocalVarIdent.create("i")))), 
              UBlock.create())),
      UTemplater.createTemplate(context, getMethodDeclaration("example")));
}
 
Example #13
Source Project: netbeans   Author: apache   File: Braces.java    License: Apache License 2.0 6 votes vote down vote up
private static ErrorDescription checkStatement(HintContext ctx, String dnKey, StatementTree statement, TreePath tp)  {
    if ( statement != null &&
         statement.getKind() != Tree.Kind.EMPTY_STATEMENT &&
         statement.getKind() != Tree.Kind.BLOCK &&
         statement.getKind() != Tree.Kind.TRY &&
         statement.getKind() != Tree.Kind.SYNCHRONIZED &&
         statement.getKind() != Tree.Kind.SWITCH &&
         statement.getKind() != Tree.Kind.ERRONEOUS &&
         !isErroneousExpression( statement )) {
        return ErrorDescriptionFactory.forTree(
                    ctx,
                    statement,
                    NbBundle.getMessage(Braces.class, dnKey),
                    new BracesFix(ctx.getInfo().getFileObject(), TreePathHandle.create(tp, ctx.getInfo())).toEditorFix());

    }
    return null;
}
 
Example #14
Source Project: annotation-tools   Author: typetools   File: IndexFileParser.java    License: MIT License 6 votes vote down vote up
private Pair<ASTPath, InnerTypeLocation> splitNewArrayType(ASTPath astPath) {
    ASTPath outerPath = astPath;
    InnerTypeLocation loc = null;
    int last = astPath.size() - 1;

    if (last > 0) {
        ASTPath.ASTEntry entry = astPath.get(last);
        if (entry.getTreeKind() == Kind.NEW_ARRAY && entry.childSelectorIs(ASTPath.TYPE)) {
            int a = entry.getArgument();
            if (a > 0) {
                outerPath = astPath.getParentPath().extend(new ASTPath.ASTEntry(Kind.NEW_ARRAY, ASTPath.TYPE, 0));
                loc = new InnerTypeLocation(TypeAnnotationPosition.getTypePathFromBinary(Collections.nCopies(2 * a, 0)));
            }
        }
    }
    return Pair.of(outerPath, loc);
}
 
Example #15
Source Project: netbeans   Author: apache   File: ArrayAccess.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    if (treePath.getLeaf().getKind() != Kind.ARRAY_ACCESS) {
        return Collections.emptyList();
    }
    ArrayAccessTree aa = (ArrayAccessTree) treePath.getLeaf();
    TypeMirror onType = info.getTrees().getTypeMirror(new TreePath(treePath, aa.getExpression()));
    boolean list = isSubType(info, onType, "java.util.List");
    boolean map = isSubType(info, onType, "java.util.Map");
    
    if (list || map) {
        Kind parentKind = treePath.getParentPath().getLeaf().getKind();
        if (CANNOT_HANDLE_PARENTS.contains(parentKind)) return null;
        return Collections.singletonList(new ConvertFromArrayAccess(info, treePath, map, parentKind == Kind.ASSIGNMENT).toEditorFix());
    }
    
    return Collections.emptyList();
}
 
Example #16
Source Project: netbeans   Author: apache   File: Utilities.java    License: Apache License 2.0 6 votes vote down vote up
public static List<AnnotationTree> findArrayValue(AnnotationTree at, String name) {
    ExpressionTree fixesArray = findValue(at, name);
    List<AnnotationTree> fixes = new LinkedList<AnnotationTree>();

    if (fixesArray != null && fixesArray.getKind() == Kind.NEW_ARRAY) {
        NewArrayTree trees = (NewArrayTree) fixesArray;

        for (ExpressionTree fix : trees.getInitializers()) {
            if (fix.getKind() == Kind.ANNOTATION) {
                fixes.add((AnnotationTree) fix);
            }
        }
    }

    if (fixesArray != null && fixesArray.getKind() == Kind.ANNOTATION) {
        fixes.add((AnnotationTree) fixesArray);
    }
    
    return fixes;
}
 
Example #17
Source Project: netbeans   Author: apache   File: IntroduceHint.java    License: Apache License 2.0 6 votes vote down vote up
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 #18
Source Project: netbeans   Author: apache   File: GeneratorUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static String[] correspondingGSNames(Tree member) {
    if (isSetter(member)) {
        String name = name(member);
        VariableTree param = ((MethodTree)member).getParameters().get(0);
        if (param.getType().getKind() == Tree.Kind.PRIMITIVE_TYPE && ((PrimitiveTypeTree)param.getType()).getPrimitiveTypeKind() == TypeKind.BOOLEAN) {
            return new String[] {'g' + name.substring(1), "is" + name.substring(3)};
        }
        return new String[] {'g' + name.substring(1)};
    }
    if (isGetter(member)) {
        return new String[] {'s' + name(member).substring(1)};
    }
    if (isBooleanGetter(member)) {
        return new String[] {"set" + name(member).substring(2)}; //NOI18N
    }
    return null;
}
 
Example #19
Source Project: netbeans   Author: apache   File: RemoveUselessCast.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #20
Source Project: netbeans   Author: apache   File: BreadCrumbsNodeImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static String className(TreePath path) {
    ClassTree ct = (ClassTree) path.getLeaf();
    
    if (path.getParentPath().getLeaf().getKind() == Kind.NEW_CLASS) {
        NewClassTree nct = (NewClassTree) path.getParentPath().getLeaf();
        
        if (nct.getClassBody() == ct) {
            return simpleName(nct.getIdentifier());
        }
    } else if (path.getParentPath().getLeaf() == path.getCompilationUnit()) {
        ExpressionTree pkg = path.getCompilationUnit().getPackageName();
        String pkgName = pkg != null ? pkg.toString() : null;
        if (pkgName != null && !pkgName.contentEquals(ERR_NAME)) {
            return pkgName + '.' + ct.getSimpleName().toString();
        }
    }
    
    return ct.getSimpleName().toString();
}
 
Example #21
Source Project: netbeans   Author: apache   File: FileToURL.java    License: Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Kind.METHOD_INVOCATION)
public static ErrorDescription computeTreeKind(HintContext ctx) {
    MethodInvocationTree mit = (MethodInvocationTree) ctx.getPath().getLeaf();

    if (!mit.getArguments().isEmpty() || !mit.getTypeArguments().isEmpty()) {
        return null;
    }

    CompilationInfo info = ctx.getInfo();
    Element e = info.getTrees().getElement(new TreePath(ctx.getPath(), mit.getMethodSelect()));

    if (e == null || e.getKind() != ElementKind.METHOD) {
        return null;
    }

    if (e.getSimpleName().contentEquals("toURL") && info.getElementUtilities().enclosingTypeElement(e).getQualifiedName().contentEquals("java.io.File")) {
        ErrorDescription w = ErrorDescriptionFactory.forName(ctx, mit, "Use of java.io.File.toURL()");

        return w;
    }

    return null;
}
 
Example #22
Source Project: openjdk-8-source   Author: keerath   File: TypeTag.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #23
Source Project: j2objc   Author: google   File: TreeConverter.java    License: Apache License 2.0 6 votes vote down vote up
private TreeNode convertClassDeclaration(ClassTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  TypeElement element = (TypeElement) getElement(path);
  // javac defines all type declarations with JCClassDecl, so differentiate here
  // to support our different declaration nodes.
  if (element.getKind() == ElementKind.ANNOTATION_TYPE) {
    throw new AssertionError("Annotation type declaration tree conversion not implemented");
  }

  TypeDeclaration newNode = convertClassDeclarationHelper(node, parent);

  newNode.setInterface(
      node.getKind() == Kind.INTERFACE || node.getKind() == Kind.ANNOTATION_TYPE);
  if (ElementUtil.isAnonymous(element)) {
    newUnit.getEnv().elementUtil().mapElementType(element, getTypeMirror(path));
  }
  return newNode;
}
 
Example #24
Source Project: netbeans   Author: apache   File: GoToSupport.java    License: Apache License 2.0 6 votes vote down vote up
private static TreePath adjustPathForModuleName(TreePath path) {
    TreePath tp = path;
    while (tp != null && (tp.getLeaf().getKind() == Kind.IDENTIFIER || tp.getLeaf().getKind() == Kind.MEMBER_SELECT)) {
        Tree parent = tp.getParentPath().getLeaf();
        if (parent.getKind() == Kind.MODULE && ((ModuleTree)parent).getName() == tp.getLeaf()) {
            return tp.getParentPath();
        }
        if (parent.getKind() == Kind.REQUIRES && ((RequiresTree)parent).getModuleName() == tp.getLeaf()
                || parent.getKind() == Kind.EXPORTS && ((ExportsTree)parent).getModuleNames() != null && ((ExportsTree)parent).getModuleNames().contains(tp.getLeaf())
                || parent.getKind() == Kind.OPENS && ((OpensTree)parent).getModuleNames() != null && ((OpensTree)parent).getModuleNames().contains(tp.getLeaf())) {
            return tp;
        }
        tp = tp.getParentPath();
    }
    return path;
}
 
Example #25
Source Project: netbeans   Author: apache   File: JavadocCompletionUtils.java    License: Apache License 2.0 5 votes vote down vote up
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 #26
Source Project: netbeans   Author: apache   File: EmptyStatements.java    License: Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#LBL_Empty_WHILE_LOOP", description = "#DSC_Empty_WHILE_LOOP", category = "empty", hintKind = Hint.Kind.INSPECTION, severity = Severity.VERIFIER, suppressWarnings = SUPPRESS_WARNINGS_KEY, id = "EmptyStatements_WHILE_LOOP")
@TriggerTreeKind(Tree.Kind.EMPTY_STATEMENT)
public static ErrorDescription forWHILE_LOOP(HintContext ctx) {
    final TreePath parentPath = ctx.getPath().getParentPath();
    final Tree parentLeaf = parentPath.getLeaf();
    if (!EnumSet.of(Kind.WHILE_LOOP).contains(parentLeaf.getKind())) {
        return null;
}

    final List<Fix> fixes = new ArrayList<>();
    fixes.add(FixFactory.createSuppressWarningsFix(ctx.getInfo(), parentPath, SUPPRESS_WARNINGS_KEY));

    return createErrorDescription(ctx, parentLeaf, fixes, Kind.WHILE_LOOP);
}
 
Example #27
Source Project: hottub   Author: dsrg-uoft   File: T6472751.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void scan(Tree node, Void ignored) {
    if (node == null)
        return null;
    Kind k = node.getKind();
    long pos = positions.getStartPosition(null,node);
    System.out.format("%s: %s%n", k, pos);
    if (k != Kind.MODIFIERS && pos < 0)
        throw new Error("unexpected position found");
    return super.scan(node, ignored);
}
 
Example #28
Source Project: netbeans   Author: apache   File: ComputeImports.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitMemberSelect(MemberSelectTree tree, Map<String, Object> p) {
    if (tree.getExpression().getKind() == Kind.IDENTIFIER) {
        p.put("request", null);
    }
    
    scan(tree.getExpression(), p);
    
    Union2<String, DeclaredType> leftSide = (Union2<String, DeclaredType>) p.remove("result");
    
    p.remove("request");
    
    if (leftSide != null && leftSide.hasFirst()) {
        String rightSide = tree.getIdentifier().toString();
        
        if (ERROR.equals(rightSide))
            rightSide = "";
        
        boolean isMethodInvocation = getCurrentPath().getParentPath().getLeaf().getKind() == Kind.METHOD_INVOCATION;
        
        //Ignore .class (which will not help us much):
        if (!"class".equals(rightSide))
            hints.add(new EnclosedHint(leftSide.first(), rightSide, !isMethodInvocation));
    }
    
    return null;
}
 
Example #29
Source Project: netbeans   Author: apache   File: ConvertToARM.java    License: Apache License 2.0 5 votes vote down vote up
private static TryTree findNestedARM(
        final Collection<? extends StatementTree> stms,
        final StatementTree var) {
    int state = var != null ? 0 : 1;
    for (StatementTree stm : stms) {
        if (stm == var) {
            state = 1;
        }
        if (state == 1) {
            if (stm.getKind() == Kind.TRY) {
                final TryTree tryTree = (TryTree)stm;
                if (tryTree.getResources() != null && !tryTree.getResources().isEmpty()) {
                    return tryTree;
                } else {
                    final Iterator<? extends StatementTree> blkStms = tryTree.getBlock().getStatements().iterator();
                    if (blkStms.hasNext()) {
                        StatementTree bstm = blkStms.next();
                        if (bstm.getKind() == Kind.TRY) {
                            return (TryTree)bstm;
                        }
                        if (bstm.getKind() == Kind.EXPRESSION_STATEMENT && blkStms.hasNext()) {
                            bstm = blkStms.next();
                            if (bstm.getKind() == Kind.TRY) {
                                return (TryTree)bstm;
                            }
                        }
                    }
                }
            }
            if (stm != var) {
                break;
            }
        }
    }
    return null;
}
 
Example #30
Source Project: netbeans   Author: apache   File: BreadCrumbsNodeImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static ModuleElement.DirectiveKind directiveKind(Kind treeKind) {
    switch (treeKind) {
        case EXPORTS:
            return ModuleElement.DirectiveKind.EXPORTS;
        case PROVIDES:
            return ModuleElement.DirectiveKind.PROVIDES;
        case REQUIRES:
            return ModuleElement.DirectiveKind.REQUIRES;
        case USES:
            return ModuleElement.DirectiveKind.USES;
    }
    return null;
}