org.netbeans.api.java.source.CompilationInfo Java Examples

The following examples show how to use org.netbeans.api.java.source.CompilationInfo. 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: SimpleBuilderResolver.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String findBuilderClass(CompilationInfo cinfo, Source source, String beanClassName) {
    TypeElement classElement = cinfo.getElements().getTypeElement(beanClassName);
    if (classElement == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder(((PackageElement)classElement.getEnclosingElement()).getQualifiedName().toString());
    if (sb.length() > 0) {
        sb.append("."); // NOI18N
    }
    sb.append(classElement.getSimpleName().toString()).append("Builder"); // NOI18N
    
    TypeElement builderEl = cinfo.getElements().getTypeElement(sb.toString());
    return builderEl != null ?
            sb.toString() :
            null;
}
 
Example #2
Source File: NPECheck.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public VisitorImpl(HintContext ctx, CompilationInfo aInfo, AtomicBoolean cancel) {
    this.ctx = ctx;
    if (ctx != null) {
        this.info = ctx.getInfo();
        this.cancelFlag = null;
    } else {
        this.info = aInfo;
        this.cancelFlag = cancel != null ? cancel : new AtomicBoolean(false);
    }

    
    this.throwableEl = this.info.getElements().getTypeElement("java.lang.Throwable"); // NOI18N
    TypeElement tel =  this.info.getElements().getTypeElement("java.lang.RuntimeException"); // NOI18N
    if (tel != null) {
        runtimeExceptionType = tel.asType();
    } else {
        runtimeExceptionType = null;
    }
    tel =  this.info.getElements().getTypeElement("java.lang.Error"); // NOI18N
    if (tel != null) {
        errorType = tel.asType();
    } else {
        errorType = null;
    }
}
 
Example #3
Source File: InnerToOuterRefactoringUI.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public RefactoringUI create(CompilationInfo info, TreePathHandle[] handles, FileObject[] files, NonRecursiveFolder[] packages) {
    assert handles.length == 1;
    TreePath resolved = handles[0].resolve(info);
    TreePath enclosing = resolved == null
            ? null
            : JavaRefactoringUtils.findEnclosingClass(info, resolved, true, true, true, true, false);
    if (enclosing != null && enclosing != resolved) {
            handles[0] = TreePathHandle.create(enclosing, info);
    }
    if(handles[0] != null && resolved != null) {
        Element inner = handles[0].resolveElement(info);
        if(inner != null && inner.getKind() != ElementKind.PACKAGE) {
            TypeElement outer = info.getElementUtilities().enclosingTypeElement(inner);
            if (outer != null && outer.getEnclosedElements().contains(inner)) {
                return new InnerToOuterRefactoringUI(handles[0], info);
            }
        }
    }
    return null;
}
 
Example #4
Source File: Flow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public VisitorImpl(CompilationInfo info, TypeElement undefinedSymbolScope, Cancel cancel) {
    super();
    this.info = info;
    this.cancel = cancel;
    this.undefinedSymbolScope = undefinedSymbolScope;
    this.thisName = info.getElements().getName("this");

    this.throwableEl = info.getElements().getTypeElement("java.lang.Throwable"); // NOI18N
    TypeElement tel =  info.getElements().getTypeElement("java.lang.RuntimeException"); // NOI18N
    if (tel != null) {
        runtimeExceptionType = tel.asType();
    } else {
        runtimeExceptionType = null;
    }
    tel =  info.getElements().getTypeElement("java.lang.Error"); // NOI18N
    if (tel != null) {
        errorType = tel.asType();
    } else {
        errorType = null;
    }
}
 
Example #5
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static TreePath deepTreePath(CompilationInfo info, int offset) {
    TreePath basic = info.getTreeUtilities().pathFor(offset);
    TreePath plusOne = info.getTreeUtilities().pathFor(offset + 1);
    
    TreePath parent = plusOne.getParentPath();
    if (parent == null) {
        return basic;
    }
    if (plusOne.getLeaf().getKind() == Kind.NEW_CLASS &&
        parent.getLeaf().getKind() == Kind.EXPRESSION_STATEMENT) {
        parent = parent.getParentPath();
        if (parent == null) {
            return basic;
        }
    }
    if (parent.getLeaf() == basic.getLeaf()) {
        return plusOne;
    }
    return basic;
}
 
Example #6
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean isMethodHeaderInsideGuardedBlock(CompilationInfo info, MethodTree method) {
    try {
        Document doc = info.getDocument();

        if (doc instanceof GuardedDocument) {
            GuardedDocument bdoc = (GuardedDocument) doc;
            int methodStart = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), method);
            int methodEnd = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), method);

            return (bdoc.getGuardedBlockChain().compareBlock(methodStart, methodEnd) & MarkBlock.OVERLAP) != 0;
        }

        return false;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        return false;
    }
}
 
Example #7
Source File: GeneratorUtilsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void validate(CompilationInfo info) {
    TypeElement test = info.getElements().getTypeElement("test.Test");
    
    boolean foundRunMethod = false;
    
    for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) {
        if ("run".equals(ee.getSimpleName().toString())) {
            if (ee.getParameters().isEmpty()) {
                assertFalse(foundRunMethod);
                foundRunMethod = true;
            }
        }
    }
    
    assertTrue(foundRunMethod);
}
 
Example #8
Source File: CdiAnalysisTask.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void run( CompilationInfo compInfo ) {
    setResult( createResult( compInfo ) );
    List<? extends TypeElement> types = compInfo.getTopLevelElements();
    for (TypeElement typeElement : types) {
        if ( isCancelled() ){
            break;
        }
        analyzeType(typeElement, null );
    }
    EditorAnnotationsHelper helper = EditorAnnotationsHelper.getInstance(getResult());
    if ( helper == null ){
        return;
    }
    helper.publish( getResult() );
}
 
Example #9
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addInnerClasses(TypeElement te, EnumSet<ElementKind> kinds, DeclaredType baseType, Set<? extends Element> toExclude, String prefix, int substitutionOffset, JavadocContext jdctx) {
    CompilationInfo controller = jdctx.javac;
    Element srcEl = jdctx.handle.resolve(controller);
    Elements elements = controller.getElements();
    Types types = controller.getTypes();
    Trees trees = controller.getTrees();
    TreeUtilities tu = controller.getTreeUtilities();
    TreePath docpath = srcEl != null ? trees.getPath(srcEl) : null;
    Scope scope = docpath != null ? trees.getScope(docpath) : tu.scopeFor(caretOffset);
    for (Element e : controller.getElementUtilities().getMembers(te.asType(), null)) {
        if ((e.getKind().isClass() || e.getKind().isInterface()) && (toExclude == null || !toExclude.contains(e))) {
            String name = e.getSimpleName().toString();
                if (Utilities.startsWith(name, prefix) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e)) && trees.isAccessible(scope, (TypeElement)e) && isOfKindAndType(e.asType(), e, kinds, baseType, scope, trees, types)) {
                    items.add(JavadocCompletionItem.createTypeItem(jdctx.javac, (TypeElement) e, substitutionOffset, null, elements.isDeprecated(e)/*, isOfSmartType(env, e.asType(), smartTypes)*/));
            }
        }
    }
}
 
Example #10
Source File: CreateMethodFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public String toDebugString(CompilationInfo info) {
    StringBuilder value = new StringBuilder();
    
    if (returnType != null) {
        value.append("CreateMethodFix:"); // NOI18N
        value.append(name);
        addArguments(info, value);
        value.append(org.netbeans.modules.editor.java.Utilities.getTypeName(info, returnType.resolve(info), true));
    } else {
        value.append("CreateConstructorFix:"); // NOI18N
        addArguments(info, value);
    }
    
    value.append(':'); // NOI18N
    value.append(inFQN); // NOI18N
    
    return value.toString();
}
 
Example #11
Source File: TooStrongCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether a method or constructor call would become ambiguous if the parameter type changes.
 * 
 * @param info compilation context
 * @param parentExec path to the constructor or method invocation
 * @param argIndex
 * @param casteeType
 * @return 
 */
private static boolean checkAmbiguous(CompilationInfo info, final TreePath parentExec, int argIndex, TypeMirror casteeType, TreePath realArgTree) {
    CharSequence altType = info.getTypeUtilities().getTypeName(casteeType, TypeUtilities.TypeNameOptions.PRINT_FQN);
    String prefix = null;
    if (casteeType != null && !(casteeType.getKind() == TypeKind.NULL || casteeType.getKind() == TypeKind.INTERSECTION)) {
        prefix = "(" + altType + ")"; // NOI18N
    }
    Tree leaf = parentExec.getLeaf();
    List<? extends Tree> arguments;
    if (leaf instanceof MethodInvocationTree) {
        MethodInvocationTree mi = (MethodInvocationTree)leaf;
        arguments = mi.getArguments();
    } else {
        arguments = ((NewClassTree)leaf).getArguments();
    }
    Tree argTree = arguments.get(argIndex);
    TreePath argPath = new TreePath(parentExec, argTree);
    return !Utilities.checkAlternativeInvocation(info, parentExec, argPath, realArgTree, prefix);
}
 
Example #12
Source File: EqualsHashCodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static KindOfType detectKind(CompilationInfo info, TypeMirror tm) {
    if (tm.getKind().isPrimitive()) {
        return KindOfType.valueOf(tm.getKind().name());
    }

    if (tm.getKind() == TypeKind.ARRAY) {
        return ((ArrayType) tm).getComponentType().getKind().isPrimitive() ? KindOfType.ARRAY_PRIMITIVE : KindOfType.ARRAY;
    }

    if (tm.getKind() == TypeKind.DECLARED) {
        Types t = info.getTypes();
        TypeElement en = info.getElements().getTypeElement("java.lang.Enum");

        if (en != null) {
            if (t.isSubtype(tm, t.erasure(en.asType()))) {
                return KindOfType.ENUM;
            }
        }

        if (((DeclaredType)tm).asElement().getKind().isClass() && ((TypeElement) ((DeclaredType) tm).asElement()).getQualifiedName().contentEquals("java.lang.String")) {
            return KindOfType.STRING;
        }
    }

    return KindOfType.OTHER;
}
 
Example #13
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean isGuarded(Tree node, CompilationInfo javac, Document doc) {
    GuardedSectionManager guards = GuardedSectionManager.getInstance((StyledDocument) doc);
    if (guards != null) {
        try {
            final int startOff = (int) javac.getTrees().getSourcePositions().
                    getStartPosition(javac.getCompilationUnit(), node);
            final Position startPos = doc.createPosition(startOff);

            for (GuardedSection guard : guards.getGuardedSections()) {
                if (guard.contains(startPos, false)) {
                    return true;
                }
            }
        } catch (BadLocationException ex) {
            Logger.getLogger(Analyzer.class.getName()).log(Level.INFO, ex.getMessage(), ex);
            // consider it as guarded
            return true;
        }
    }
    return false;
}
 
Example #14
Source File: JavaSourceAccessor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void addPhaseCompletionTask (final JavaSource js,
        final CancellableTask<CompilationInfo> task,
        final JavaSource.Phase phase,
        final JavaSource.Priority priority,
        final TaskIndexingMode taskIndexingMode) {
    
    final Collection<Source> sources = getSources(js);
    assert sources.size() == 1;
    final int pp = translatePriority(priority);
    if (tasks.keySet().contains(task)) {
        throw new IllegalArgumentException(String.format("Task: %s is already scheduled", task.toString()));   //NOI18N
    }
    final ParserResultTask<?> hanz = new CancelableTaskWrapper(task, pp, phase, js, taskIndexingMode);
    tasks.put(task, hanz);
    Utilities.addParserResultTask(hanz, sources.iterator().next());
}
 
Example #15
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addAllTypes(JavadocContext env, EnumSet<ElementKind> kinds, Set<? extends Element> toExclude, String prefix, int substitutionOffset) {
//        String prefix = env.getPrefix();
        CompilationInfo controller = env.javac;
        boolean isCaseSensitive = false;
        ClassIndex.NameKind kind = 
            isCaseSensitive? ClassIndex.NameKind.PREFIX : ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX;
//        ClassIndex.NameKind kind = env.isCamelCasePrefix() ?
//            Utilities.isCaseSensitive() ? ClassIndex.NameKind.CAMEL_CASE : ClassIndex.NameKind.CAMEL_CASE_INSENSITIVE :
//            Utilities.isCaseSensitive() ? ClassIndex.NameKind.PREFIX : ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX;
        Set<ElementHandle<Element>> excludeHandles = null;
        if (toExclude != null) {
            excludeHandles = new HashSet<ElementHandle<Element>>(toExclude.size());
            for (Element el : toExclude) {
                excludeHandles.add(ElementHandle.create(el));
            }
        }
        for(ElementHandle<TypeElement> name : controller.getClasspathInfo().getClassIndex().getDeclaredTypes(prefix, kind, EnumSet.allOf(ClassIndex.SearchScope.class))) {
            if ((excludeHandles == null || !excludeHandles.contains(name)) && !isAnnonInner(name)) {
                items.add(LazyJavaCompletionItem.createTypeItem(name, kinds, substitutionOffset, env.getReferencesCount(), controller.getSnapshot().getSource(), false, false, false, null));
            }
        }
    }
 
Example #16
Source File: TokenList.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public TokenList(CompilationInfo info, final Document doc, AtomicBoolean cancel) {
    this.info = info;
    this.doc = doc;
    this.cancel = cancel;
    
    this.sourcePositions = info.getTrees().getSourcePositions();
    
    doc.render(new Runnable() {
        @Override
        public void run() {
            if (TokenList.this.cancel.get()) {
                return ;
            }
            
            topLevel = TokenHierarchy.get(doc).tokenSequence();
            
            topLevelIsJava = topLevel.language() == JavaTokenId.language();
            
            if (topLevelIsJava) {
                ts = topLevel;
                ts.moveStart();
                ts.moveNext(); //XXX: what about empty document
            }
        }
    });
}
 
Example #17
Source File: ConvertToLambdaPreconditionChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public ConvertToLambdaPreconditionChecker(TreePath pathToNewClassTree, CompilationInfo info) {

        this.pathToNewClassTree = pathToNewClassTree;
        this.newClassTree = (NewClassTree) pathToNewClassTree.getLeaf();
        this.info = info;
        this.types = info.getTypes();

        Element el = info.getTrees().getElement(pathToNewClassTree);
        if (el != null && el.getKind() == ElementKind.CONSTRUCTOR) {
            createdClass = el.getEnclosingElement();
        } else {
            createdClass = null;
        }
        this.lambdaMethodTree = getMethodFromFunctionalInterface(this.pathToNewClassTree);
        this.localScope = getScopeFromTree(this.pathToNewClassTree);
        this.ownerClass = findFieldOwner();
    }
 
Example #18
Source File: FindLocalUsagesQuery.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Set<Token> findUsages(Element element, CompilationInfo info, Document doc) {
    this.info = info;
    this.usages = new HashSet<Token>();
    this.toFind = element;
    this.doc = doc;
    
    scan(info.getCompilationUnit(), null);
    return usages;
}
 
Example #19
Source File: WebBeansAnalysisTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void analyzeType(TypeElement typeElement , TypeElement parent ,
        WebBeansModel model , CompilationInfo info )
{
    ElementKind kind = typeElement.getKind();
    ModelAnalyzer analyzer = ANALIZERS.get( kind );
    if ( analyzer != null ){
        analyzer.analyze(typeElement, parent, model, getCancel(), getResult());
    }
    if ( isCancelled() ){
        return;
    }
    List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
    List<TypeElement> types = ElementFilter.typesIn(enclosedElements);
    for (TypeElement innerType : types) {
        if ( innerType == null ){
            continue;
        }
        analyzeType(innerType, typeElement , model , info );
    }
    Set<Element> enclosedSet = new HashSet<Element>( enclosedElements );
    enclosedSet.removeAll( types );
    for(Element element : enclosedSet ){
        if ( element == null ){
            continue;
        }
        analyze(typeElement, model, element, info );
    }
}
 
Example #20
Source File: Flow.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static FlowResult assignmentsForUse(CompilationInfo info, Cancel cancel) {
    FlowResult result = (FlowResult) info.getCachedValue(KEY_FLOW);
    
    if (result == null) {
        result = assignmentsForUse(info, new TreePath(info.getCompilationUnit()), cancel);
        
        if (result != null && !cancel.isCanceled()) {
            info.putCachedValue(KEY_FLOW, result, CacheClearPolicy.ON_TASK_END);
        }
    }
    
    return result;
}
 
Example #21
Source File: DelegateFieldAnalizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Collection<TypeMirror> getDecoratedTypes( TypeElement element , 
        CompilationInfo info ) 
{
    TypeElement serializable = info.getElements().getTypeElement(
            Serializable.class.getCanonicalName());
    Collection<TypeMirror> result = new LinkedList<TypeMirror>();
    collectDecoratedTypes( element.asType() , result , serializable, info );
    return result;
}
 
Example #22
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Only for members (i.e. generated constructor):
 */
public static List<? extends Tree> filterHidden(CompilationInfo info, TreePath basePath, Iterable<? extends Tree> members) {
    List<Tree> result = new LinkedList<Tree>();

    for (Tree t : members) {
        if (!info.getTreeUtilities().isSynthetic(new TreePath(basePath, t))) {
            result.add(t);
        }
    }

    return result;
}
 
Example #23
Source File: ChangeMethodParameters.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    try {
        cancel = false;
        return analyze(info, offset);
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
        return null;
    }
}
 
Example #24
Source File: Flow.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean definitellyAssignedImpl(CompilationInfo info, 
        Element var, TypeElement scope, 
        Iterable<? extends TreePath> trees, boolean reassignAllowed, Cancel cancel) {
    VisitorImpl v = new VisitorImpl(info, scope, cancel);
    if (scope != null) {
        v.canonicalUndefined(var);
    }
    v.variable2State.put(var, State.create(null, false));

    for (TreePath tp : trees) {
        if (cancel.isCanceled()) return false;
        
        v.scan(tp, null);
        
        TreePath toResume = tp;
        
        while (toResume != null) {
            v.resume(toResume.getLeaf(), v.resumeAfter);
            toResume = toResume.getParentPath();
        }

        State s = v.variable2State.get(var);
        if (s == null) {
            s = v.variable2StateFinal.get(var);
        }
        if (s != null && !s.assignments.contains(null)) {
            return reassignAllowed || !s.reassigned;
        }
    }

    return false;
}
 
Example #25
Source File: MissingJavaEEForUnitTestExecutionHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isEEType(CompilationInfo info, TypeMirror type) {
    if (type == null) {
        return false;
    }
    if (isEEType(type)) {
        return true;
    }
    List<? extends TypeMirror> l = info.getTypes().directSupertypes(type);
    for (TypeMirror m : l) {
        if (isEEType(info, m)) {
            return true;
        }
    }
    return false;
}
 
Example #26
Source File: ErrorHintsProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public PosExtractor(CompilationInfo info, StyledDocument doc, int startOffset, int endOffset, DataObject dobj, boolean rangePrepared) {
    this.info = info;
    this.sdoc = doc;
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.rangePrepared = rangePrepared;
    this.dobj = dobj;
}
 
Example #27
Source File: IntroduceAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TreePath pathFor(CompilationInfo info, int pos) {
    TokenSequence<JavaTokenId> ts = info.getTokenHierarchy().tokenSequence(JavaTokenId.language());

    ts.move(info.getSnapshot().getEmbeddedOffset(pos));

    if (ts.moveNext() && ts.token().id() == JavaTokenId.IDENTIFIER) {
        pos = ts.offset() + 1;
    }

    return info.getTreeUtilities().pathFor(pos);
}
 
Example #28
Source File: ErrorNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of ErrorNode */
public ErrorNode(CompilationInfo info, Diagnostic diag) {
    super(Children.LEAF); //always leaf
    this.info = info;
    this.diag = diag;
    String ss = diag.getMessage(Locale.ENGLISH);
    setDisplayName(diag.getCode() + " " + diag.getKind() + ": " + ss); //NOI18N
    setIconBaseWithExtension("org/netbeans/modules/java/debug/resources/element.png"); //NOI18N
}
 
Example #29
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Finds and returns the most generic super types, which declare the method. The expected return type and
 * accessing Element must be provided, so that the method declaration is really accessible to the potential
 * caller.
 * 
 * @param methodType the method type to search for.
 * @return 
 */
static List<TypeMirror> findBaseTypes(CompilationInfo info, 
        ExecutableElement method,
        DeclaredType startFrom,
        Collection<? extends TypeMirror> expectedReturnType, 
        TypeMirror castableToType, 
        Scope accessor) {
    Set<TypeMirror> seenTypes = new HashSet<TypeMirror>();
    List<TypeMirror> collected = new ArrayList<TypeMirror>();
    collectMethods(info, accessor, method, expectedReturnType, castableToType,
            startFrom, collected, seenTypes);
    return collected;
}
 
Example #30
Source File: CreateFieldTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Fix> computeFixes(CompilationInfo info, String diagnosticCode, int pos, TreePath path) throws Exception {
    List<Fix> fixes = CreateElement.analyze(info, diagnosticCode, pos);
    List<Fix> result=  new LinkedList<Fix>();
    
    for (Fix f : fixes) {
        if (f instanceof CreateFieldFix)
            result.add(f);
    }
    
    return result;
}