Java Code Examples for org.netbeans.api.java.source.CompilationInfo#getCompilationUnit()

The following examples show how to use org.netbeans.api.java.source.CompilationInfo#getCompilationUnit() . 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: DiffContext.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public DiffContext(CompilationInfo copy, Set<Tree> syntheticTrees) {
    this.tokenSequence = copy.getTokenHierarchy().tokenSequence(JavaTokenId.language());
    this.mainCode = this.origText = copy.getText();
    this.style = getCodeStyle(copy);
    this.context = JavaSourceAccessor.getINSTANCE().getJavacTask(copy).getContext();
    this.mainUnit = this.origUnit = (JCCompilationUnit) copy.getCompilationUnit();
    this.trees = copy.getTrees();
    this.doc = copy.getSnapshot().getSource().getDocument(false); //TODO: true or false?
    this.positionConverter = copy.getPositionConverter();
    this.file = copy.getFileObject();
    this.syntheticTrees = syntheticTrees;
    
    this.textLength = copy.getSnapshot() == null ? Integer.MAX_VALUE : copy.getSnapshot().getOriginalOffset(copy.getSnapshot().getText().length());
    this.blockSequences = new BlockSequences(this.tokenSequence, doc, textLength);
    
    this.forceInitialComment = false;
}
 
Example 2
Source File: AssignResultToVariable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatementTree findExactStatement(CompilationInfo info, BlockTree block, int offset, boolean start) {
    if (offset == (-1)) return null;
    
    SourcePositions sp = info.getTrees().getSourcePositions();
    CompilationUnitTree cut = info.getCompilationUnit();
    
    for (StatementTree t : block.getStatements()) {
        long pos = start ? sp.getStartPosition(info.getCompilationUnit(), t) : sp.getEndPosition( cut, t);

        if (offset == pos) {
            return t;
        }
    }

    return null;
}
 
Example 3
Source File: AddOrRemoveFinalModifier.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    Tree leaf = treePath.getLeaf();

    if (leaf.getKind() == Kind.IDENTIFIER) {
        Element el = compilationInfo.getTrees().getElement(treePath);
        if (el == null) {
            return null;
        }
        TreePath declaration = compilationInfo.getTrees().getPath(el);
        
        // do not offer any modifications for members in other CUs
        if (declaration != null && declaration.getCompilationUnit() == compilationInfo.getCompilationUnit()) {
            return Collections.singletonList((Fix) new FixImpl(compilationInfo.getFileObject(), el.getSimpleName().toString(), TreePathHandle.create(declaration, compilationInfo), fixDescription, type));
        }
    }
    
    return Collections.<Fix>emptyList();
}
 
Example 4
Source File: CopyFinderBasedBulkSearch.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Collection<TreePath>> match(CompilationInfo info, AtomicBoolean cancel, TreePath toSearch, BulkPattern pattern, Map<String, Long> timeLog) {
    Parameters.notNull("info", info);
    Map<String, Collection<TreePath>> result = new HashMap<String, Collection<TreePath>>();
    TreePath topLevel = new TreePath(info.getCompilationUnit());
    
    for (Entry<Tree, String> e : ((BulkPatternImpl) pattern).pattern2Code.entrySet()) {
        for (Occurrence od : Matcher.create(info).setCancel(new AtomicBoolean()).setUntypedMatching().setCancel(cancel).match(Pattern.createPatternWithFreeVariables(new TreePath(topLevel, e.getKey()), Collections.<String, TypeMirror>emptyMap()))) {
            Collection<TreePath> c = result.get(e.getValue());

            if (c == null) {
                result.put(e.getValue(), c = new LinkedList<TreePath>());
            }

            c.add(od.getOccurrenceRoot());
        }
    }

    return result;
}
 
Example 5
Source File: JUnitTestUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a main class.
 *
 * @param  compInfo  defines scope in which the class is to be found
 * @param  className  name of the class to be found
 * @return  the found class; or <code>null</code> if the class was not
 *          found (e.g. because of a broken source file)
 */
public static ClassTree findMainClass(final CompilationInfo compInfo) {
    final String className = compInfo.getFileObject().getName();
    
    CompilationUnitTree compUnitTree = compInfo.getCompilationUnit();
    String shortClassName = getSimpleName(className);
    for (Tree typeDecl : compUnitTree.getTypeDecls()) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
            ClassTree clazz = (ClassTree) typeDecl;
            if (clazz.getSimpleName().toString().equals(shortClassName)) {
                return clazz;
            }
        }
    }
    return null;
}
 
Example 6
Source File: MemberAdditionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testEmptyClass() throws Exception {
    performTest("EmptyClass");

    source.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(Phase.RESOLVED);
            ClassTree topLevel = findTopLevelClass(copy);
            SourceUtilsTestUtil2.run(copy, new AddSimpleField(), topLevel);
        }
    }).commit();

    JavaSourceAccessor.getINSTANCE().revalidate(source);

    CompilationInfo check = SourceUtilsTestUtil.getCompilationInfo(source, Phase.RESOLVED);
    CompilationUnitTree cu = check.getCompilationUnit();

    assertEquals(check.getDiagnostics().toString(), 0, check.getDiagnostics().size());
    
    ClassTree newTopLevel = findTopLevelClass(check);
    Element clazz = check.getTrees().getElement(TreePath.getPath(cu, newTopLevel));
    Element pack = clazz.getEnclosingElement();
    
    assertEquals(ElementKind.PACKAGE, pack.getKind());
    assertEquals("test", ((PackageElement) pack).getQualifiedName().toString());
    assertEquals(clazz.getEnclosedElements().toString(), 1 + 1/*syntetic default constructor*/, clazz.getEnclosedElements().size());
}
 
Example 7
Source File: MemberAdditionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testSynteticDefaultConstructor() throws Exception {
    performTest("SynteticDefaultConstructor");
    
    source.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(Phase.RESOLVED);
            ClassTree topLevel = findTopLevelClass(copy);                
            SourceUtilsTestUtil2.run(copy, new AddSimpleField(), topLevel);
        }
    }).commit();

    JavaSourceAccessor.getINSTANCE().revalidate(source);
    
    CompilationInfo check = SourceUtilsTestUtil.getCompilationInfo(source, Phase.RESOLVED);
    CompilationUnitTree cu = check.getCompilationUnit();

    assertEquals(check.getDiagnostics().toString(), 0, check.getDiagnostics().size());

    ClassTree newTopLevel = findTopLevelClass(check);
    Element clazz = check.getTrees().getElement(TreePath.getPath(cu, newTopLevel));
    Element pack = clazz.getEnclosingElement();

    assertEquals(ElementKind.PACKAGE, pack.getKind());
    assertEquals("test", ((PackageElement) pack).getQualifiedName().toString());
    assertEquals(clazz.getEnclosedElements().toString(), 2 + 1/*syntetic default constructor*/, clazz.getEnclosedElements().size());
}
 
Example 8
Source File: TestUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a main class.
 *
 * @param  compInfo  defines scope in which the class is to be found
 * @param  className  name of the class to be found
 * @return  the found class; or <code>null</code> if the class was not
 *          found (e.g. because of a broken source file)
 */
public static ClassTree findMainClass(final CompilationInfo compInfo) {
    final String className = compInfo.getFileObject().getName();
    
    CompilationUnitTree compUnitTree = compInfo.getCompilationUnit();
    String shortClassName = getSimpleName(className);
    for (Tree typeDecl : compUnitTree.getTypeDecls()) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
            ClassTree clazz = (ClassTree) typeDecl;
            if (clazz.getSimpleName().toString().equals(shortClassName)) {
                return clazz;
            }
        }
    }
    return null;
}
 
Example 9
Source File: MemberAdditionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testClassImplementingList() throws Exception {
    performTest("ClassImplementingList");

    source.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(Phase.RESOLVED);
            ClassTree topLevel = findTopLevelClass(copy);
            SourceUtilsTestUtil2.run(copy, new AddSimpleField(), topLevel);
        }
    }).commit();

    JavaSourceAccessor.getINSTANCE().revalidate(source);
    
    CompilationInfo check = SourceUtilsTestUtil.getCompilationInfo(source, Phase.RESOLVED);
    CompilationUnitTree cu = check.getCompilationUnit();

    assertEquals(check.getDiagnostics().toString(), 1, check.getDiagnostics().size());
    assertEquals("compiler.err.does.not.override.abstract", check.getDiagnostics().get(0).getCode());
    
    ClassTree newTopLevel = findTopLevelClass(check);
    Element clazz = check.getTrees().getElement(TreePath.getPath(cu, newTopLevel));
    Element pack = clazz.getEnclosingElement();
    
    assertEquals(ElementKind.PACKAGE, pack.getKind());
    assertEquals("test", ((PackageElement) pack).getQualifiedName().toString());
    assertEquals(clazz.getEnclosedElements().toString(), 1 + 1/*syntetic default constructor*/, clazz.getEnclosedElements().size());
}
 
Example 10
Source File: JSEmbeddingProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void colorizeJSB(final CompilationInfo ci) {
    final CompilationUnitTree cu = ci.getCompilationUnit();
    final Trees trees = ci.getTrees();
    final SourcePositions sp = trees.getSourcePositions();
    final Finder f = new Finder(trees);
    final List<LiteralTree> result = new ArrayList<>();
    f.scan(cu, result);
    if (!result.isEmpty()) {
        try {
            final TokenHierarchy<Document> tk = TokenHierarchy.get(ci.getDocument());
            final Language<?> java = Language.find(JAVA_MIME_TYPE);
            final Language<?> javaScript = Language.find(JAVASCRIPT_MIME_TYPE);
            if (java != null && javaScript != null) {
                final TokenSequence<?> seq = tk.tokenSequence(java);
                if (seq != null) {
                    for (LiteralTree lt : result) {
                        final int start = (int) sp.getStartPosition(cu, lt);
                        final int end = (int) sp.getEndPosition(cu, lt);
                        seq.move(start);
                        while (seq.moveNext() && seq.offset() < end) {
                            if (
                                seq.embedded() != null &&
                                seq.embedded().language() != null &&
                                "text/x-java-string".equals(seq.embedded().language().mimeType())
                            ) {
                                seq.removeEmbedding(seq.embedded().language());
                            }
                            seq.createEmbedding(javaScript, 1, 1, true);
                        }
                    }
                }
            }
        } catch (IOException ioe) {
            LOG.log(Level.WARNING, null, ioe);
        }
    }
}
 
Example 11
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public PreconditionsChecker(Tree forLoop, CompilationInfo workingCopy) {
    if (forLoop.getKind() == Tree.Kind.ENHANCED_FOR_LOOP) {
        this.isForLoop = true;
        this.workingCopy = workingCopy;
        this.hasUncaughtException = workingCopy.getTreeUtilities()
                .getUncaughtExceptions(TreePath.getPath(workingCopy.getCompilationUnit(), forLoop)).stream().anyMatch(this::filterCheckedExceptions);
        this.innerVariables = this.getInnerVariables(forLoop, workingCopy.getTrees());
        this.visitor = new ForLoopTreeVisitor(this.innerVariables, workingCopy, new TreePath(workingCopy.getCompilationUnit()), (EnhancedForLoopTree) forLoop);
        this.isIterable = this.isIterbale(((EnhancedForLoopTree) forLoop).getExpression());
        visitor.scan(TreePath.getPath(workingCopy.getCompilationUnit(), forLoop), workingCopy.getTrees());
    } else {
        this.isForLoop = false;
    }
}
 
Example 12
Source File: ElementScanningTaskFactory.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
public void run(CompilationInfo p) throws Exception {
    final CompilationUnitTree compilationUnitTree = p.getCompilationUnit();
    final TreePath rootPath = new TreePath(compilationUnitTree);
    mappedElementExtractor = new MappedElementExtractor(p.getFileObject(), compilationUnitTree, p.getTrees(), rootPath);
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            targetModel.refresh(compilationUnitTree.accept(mappedElementExtractor, null));
            table.setModel(targetModel);
        }
    });
}
 
Example 13
Source File: ComputeOverriding.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Map<ElementHandle<? extends Element>, List<ElementDescription>> process(CompilationInfo info) {
    IsOverriddenVisitor v = new IsOverriddenVisitor(info, cancel);
    CompilationUnitTree unit = info.getCompilationUnit();
    
    long startTime1 = System.currentTimeMillis();
    
    v.scan(unit, null);
    
    long endTime1 = System.currentTimeMillis();
    
    Logger.getLogger("TIMER").log(Level.FINE, "Overridden Scanner", //NOI18N
                new Object[] {info.getFileObject(), endTime1 - startTime1});
    
    Map<ElementHandle<? extends Element>, List<ElementDescription>> result = new HashMap<ElementHandle<? extends Element>, List<ElementDescription>>();
    
    for (ElementHandle<TypeElement> td : v.type2Declaration.keySet()) {
        if (isCanceled())
            return null;

        Map<ElementHandle<ExecutableElement>, List<ElementDescription>> overrides = compute(info, td, cancel);

        if (overrides != null) {
            result.putAll(overrides);
        }
    }
    
    if (isCanceled())
        return null;
    else
        return result;
}
 
Example 14
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isInHeader(CompilationInfo info, ClassTree tree, int offset) {
    CompilationUnitTree cut = info.getCompilationUnit();
    SourcePositions sp = info.getTrees().getSourcePositions();
    long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
    
    List<? extends Tree> impls = tree.getImplementsClause();
    List<? extends TypeParameterTree> typeparams;
    if (impls != null && !impls.isEmpty()) {
        lastKnownOffsetInHeader= sp.getEndPosition(cut, impls.get(impls.size() - 1));
    } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
        lastKnownOffsetInHeader= sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
    } else if (tree.getExtendsClause() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getExtendsClause());
    } else if (tree.getModifiers() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
    }
    
    TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
    
    ts.move((int) lastKnownOffsetInHeader);
    
    while (ts.moveNext()) {
        if (ts.token().id() == JavaTokenId.LBRACE) {
            return offset < ts.offset();
        }
    }
    
    return false;
}
 
Example 15
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isInHeader(CompilationInfo info, MethodTree tree, int offset) {
    CompilationUnitTree cut = info.getCompilationUnit();
    SourcePositions sp = info.getTrees().getSourcePositions();
    long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
    
    List<? extends ExpressionTree> throwz;
    List<? extends VariableTree> params;
    List<? extends TypeParameterTree> typeparams;
    
    if ((throwz = tree.getThrows()) != null && !throwz.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, throwz.get(throwz.size() - 1));
    } else if ((params = tree.getParameters()) != null && !params.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, params.get(params.size() - 1));
    } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
    } else if (tree.getReturnType() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getReturnType());
    } else if (tree.getModifiers() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
    }
    
    TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
    
    ts.move((int) lastKnownOffsetInHeader);
    
    while (ts.moveNext()) {
        if (ts.token().id() == JavaTokenId.LBRACE || ts.token().id() == JavaTokenId.SEMICOLON) {
            return offset < ts.offset();
        }
    }
    
    return false;
}
 
Example 16
Source File: SemanticHighlighterBase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected boolean process(CompilationInfo info, final Document doc, ErrorDescriptionSetter setter) {
    DetectorVisitor v = new DetectorVisitor(info, doc, cancel);
    
    Map<Token, Coloring> newColoring = new IdentityHashMap<>();

    CompilationUnitTree cu = info.getCompilationUnit();
    
    v.scan(cu, null);
    
    if (cancel.get())
        return true;
    
    boolean computeUnusedImports = "text/x-java".equals(FileUtil.getMIMEType(info.getFileObject()));
    
    List<Pair<int[], Coloring>> extraColoring = computeUnusedImports ? new ArrayList<>(v.extraColoring) : v.extraColoring;

    if (computeUnusedImports) {
        Collection<TreePath> unusedImports = UnusedImports.process(info, cancel);

        if (unusedImports == null) return true;
        
        Coloring unused = collection2Coloring(Arrays.asList(ColoringAttributes.UNUSED));

        for (TreePath tree : unusedImports) {
            if (cancel.get()) {
                return true;
            }

            //XXX: finish
            extraColoring.add(Pair.of(new int[] {
                (int) info.getTrees().getSourcePositions().getStartPosition(cu, tree.getLeaf()),
                (int) info.getTrees().getSourcePositions().getEndPosition(cu, tree.getLeaf())
            }, unused));
        }
    }
    
    for (Element decl : v.type2Uses.keySet()) {
        if (cancel.get())
            return true;
        
        List<Use> uses = v.type2Uses.get(decl);
        
        for (Use u : uses) {
            if (u.spec == null)
                continue;
            
            if (u.type.contains(UseTypes.DECLARATION) && Utilities.isPrivateElement(decl)) {
                if ((decl.getKind().isField() && !isSerialSpecField(info, decl)) || isLocalVariableClosure(decl)) {
                    if (!hasAllTypes(uses, EnumSet.of(UseTypes.READ, UseTypes.WRITE))) {
                        u.spec.add(ColoringAttributes.UNUSED);
                    }
                }
                
                if ((decl.getKind() == ElementKind.CONSTRUCTOR && !decl.getModifiers().contains(Modifier.PRIVATE)) || decl.getKind() == ElementKind.METHOD) {
                    if (!(hasAllTypes(uses, EnumSet.of(UseTypes.EXECUTE)) || isSerializationMethod(info, (ExecutableElement)decl))) {
                        u.spec.add(ColoringAttributes.UNUSED);
                    }
                }
                
                if (decl.getKind().isClass() || decl.getKind().isInterface()) {
                    if (!hasAllTypes(uses, EnumSet.of(UseTypes.CLASS_USE))) {
                        u.spec.add(ColoringAttributes.UNUSED);
                    }
                }
            }
            
            Coloring c = collection2Coloring(u.spec);
            
            List<Token> tl = v.tree2Tokens.get(u.tree.getLeaf());
            
            if (tl != null) {
                for (Token t : tl) {
                    newColoring.put(t, c);
                }
            }
        }
    }
    
    Coloring kwc = collection2Coloring(EnumSet.of(ColoringAttributes.KEYWORD));
    for (Token kw : v.contextKeywords) {
        newColoring.put(kw, kwc);
    }
    
    if (cancel.get())
        return true;
    
    if (computeUnusedImports) {
        setter.setHighlights(doc, extraColoring, v.preText);
    }

    setter.setColorings(doc, newColoring);

    return false;
}
 
Example 17
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static Token<JavaTokenId> createHighlightImpl(CompilationInfo info, Document doc, TreePath tree) {
    Tree leaf = tree.getLeaf();
    SourcePositions positions = info.getTrees().getSourcePositions();
    CompilationUnitTree cu = info.getCompilationUnit();
    
    //XXX: do not use instanceof:
    if (leaf instanceof MethodTree || leaf instanceof VariableTree || leaf instanceof ClassTree
            || leaf instanceof MemberSelectTree || leaf instanceof AnnotatedTypeTree || leaf instanceof MemberReferenceTree
            || "BINDING_PATTERN".equals(leaf.getKind().name())) {
        return findIdentifierSpan(info, doc, tree);
    }
    
    int start = (int) positions.getStartPosition(cu, leaf);
    int end = (int) positions.getEndPosition(cu, leaf);
    
    if (start == Diagnostic.NOPOS || end == Diagnostic.NOPOS) {
        return null;
    }
    
    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language());
    
    if (ts.move(start) == Integer.MAX_VALUE) {
        return null;
    }
    
    if (ts.moveNext()) {
        Token<JavaTokenId> token = ts.token();
        if (ts.offset() == start && token != null) {
            final JavaTokenId id = token.id();
            if (id == JavaTokenId.IDENTIFIER) {
                return token;
            }
            if (id == JavaTokenId.THIS || id == JavaTokenId.SUPER) {
                return ts.offsetToken();
            }
        }
    }
    
    return null;
}
 
Example 18
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public List<Fix> run(final CompilationInfo info, String diagnosticKey, final int offset, TreePath treePath, Data<Object> data) {
    TreePath path = deepTreePath(info, offset);
    if (path == null) {
        return null;
    }

    Map<Tree, Object> holder = data == null ? null : (Map)data.getData();
    Object saved = null;
    if (holder != null) {
        saved = holder.get(path.getLeaf());
    }
    if (Boolean.TRUE == saved) {
        return null;
    }
    Element e = info.getTrees().getElement(path);
    final Tree leaf = path.getLeaf();
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    boolean containsDefaultMethod = saved == Boolean.FALSE;

    boolean completingAnonymous = e != null && e.getKind() == ElementKind.CONSTRUCTOR && 
            leaf.getKind() == Tree.Kind.NEW_CLASS;
    TypeElement tel = findTypeElement(info, path);
    
    if (!Utilities.isValidElement(tel)) {
        return null;
    }
    List<Fix> fixes = new ArrayList<>();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(leaf.getKind()) || leaf.getKind().toString().equals(RECORD)) {
        CompilationUnitTree cut = info.getCompilationUnit();
        // do not offer for class declarations without body
        long start = info.getTrees().getSourcePositions().getStartPosition(cut, leaf);
        long end = info.getTrees().getSourcePositions().getEndPosition(cut, leaf);
        for (Diagnostic d : info.getDiagnostics()) {
            long position = d.getPosition();
            if (d.getCode().equals(PREMATURE_EOF_CODE) && position > start && position < end) {
                return null;
            }
        }
    }
    
    if (completingAnonymous) {
        //if the parent of path.getLeaf is an error, the situation probably is like:
        //new Runnable {}
        //(missing '()' for constructor)
        //do not propose the hint in this case:
        final boolean[] parentError = new boolean[] {false};
        new ErrorAwareTreePathScanner() {
            @Override
            public Object visitNewClass(NewClassTree nct, Object o) {
                if (leaf == nct) {
                    parentError[0] = getCurrentPath().getParentPath().getLeaf().getKind() == Kind.ERRONEOUS;
                }
                return super.visitNewClass(nct, o);
            }
        }.scan(path.getParentPath(), null);
        if (parentError[0]) {
            // ignore
            return null;
        }
        fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
    }
    boolean someAbstract = false;
    X: if (isUsableElement) {
        for (ExecutableElement ee : ElementFilter.methodsIn(e.getEnclosedElements())) {
            if (ee.getModifiers().contains(Modifier.ABSTRACT)) {
                // make class abstract. In case of enums, suggest to implement the
                // abstract methods on all enum values.
                if (e.getKind() == ElementKind.ENUM) {
                    // cannot make enum abstract, but can generate abstract methods skeleton
                    // to all enum members
                    fixes.add(new ImplementOnEnumValues2(info,  tel, containsDefaultMethod));
                    // avoid other possible fixes:
                    break X;
                } else if (e.getKind().isClass()) {
                    someAbstract = true;
                    break;
                }
            }
        }
        // offer to fix all abstract methods
        if (!someAbstract) {
            fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
        }
        if (e.getKind() == ElementKind.CLASS && e.getSimpleName() != null && !e.getSimpleName().contentEquals("")) {
            fixes.add(new MakeAbstractFix(info, path, e.getSimpleName().toString()).toEditorFix());
        }
    } 
    if (e != null && e.getKind() == ElementKind.ENUM_CONSTANT) {
        fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
    }
    return fixes;
}
 
Example 19
Source File: Matcher.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Matcher(CompilationInfo info) {
    this.info = info;
    this.root = new TreePath(info.getCompilationUnit());
    this.options.add(Options.ALLOW_GO_DEEPER);
}
 
Example 20
Source File: UnusedImports.java    From netbeans with Apache License 2.0 3 votes vote down vote up
public static Collection<TreePath> process(CompilationInfo info, AtomicBoolean cancel) {
    Collection<TreePath> result = (Collection<TreePath>) info.getCachedValue(KEY_CACHE);
    
    if (result != null) return result;
    
    DetectorVisitor v = new DetectorVisitor(info, cancel);
    
    CompilationUnitTree cu = info.getCompilationUnit();
    
    v.scan(cu, null);
    
    if (cancel.get())
        return null;
    
    List<TreePath> allUnusedImports = new ArrayList<TreePath>();

    for (TreePath tree : v.getUnusedImports().values()) {
        if (cancel.get()) {
            return null;
        }

        allUnusedImports.add(tree);
    }
    
    allUnusedImports = Collections.unmodifiableList(allUnusedImports);
    
    info.putCachedValue(KEY_CACHE, allUnusedImports, CacheClearPolicy.ON_CHANGE);
    
    return allUnusedImports;
}