Search in sources :

Example 31 with IndexNotReadyException

use of com.intellij.openapi.project.IndexNotReadyException in project intellij-community by JetBrains.

the class DependenciesHandlerBase method perform.

private void perform(List<DependenciesBuilder> builders) {
    try {
        PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot();
        for (AnalysisScope scope : myScopes) {
            builders.add(createDependenciesBuilder(scope));
        }
        for (DependenciesBuilder builder : builders) {
            builder.analyze();
        }
        snapshot.logResponsivenessSinceCreation("Dependency analysis");
    } catch (IndexNotReadyException e) {
        DumbService.getInstance(myProject).showDumbModeNotification("Analyze dependencies is not available until indices are ready");
        throw new ProcessCanceledException();
    }
}
Also used : PerformanceWatcher(com.intellij.diagnostic.PerformanceWatcher) AnalysisScope(com.intellij.analysis.AnalysisScope) DependenciesBuilder(com.intellij.packageDependencies.DependenciesBuilder) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 32 with IndexNotReadyException

use of com.intellij.openapi.project.IndexNotReadyException in project intellij-community by JetBrains.

the class HighlightMethodUtil method checkConstructorCall.

static void checkConstructorCall(@NotNull PsiClassType.ClassResolveResult typeResolveResult, @NotNull PsiConstructorCall constructorCall, @NotNull PsiType type, PsiJavaCodeReferenceElement classReference, @NotNull HighlightInfoHolder holder, @NotNull JavaSdkVersion javaSdkVersion) {
    PsiExpressionList list = constructorCall.getArgumentList();
    if (list == null)
        return;
    PsiClass aClass = typeResolveResult.getElement();
    if (aClass == null)
        return;
    final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(holder.getProject()).getResolveHelper();
    PsiClass accessObjectClass = null;
    if (constructorCall instanceof PsiNewExpression) {
        PsiExpression qualifier = ((PsiNewExpression) constructorCall).getQualifier();
        if (qualifier != null) {
            accessObjectClass = (PsiClass) PsiUtil.getAccessObjectClass(qualifier).getElement();
        }
    }
    if (classReference != null && !resolveHelper.isAccessible(aClass, constructorCall, accessObjectClass)) {
        String description = HighlightUtil.buildProblemWithAccessDescription(classReference, typeResolveResult);
        PsiElement element = classReference.getReferenceNameElement();
        HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
        HighlightUtil.registerAccessQuickFixAction(aClass, classReference, info, null);
        holder.add(info);
        return;
    }
    PsiMethod[] constructors = aClass.getConstructors();
    if (constructors.length == 0) {
        if (list.getExpressions().length != 0) {
            String constructorName = aClass.getName();
            String argTypes = buildArgTypesList(list);
            String description = JavaErrorMessages.message("wrong.constructor.arguments", constructorName + "()", argTypes);
            String tooltip = createMismatchedArgumentsHtmlTooltip(list, null, PsiParameter.EMPTY_ARRAY, constructorName, PsiSubstitutor.EMPTY, aClass);
            HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).description(description).escapedToolTip(tooltip).navigationShift(+1).create();
            QuickFixAction.registerQuickFixAction(info, constructorCall.getTextRange(), QUICK_FIX_FACTORY.createCreateConstructorFromCallFix(constructorCall));
            if (classReference != null) {
                ConstructorParametersFixer.registerFixActions(classReference, constructorCall, info, getFixRange(list));
            }
            holder.add(info);
            return;
        }
        if (classReference != null && aClass.hasModifierProperty(PsiModifier.PROTECTED) && callingProtectedConstructorFromDerivedClass(constructorCall, aClass)) {
            holder.add(buildAccessProblem(classReference, typeResolveResult, aClass));
        } else if (aClass.isInterface() && constructorCall instanceof PsiNewExpression) {
            final PsiReferenceParameterList typeArgumentList = ((PsiNewExpression) constructorCall).getTypeArgumentList();
            if (typeArgumentList.getTypeArguments().length > 0) {
                holder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(typeArgumentList).descriptionAndTooltip("Anonymous class implements interface; cannot have type arguments").create());
            }
        }
    } else {
        PsiElement place = list;
        if (constructorCall instanceof PsiNewExpression) {
            final PsiAnonymousClass anonymousClass = ((PsiNewExpression) constructorCall).getAnonymousClass();
            if (anonymousClass != null)
                place = anonymousClass;
        }
        JavaResolveResult[] results = resolveHelper.multiResolveConstructor((PsiClassType) type, list, place);
        MethodCandidateInfo result = null;
        if (results.length == 1)
            result = (MethodCandidateInfo) results[0];
        PsiMethod constructor = result == null ? null : result.getElement();
        boolean applicable = true;
        try {
            final PsiDiamondType diamondType = constructorCall instanceof PsiNewExpression ? PsiDiamondType.getDiamondType((PsiNewExpression) constructorCall) : null;
            final JavaResolveResult staticFactory = diamondType != null ? diamondType.getStaticFactory() : null;
            applicable = staticFactory instanceof MethodCandidateInfo ? ((MethodCandidateInfo) staticFactory).isApplicable() : result != null && result.isApplicable();
        } catch (IndexNotReadyException e) {
        // ignore
        }
        PsiElement infoElement = list.getTextLength() > 0 ? list : constructorCall;
        if (constructor == null) {
            String name = aClass.getName();
            name += buildArgTypesList(list);
            String description = JavaErrorMessages.message("cannot.resolve.constructor", name);
            HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).descriptionAndTooltip(description).navigationShift(+1).create();
            if (info != null) {
                WrapExpressionFix.registerWrapAction(results, list.getExpressions(), info);
                registerFixesOnInvalidConstructorCall(constructorCall, classReference, list, aClass, constructors, results, infoElement, info);
                holder.add(info);
            }
        } else {
            if (classReference != null && (!result.isAccessible() || constructor.hasModifierProperty(PsiModifier.PROTECTED) && callingProtectedConstructorFromDerivedClass(constructorCall, aClass))) {
                holder.add(buildAccessProblem(classReference, result, constructor));
            } else if (!applicable) {
                String constructorName = HighlightMessageUtil.getSymbolName(constructor, result.getSubstitutor());
                String containerName = HighlightMessageUtil.getSymbolName(constructor.getContainingClass(), result.getSubstitutor());
                String argTypes = buildArgTypesList(list);
                String description = JavaErrorMessages.message("wrong.method.arguments", constructorName, containerName, argTypes);
                String toolTip = createMismatchedArgumentsHtmlTooltip(result, list);
                HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(infoElement).description(description).escapedToolTip(toolTip).navigationShift(+1).create();
                if (info != null) {
                    JavaResolveResult[] methodCandidates = results;
                    if (constructorCall instanceof PsiNewExpression) {
                        methodCandidates = resolveHelper.getReferencedMethodCandidates((PsiCallExpression) constructorCall, true);
                    }
                    registerFixesOnInvalidConstructorCall(constructorCall, classReference, list, aClass, constructors, methodCandidates, infoElement, info);
                    registerMethodReturnFixAction(info, result, constructorCall);
                    holder.add(info);
                }
            } else {
                if (constructorCall instanceof PsiNewExpression) {
                    PsiReferenceParameterList typeArgumentList = ((PsiNewExpression) constructorCall).getTypeArgumentList();
                    HighlightInfo info = GenericsHighlightUtil.checkReferenceTypeArgumentList(constructor, typeArgumentList, result.getSubstitutor(), false, javaSdkVersion);
                    if (info != null) {
                        holder.add(info);
                    }
                }
            }
        }
        if (result != null && !holder.hasErrorResults()) {
            holder.add(checkVarargParameterErasureToBeAccessible(result, constructorCall));
        }
    }
}
Also used : HighlightInfo(com.intellij.codeInsight.daemon.impl.HighlightInfo) MethodCandidateInfo(com.intellij.psi.infos.MethodCandidateInfo) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException)

Example 33 with IndexNotReadyException

use of com.intellij.openapi.project.IndexNotReadyException in project intellij-community by JetBrains.

the class HighlightControlFlowUtil method checkVariableInitializedBeforeUsage.

@Nullable
public static HighlightInfo checkVariableInitializedBeforeUsage(@NotNull PsiReferenceExpression expression, @NotNull PsiVariable variable, @NotNull Map<PsiElement, Collection<PsiReferenceExpression>> uninitializedVarProblems, @NotNull PsiFile containingFile) {
    if (variable instanceof ImplicitVariable)
        return null;
    if (!PsiUtil.isAccessedForReading(expression))
        return null;
    int startOffset = expression.getTextRange().getStartOffset();
    final PsiElement topBlock;
    if (variable.hasInitializer()) {
        topBlock = PsiUtil.getVariableCodeBlock(variable, variable);
        if (topBlock == null)
            return null;
    } else {
        PsiElement scope = variable instanceof PsiField ? ((PsiField) variable).getContainingClass() : variable.getParent() != null ? variable.getParent().getParent() : null;
        if (scope instanceof PsiCodeBlock && scope.getParent() instanceof PsiSwitchStatement) {
            scope = PsiTreeUtil.getParentOfType(scope, PsiCodeBlock.class);
        }
        topBlock = FileTypeUtils.isInServerPageFile(scope) && scope instanceof PsiFile ? scope : PsiUtil.getTopLevelEnclosingCodeBlock(expression, scope);
        if (variable instanceof PsiField) {
            // non final field already initialized with default value
            if (!variable.hasModifierProperty(PsiModifier.FINAL))
                return null;
            // if we're inside non-ctr method, skip it
            if (PsiUtil.findEnclosingConstructorOrInitializer(expression) == null && HighlightUtil.findEnclosingFieldInitializer(expression) == null) {
                return null;
            }
            if (topBlock == null)
                return null;
            final PsiElement parent = topBlock.getParent();
            // access to final fields from inner classes always allowed
            if (inInnerClass(expression, ((PsiField) variable).getContainingClass()))
                return null;
            final PsiCodeBlock block;
            final PsiClass aClass;
            if (parent instanceof PsiMethod) {
                PsiMethod constructor = (PsiMethod) parent;
                if (!containingFile.getManager().areElementsEquivalent(constructor.getContainingClass(), ((PsiField) variable).getContainingClass()))
                    return null;
                // static variables already initialized in class initializers
                if (variable.hasModifierProperty(PsiModifier.STATIC))
                    return null;
                // as a last chance, field may be initialized in this() call
                final List<PsiMethod> redirectedConstructors = JavaHighlightUtil.getChainedConstructors(constructor);
                for (int j = 0; redirectedConstructors != null && j < redirectedConstructors.size(); j++) {
                    PsiMethod redirectedConstructor = redirectedConstructors.get(j);
                    // variable must be initialized before its usage
                    //???
                    //if (startOffset < redirectedConstructor.getTextRange().getStartOffset()) continue;
                    PsiCodeBlock body = redirectedConstructor.getBody();
                    if (body != null && variableDefinitelyAssignedIn(variable, body)) {
                        return null;
                    }
                }
                block = constructor.getBody();
                aClass = constructor.getContainingClass();
            } else if (parent instanceof PsiClassInitializer) {
                final PsiClassInitializer classInitializer = (PsiClassInitializer) parent;
                if (!containingFile.getManager().areElementsEquivalent(classInitializer.getContainingClass(), ((PsiField) variable).getContainingClass()))
                    return null;
                block = classInitializer.getBody();
                aClass = classInitializer.getContainingClass();
            } else {
                // field reference outside code block
                // check variable initialized before its usage
                final PsiField field = (PsiField) variable;
                aClass = field.getContainingClass();
                final PsiField anotherField = PsiTreeUtil.getTopmostParentOfType(expression, PsiField.class);
                if (aClass == null || isFieldInitializedInOtherFieldInitializer(aClass, field, field.hasModifierProperty(PsiModifier.STATIC))) {
                    return null;
                }
                if (anotherField != null && !anotherField.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.STATIC) && isFieldInitializedInClassInitializer(field, true, Arrays.stream(aClass.getInitializers()))) {
                    return null;
                }
                int offset = startOffset;
                if (anotherField != null && anotherField.getContainingClass() == aClass && !field.hasModifierProperty(PsiModifier.STATIC)) {
                    offset = 0;
                }
                block = null;
                // initializers will be checked later
                final PsiMethod[] constructors = aClass.getConstructors();
                for (PsiMethod constructor : constructors) {
                    // variable must be initialized before its usage
                    if (offset < constructor.getTextRange().getStartOffset())
                        continue;
                    PsiCodeBlock body = constructor.getBody();
                    if (body != null && variableDefinitelyAssignedIn(variable, body)) {
                        return null;
                    }
                    // as a last chance, field may be initialized in this() call
                    final List<PsiMethod> redirectedConstructors = JavaHighlightUtil.getChainedConstructors(constructor);
                    for (int j = 0; redirectedConstructors != null && j < redirectedConstructors.size(); j++) {
                        PsiMethod redirectedConstructor = redirectedConstructors.get(j);
                        // variable must be initialized before its usage
                        if (offset < redirectedConstructor.getTextRange().getStartOffset())
                            continue;
                        PsiCodeBlock redirectedBody = redirectedConstructor.getBody();
                        if (redirectedBody != null && variableDefinitelyAssignedIn(variable, redirectedBody)) {
                            return null;
                        }
                    }
                }
            }
            if (aClass != null) {
                // field may be initialized in class initializer
                final PsiClassInitializer[] initializers = aClass.getInitializers();
                for (PsiClassInitializer initializer : initializers) {
                    PsiCodeBlock body = initializer.getBody();
                    if (body == block)
                        break;
                    // variable referenced in initializer must be initialized in initializer preceding assignment
                    // variable referenced in field initializer or in class initializer
                    boolean shouldCheckInitializerOrder = block == null || block.getParent() instanceof PsiClassInitializer;
                    if (shouldCheckInitializerOrder && startOffset < initializer.getTextRange().getStartOffset())
                        continue;
                    if (initializer.hasModifierProperty(PsiModifier.STATIC) == variable.hasModifierProperty(PsiModifier.STATIC)) {
                        if (variableDefinitelyAssignedIn(variable, body))
                            return null;
                    }
                }
            }
        }
    }
    if (topBlock == null)
        return null;
    Collection<PsiReferenceExpression> codeBlockProblems = uninitializedVarProblems.get(topBlock);
    if (codeBlockProblems == null) {
        try {
            final ControlFlow controlFlow = getControlFlow(topBlock);
            codeBlockProblems = ControlFlowUtil.getReadBeforeWriteLocals(controlFlow);
        } catch (AnalysisCanceledException | IndexNotReadyException e) {
            codeBlockProblems = Collections.emptyList();
        }
        uninitializedVarProblems.put(topBlock, codeBlockProblems);
    }
    if (codeBlockProblems.contains(expression)) {
        final String name = expression.getElement().getText();
        String description = JavaErrorMessages.message("variable.not.initialized", name);
        HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
        QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createAddVariableInitializerFix(variable));
        if (variable instanceof PsiField) {
            QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createModifierListFix(variable, PsiModifier.FINAL, false, false));
        }
        return highlightInfo;
    }
    return null;
}
Also used : HighlightInfo(com.intellij.codeInsight.daemon.impl.HighlightInfo) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) Nullable(org.jetbrains.annotations.Nullable)

Example 34 with IndexNotReadyException

use of com.intellij.openapi.project.IndexNotReadyException in project intellij-community by JetBrains.

the class GenericsHighlightUtil method checkOverrideAnnotation.

@Nullable
static HighlightInfo checkOverrideAnnotation(@NotNull PsiMethod method, @NotNull PsiAnnotation overrideAnnotation, @NotNull LanguageLevel languageLevel) {
    try {
        MethodSignatureBackedByPsiMethod superMethod = SuperMethodsSearch.search(method, null, true, false).findFirst();
        if (superMethod != null && method.getContainingClass().isInterface()) {
            final PsiMethod psiMethod = superMethod.getMethod();
            final PsiClass containingClass = psiMethod.getContainingClass();
            if (containingClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName()) && psiMethod.hasModifierProperty(PsiModifier.PROTECTED)) {
                superMethod = null;
            }
        }
        if (superMethod == null) {
            String description = JavaErrorMessages.message("method.does.not.override.super");
            HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(overrideAnnotation).descriptionAndTooltip(description).create();
            QUICK_FIX_FACTORY.registerPullAsAbstractUpFixes(method, new QuickFixActionRegistrarImpl(highlightInfo));
            return highlightInfo;
        }
        PsiClass superClass = superMethod.getMethod().getContainingClass();
        if (languageLevel.equals(LanguageLevel.JDK_1_5) && superClass != null && superClass.isInterface()) {
            String description = JavaErrorMessages.message("override.not.allowed.in.interfaces");
            HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(overrideAnnotation).descriptionAndTooltip(description).create();
            QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createIncreaseLanguageLevelFix(LanguageLevel.JDK_1_6));
            return info;
        }
        return null;
    } catch (IndexNotReadyException e) {
        return null;
    }
}
Also used : QuickFixActionRegistrarImpl(com.intellij.codeInsight.daemon.impl.quickfix.QuickFixActionRegistrarImpl) HighlightInfo(com.intellij.codeInsight.daemon.impl.HighlightInfo) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) Nullable(org.jetbrains.annotations.Nullable)

Example 35 with IndexNotReadyException

use of com.intellij.openapi.project.IndexNotReadyException in project intellij-community by JetBrains.

the class CompletionProgressIndicator method duringCompletion.

void duringCompletion(CompletionInitializationContext initContext) {
    if (isAutopopupCompletion()) {
        if (shouldPreselectFirstSuggestion(myParameters)) {
            if (!CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS) {
                myLookup.setFocusDegree(LookupImpl.FocusDegree.SEMI_FOCUSED);
                if (FeatureUsageTracker.getInstance().isToBeAdvertisedInLookup(CodeCompletionFeatures.EDITING_COMPLETION_FINISH_BY_CONTROL_DOT, getProject())) {
                    String dotShortcut = CompletionContributor.getActionShortcut(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_DOT);
                    if (StringUtil.isNotEmpty(dotShortcut)) {
                        addAdvertisement("Press " + dotShortcut + " to choose the selected (or first) suggestion and insert a dot afterwards", null);
                    }
                }
            } else {
                myLookup.setFocusDegree(LookupImpl.FocusDegree.FOCUSED);
            }
        }
        if (!myEditor.isOneLineMode() && FeatureUsageTracker.getInstance().isToBeAdvertisedInLookup(CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ARROWS, getProject())) {
            String downShortcut = CompletionContributor.getActionShortcut(IdeActions.ACTION_LOOKUP_DOWN);
            String upShortcut = CompletionContributor.getActionShortcut(IdeActions.ACTION_LOOKUP_UP);
            if (StringUtil.isNotEmpty(downShortcut) && StringUtil.isNotEmpty(upShortcut)) {
                addAdvertisement(downShortcut + " and " + upShortcut + " will move caret down and up in the editor", null);
            }
        }
    } else if (DumbService.isDumb(getProject())) {
        addAdvertisement("The results might be incomplete while indexing is in progress", MessageType.WARNING.getPopupBackground());
    }
    ProgressManager.checkCanceled();
    Document document = initContext.getEditor().getDocument();
    if (!initContext.getOffsetMap().wasModified(CompletionInitializationContext.IDENTIFIER_END_OFFSET)) {
        try {
            final int selectionEndOffset = initContext.getSelectionEndOffset();
            final PsiReference reference = TargetElementUtil.findReference(myEditor, selectionEndOffset);
            if (reference != null) {
                final int replacementOffset = findReplacementOffset(selectionEndOffset, reference);
                if (replacementOffset > document.getTextLength()) {
                    LOG.error("Invalid replacementOffset: " + replacementOffset + " returned by reference " + reference + " of " + reference.getClass() + "; doc=" + document + "; doc actual=" + (document == initContext.getFile().getViewProvider().getDocument()) + "; doc committed=" + PsiDocumentManager.getInstance(getProject()).isCommitted(document));
                } else {
                    initContext.setReplacementOffset(replacementOffset);
                }
            }
        } catch (IndexNotReadyException ignored) {
        }
    }
    for (CompletionContributor contributor : CompletionContributor.forLanguage(initContext.getPositionLanguage())) {
        ProgressManager.checkCanceled();
        if (DumbService.getInstance(initContext.getProject()).isDumb() && !DumbService.isDumbAware(contributor)) {
            continue;
        }
        contributor.duringCompletion(initContext);
    }
    if (document instanceof DocumentWindow) {
        myHostOffsets = new OffsetsInFile(initContext.getFile(), initContext.getOffsetMap()).toTopLevelFile();
    }
}
Also used : DocumentWindow(com.intellij.injected.editor.DocumentWindow) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) PsiReference(com.intellij.psi.PsiReference) Document(com.intellij.openapi.editor.Document) LightweightHint(com.intellij.ui.LightweightHint)

Aggregations

IndexNotReadyException (com.intellij.openapi.project.IndexNotReadyException)70 Nullable (org.jetbrains.annotations.Nullable)14 ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)12 PsiElement (com.intellij.psi.PsiElement)11 Project (com.intellij.openapi.project.Project)10 PsiFile (com.intellij.psi.PsiFile)10 TextRange (com.intellij.openapi.util.TextRange)9 VirtualFile (com.intellij.openapi.vfs.VirtualFile)8 NotNull (org.jetbrains.annotations.NotNull)8 Document (com.intellij.openapi.editor.Document)6 Editor (com.intellij.openapi.editor.Editor)6 LocalQuickFixAndIntentionActionOnPsiElement (com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement)5 Ref (com.intellij.openapi.util.Ref)4 LightweightHint (com.intellij.ui.LightweightHint)4 HighlightInfo (com.intellij.codeInsight.daemon.impl.HighlightInfo)3 Module (com.intellij.openapi.module.Module)3 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)3 StringUtil (com.intellij.openapi.util.text.StringUtil)3 PsiClass (com.intellij.psi.PsiClass)3 javax.swing (javax.swing)3