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 File: TemplatingTest.java    From Refaster with 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 #2
Source File: GoToSupport.java    From netbeans with 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 #3
Source File: RemoveInvalidModifier.java    From netbeans with 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 #4
Source File: IntroduceHint.java    From netbeans with 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 #5
Source File: Ifs.java    From netbeans with 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 #6
Source File: RemoveUselessCast.java    From netbeans with 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 #7
Source File: UtilitiesTest.java    From netbeans with 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 #8
Source File: ClassStructure.java    From netbeans with 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 #9
Source File: Utilities.java    From netbeans with 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 #10
Source File: ArrayAccess.java    From netbeans with 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 #11
Source File: IndexFileParser.java    From annotation-tools with 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 #12
Source File: XPFlagCleaner.java    From piranha with 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 #13
Source File: TreeConverter.java    From j2objc with 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 #14
Source File: GeneratorUtilities.java    From netbeans with 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 #15
Source File: ImmutableTreeTranslator.java    From netbeans with 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 #16
Source File: Imports.java    From netbeans with 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 #17
Source File: FileToURL.java    From netbeans with 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 #18
Source File: Tiny.java    From netbeans with 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 #19
Source File: FinalizeDoesNotCallSuper.java    From netbeans with 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 #20
Source File: TypeTag.java    From openjdk-8-source with 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 #21
Source File: BreadCrumbsNodeImpl.java    From netbeans with 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 #22
Source File: TypeTag.java    From hottub with 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 File: TypeTag.java    From openjdk-jdk8u with 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 #24
Source File: Braces.java    From netbeans with 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 #25
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether tree is part of compound variable declaration.
 *
 * @param tree tree to examine.
 * @return true if {@code tree} is part of compound var declaration.
 * @since 2.34.0
 */
public boolean isPartOfCompoundVariableDeclaration(@NonNull Tree tree) {
    TokenSequence<JavaTokenId> tokenSequence = tokensFor(tree);

    if (tree.getKind() != Tree.Kind.VARIABLE) {
        return false;
    }

    // If tree ends with comma then tree is part of compound variable declaration.
    tokenSequence.moveEnd();
    if (tokenSequence.movePrevious() && tokenSequence.token().id() == JavaTokenId.COMMA) {
        return true;
    }

    int startPos = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), tree);
    tokenSequence.moveStart();

    int tokensLength = 0;

    // To find out the first subtree from compound varaible declaration statement(if any).
    while (tokenSequence.moveNext()) {
        tokensLength += tokenSequence.token().length();
        if (tokenSequence.token().id() == JavaTokenId.IDENTIFIER) {

            Tree path = pathFor(startPos + tokensLength).getLeaf();
            TokenSequence<JavaTokenId> TokenSeq = tokensFor(path);
            TokenSeq.moveEnd();

            if (TokenSeq.movePrevious() && TokenSeq.token().id() == JavaTokenId.COMMA) {
                return true;
            }
            break;
        }
    }

    return false;
}
 
Example #26
Source File: JavadocCompletionUtils.java    From netbeans with 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 #27
Source File: EncapsulateFieldRefactoringPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isInGetterSetter(
        TreePath path,
        ElementHandle<ExecutableElement> currentGetter,
        ElementHandle<ExecutableElement> currentSetter) {

    if (sourceFile != workingCopy.getFileObject()) {
        return false;
    }

    Tree leaf = path.getLeaf();
    Kind kind = leaf.getKind();
    while (true) {
        switch (kind) {
            case METHOD:
                if (workingCopy.getTreeUtilities().isSynthetic(path)) {
                    return false;
                }
                Element m = workingCopy.getTrees().getElement(path);
                return currentGetter != null && m == currentGetter.resolve(workingCopy)
                        || currentSetter != null && m == currentSetter.resolve(workingCopy);
            case COMPILATION_UNIT:
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
            case NEW_CLASS:
                return false;
        }
        path = path.getParentPath();
        leaf = path.getLeaf();
        kind = leaf.getKind();
    }
}
 
Example #28
Source File: SafeDeleteRefactoringPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Problem findUsagesAndDelete(Set<TreePathHandle> refactoredObjects, RefactoringSession usages, Collection<? extends FileObject> files, RefactoringElementsBag refactoringElements) throws IllegalArgumentException {
    fireProgressListenerStart(AbstractRefactoring.PARAMETERS_CHECK, whereUsedQueries.length + 1);
    Problem problem = null;
    try {
        for (int i = 0; i < whereUsedQueries.length; ++i) {
            TreePathHandle refactoredObject = whereUsedQueries[i].getRefactoringSource().lookup(TreePathHandle.class);
            refactoredObjects.add(refactoredObject);
            whereUsedQueries[i].prepare(usages);
            TreePathHandle treePathHandle = grips.get(i);
            Set<FileObject> relevant = getRelevantFiles(treePathHandle);
            if(Tree.Kind.METHOD == treePathHandle.getKind()) {
                OverriddenAbsMethodFinder finder = new OverriddenAbsMethodFinder(allMethods);
                JavaSource javaSrc = JavaSource.forFileObject(treePathHandle.getFileObject());
                try {
                    javaSrc.runUserActionTask(finder, true);
                } catch (IOException ioException) {
                    ErrorManager.getDefault().notify(cancelRequested.get()?ErrorManager.INFORMATIONAL:ErrorManager.UNKNOWN,ioException);
                }
                problem = finder.getProblem();
            }
            TransformTask task = new TransformTask(new DeleteTransformer(allMethods, files), treePathHandle);
            problem = JavaPluginUtils.chainProblems(createAndAddElements(relevant, task, refactoringElements, refactoring), problem);
            fireProgressListenerStep();
        }
    } finally {
        usages.finished();
    }
    
    return problem;
}
 
Example #29
Source File: Documentifier.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void documentifyField(JCClassDecl base, JCVariableDecl field, boolean isFxStyle) {
    Kind baseKind = base.getKind();
    Set<Modifier> fieldMods = field.getModifiers().getFlags();
    String doc = (baseKind == Kind.ENUM
                  && fieldMods.contains(Modifier.PUBLIC)
                  && fieldMods.contains(Modifier.STATIC)
                  && fieldMods.contains(Modifier.FINAL)) ?
                 docGen.getConstComment() :
                 docGen.getFieldComment(base, field, isFxStyle);
    Comment comm = comment(doc);
    curDocComments.putComment(field, comm);
}
 
Example #30
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeMirror attributeTree(JavacTaskImpl jti, Tree tree, Scope scope, 
            final List<Diagnostic<? extends JavaFileObject>> errors, @NullAllowed final Diagnostic.Kind filter) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Enter enter = Enter.instance(jti.getContext());
        
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            private Diagnostic.Kind f = filter == null ? Diagnostic.Kind.ERROR : filter;
            @Override
            public void report(JCDiagnostic diag) {
                if (diag.getKind().compareTo(f) >= 0) {
                    errors.add(diag);
                }
            }            
        };
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
//            enter.shadowTypeEnvs(true);
            Attr attr = Attr.instance(jti.getContext());
            Env<AttrContext> env = ((JavacScope) scope).getEnv();
            if (tree instanceof JCTree.JCExpression) {
                return attr.attribExpr((JCTree) tree,env, Type.noType);
            }
            return attr.attribStat((JCTree) tree,env);
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
//            enter.shadowTypeEnvs(false);
        }
    }