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 Project: netbeans   Author: apache   File: InnerToOuterRefactoringUI.java    License: 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 #2
Source Project: netbeans   Author: apache   File: GeneratorUtilsTest.java    License: 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 #3
Source Project: netbeans   Author: apache   File: JavadocCompletionQuery.java    License: 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 #4
Source Project: netbeans   Author: apache   File: TooStrongCast.java    License: 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 #5
Source Project: netbeans   Author: apache   File: EqualsHashCodeGenerator.java    License: 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 #6
Source Project: netbeans   Author: apache   File: SimpleBuilderResolver.java    License: 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 #7
Source Project: netbeans   Author: apache   File: JavadocCompletionQuery.java    License: 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 #8
Source Project: netbeans   Author: apache   File: JavaSourceAccessor.java    License: 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 #9
Source Project: netbeans   Author: apache   File: JavadocUtilities.java    License: 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 #10
Source Project: netbeans   Author: apache   File: CreateMethodFix.java    License: 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 Project: netbeans   Author: apache   File: TokenList.java    License: 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 #12
Source Project: netbeans   Author: apache   File: ConvertToLambdaPreconditionChecker.java    License: 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 #13
Source Project: netbeans   Author: apache   File: CdiAnalysisTask.java    License: 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 #14
Source Project: netbeans   Author: apache   File: Utilities.java    License: 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 #15
Source Project: netbeans   Author: apache   File: NPECheck.java    License: 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 #16
Source Project: netbeans   Author: apache   File: Flow.java    License: 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 #17
Source Project: netbeans   Author: apache   File: ImplementAllAbstractMethods.java    License: 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 #18
Source Project: netbeans   Author: apache   File: ExpectedTypeResolver.java    License: 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 #19
Source Project: netbeans   Author: apache   File: ElementHeaderFormater.java    License: Apache License 2.0 5 votes vote down vote up
public static String getMethodHeader(MethodTree tree, ClassTree enclosingClass, CompilationInfo info, String s) {
    VeryPretty veryPretty = new VeryPretty(new DiffContext(info));
    if (enclosingClass != null) {
        veryPretty.enclClass = (com.sun.tools.javac.tree.JCTree.JCClassDecl) enclosingClass;
    }
    return veryPretty.getMethodHeader(tree, s);
}
 
Example #20
Source Project: netbeans   Author: apache   File: ChangeMethodReturnType.java    License: Apache License 2.0 5 votes vote down vote up
private TypeMirror purify(CompilationInfo info, TypeMirror targetType) {
    if (targetType != null && targetType.getKind() == TypeKind.ERROR) {
        targetType = info.getTrees().getOriginalType((ErrorType) targetType);
    }

    if (targetType == null || targetType.getKind() == /*XXX:*/TypeKind.ERROR || targetType.getKind() == TypeKind.NONE || targetType.getKind() == TypeKind.NULL) return null;

    return Utilities.resolveTypeForDeclaration(info, targetType);
}
 
Example #21
Source Project: netbeans   Author: apache   File: CopyFinderTest.java    License: Apache License 2.0 5 votes vote down vote up
protected VariableAssignments computeVariables(CompilationInfo info, TreePath searchingFor, TreePath scope, AtomicBoolean cancel, Map<String, TypeMirror> designedTypeHack) {
    Collection<VariableAssignments> values = CopyFinder.internalComputeDuplicates(info, Collections.singletonList(searchingFor), scope, null, null, new AtomicBooleanCancel(cancel), designedTypeHack, Options.ALLOW_VARIABLES_IN_PATTERN).values();

    if (values.iterator().hasNext()) {
        return values.iterator().next();
    } else {
        return null;
    }
}
 
Example #22
Source Project: netbeans   Author: apache   File: TestGeneratorSetup.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the given class is testable.
 *
 * @param  jc  class to be checked
 * @return  TestabilityResult that isOk, if the class is testable or carries
 *          the information why the class is not testable
 */
private TestabilityResult isClassTestableSingle(CompilationInfo compInfo,
                                                TypeElement classElem, long skipTestabilityResultMask) {
    assert classElem != null;
    
    TestabilityResult result = TestabilityResult.OK;

    /*
     * If the class is a test class and test classes should be skipped,
     * do not check nested classes (skip all):
     */
    /* Check if the class itself (w/o nested classes) is testable: */
    Set<Modifier> modifiers = classElem.getModifiers();

    if (modifiers.contains(PRIVATE))
        result = TestabilityResult.combine(result, TestabilityResult.PRIVATE_CLASS);
    if (isSkipTestClasses() && TestUtil.isClassImplementingTestInterface(compInfo, classElem)) 
        result = TestabilityResult.combine(result, TestabilityResult.TEST_CLASS);
    if (isSkipPackagePrivateClasses() && (modifiers.isEmpty() || !EnumSet.copyOf(modifiers).removeAll(ACCESS_MODIFIERS)))
        result = TestabilityResult.combine(result, TestabilityResult.PACKAGE_PRIVATE_CLASS);
    if (isSkipAbstractClasses() && modifiers.contains(ABSTRACT))
        result = TestabilityResult.combine(result, TestabilityResult.ABSTRACT_CLASS);
    if (!modifiers.contains(STATIC) && (classElem.getNestingKind() != NestingKind.TOP_LEVEL))
        result = TestabilityResult.combine(result, TestabilityResult.NONSTATIC_INNER_CLASS);
    // #175201
    // if (!hasTestableMethods(classElem))
    //    result = TestabilityResult.combine(result, TestabilityResult.NO_TESTEABLE_METHODS);
    if (isSkipExceptionClasses() && TestUtil.isClassException(compInfo, classElem)) 
        result = TestabilityResult.combine(result, TestabilityResult.EXCEPTION_CLASS);

    //apply filter mask
    result = TestabilityResult.filter(result, skipTestabilityResultMask);

    return result;
}
 
Example #23
Source Project: netbeans   Author: apache   File: HintsInvoker.java    License: Apache License 2.0 5 votes vote down vote up
public ScannerImpl(CompilationInfo info, AtomicBoolean cancel, Map<Kind, List<HintDescription>> hints, Collection<? super MessageImpl> problems) {
    super(cancel);
    this.info = info;
    this.file = null;
    this.env  = null;
    this.hints = hints;
    this.problems = problems;
}
 
Example #24
Source Project: netbeans   Author: apache   File: JSEmbeddingProvider.java    License: 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 #25
Source Project: netbeans   Author: apache   File: AssignResultToVariable.java    License: Apache License 2.0 5 votes vote down vote up
private StatementTree findStatementForgiving(CompilationInfo info, BlockTree block, int offset) {
    //<method-call>()|;
    StatementTree found = findMatchingMethodInvocation(info, block, offset);

    if (found != null) return found;

    //<method-call>();| or |<method-call>();
    StatementTree left = findExactStatement(info, block, offset, false);
    StatementTree right = findExactStatement(info, block, offset, true);

    if (left != null && right != null) {
        //cannot decide which one, stop
        return null;
    }

    if (left != null) return left;
    if (right != null) return right;

    //<method-call>;   | or |  <method-call>();
    int leftOffset = findFirstNonWhitespace(info, offset, true);
    int rightOffset = findFirstNonWhitespace(info, offset, false);
    
    left = findExactStatement(info, block, leftOffset, false);
    right = findExactStatement(info, block, rightOffset, true);

    if (left != null && right != null) {
        //cannot decide which one, stop
        return null;
    }

    return left != null ? left : right;
}
 
Example #26
Source Project: netbeans   Author: apache   File: SuspiciousNamesCombination.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, Integer> ensureNameMapLoaded(CompilationInfo info) {
    Map<String, Integer> mapNameToGroup = (Map<String, Integer>)info.getCachedValue(KEY);
    if (mapNameToGroup != null) {
        return mapNameToGroup;
    }
    mapNameToGroup = new HashMap<String, Integer>();
    Preferences prefs = getPreferences(null);
    String value = prefs.get(GROUP_KEY, DEFAULT_GROUPS);
    if (value == null) {
        info.putCachedValue(KEY, mapNameToGroup, CompilationInfo.CacheClearPolicy.ON_TASK_END);
        return mapNameToGroup;
    }
    String[] groups = value.split(Pattern.quote(GROUP_SEPARATOR));
    int idx = 0;
    for (String g : groups) {
        String[] names = g.split(SEPARATORS_REGEX);
        for (String n : names) {
            if (n.isEmpty()) {
                continue;
            }
            mapNameToGroup.put(n.toLowerCase(), idx);
        }
        idx++;
    }
    info.putCachedValue(KEY, mapNameToGroup, CompilationInfo.CacheClearPolicy.ON_TASK_END);
    return mapNameToGroup;
}
 
Example #27
Source Project: netbeans   Author: apache   File: JavadocCompletionItem.java    License: Apache License 2.0 5 votes vote down vote up
public static CompletionItem createExecutableItem(CompilationInfo info, ExecutableElement e,
        ExecutableType et, int startOffset, boolean isInherited,
        boolean isDeprecated) {
    
    CompletionItem delegate = JavaCompletionItem.createExecutableItem(
            info, e, et, null, startOffset, null, isInherited, isDeprecated, false, false, false, -1, false, null);
    return new JavadocExecutableItem(delegate, e, startOffset);
}
 
Example #28
Source Project: netbeans   Author: apache   File: ConvertAnonymousToInner.java    License: Apache License 2.0 5 votes vote down vote up
static Fix computeFix(CompilationInfo info, int selStart, int selEnd, boolean onlyHeader) {
    TreePath tp = findNCT(info, info.getTreeUtilities().pathFor((selStart + selEnd + 1) / 2), selStart, selEnd, onlyHeader);

    if (tp == null) {
        tp = findNCT(info, info.getTreeUtilities().pathFor((selStart + selEnd + 1) / 2 + 1), selStart, selEnd, onlyHeader);
    }
    
    if (tp == null) {
        return null;
    }
    
    return new FixImpl(TreePathHandle.create(tp, info), info.getJavaSource(), info.getFileObject());
}
 
Example #29
Source Project: netbeans   Author: apache   File: ErrorHintsProvider.java    License: 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 #30
Source Project: netbeans   Author: apache   File: Flow.java    License: 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;
}