Search in sources :

Example 41 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class InlineUtil method solveVariableNameConflicts.

public static void solveVariableNameConflicts(final PsiElement scope, final PsiElement placeToInsert, final PsiElement renameScope) throws IncorrectOperationException {
    if (scope instanceof PsiVariable) {
        PsiVariable var = (PsiVariable) scope;
        String name = var.getName();
        String oldName = name;
        final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(scope.getProject());
        while (true) {
            String newName = codeStyleManager.suggestUniqueVariableName(name, placeToInsert, true);
            if (newName.equals(name))
                break;
            name = newName;
            newName = codeStyleManager.suggestUniqueVariableName(name, var, true);
            if (newName.equals(name))
                break;
            name = newName;
        }
        if (!name.equals(oldName)) {
            RefactoringUtil.renameVariableReferences(var, name, new LocalSearchScope(renameScope), true);
            var.getNameIdentifier().replace(JavaPsiFacade.getElementFactory(scope.getProject()).createIdentifier(name));
        }
    }
    PsiElement[] children = scope.getChildren();
    for (PsiElement child : children) {
        solveVariableNameConflicts(child, placeToInsert, renameScope);
    }
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 42 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class FindManagerTest method testFindInCurrentFileOutsideProject.

public void testFindInCurrentFileOutsideProject() throws Exception {
    final TempDirTestFixture tempDirFixture = new TempDirTestFixtureImpl();
    tempDirFixture.setUp();
    try {
        VirtualFile file = tempDirFixture.createFile("a.txt", "foo bar foo");
        FindModel findModel = FindManagerTestUtils.configureFindModel("foo");
        findModel.setWholeWordsOnly(true);
        findModel.setCustomScope(true);
        findModel.setCustomScope(new LocalSearchScope(PsiManager.getInstance(myProject).findFile(file)));
        assertSize(2, findUsages(findModel));
    } finally {
        tempDirFixture.tearDown();
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LightVirtualFile(com.intellij.testFramework.LightVirtualFile) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) TempDirTestFixture(com.intellij.testFramework.fixtures.TempDirTestFixture) LightTempDirTestFixtureImpl(com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl) TempDirTestFixtureImpl(com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl)

Example 43 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class FindManagerTest method testLocalScopeSearchPerformance.

public void testLocalScopeSearchPerformance() throws Exception {
    final int fileCount = 3000;
    final int lineCount = 500;
    TempDirTestFixture fixture = new LightTempDirTestFixtureImpl();
    fixture.setUp();
    try {
        String sampleText = StringUtil.repeat("zoo TargetWord foo bar goo\n", lineCount);
        for (int i = 0; i < fileCount; i++) {
            fixture.createFile("a" + i + ".txt", sampleText);
        }
        PsiTestUtil.addSourceContentToRoots(myModule, fixture.getFile(""));
        VirtualFile file = fixture.createFile("target.txt", sampleText);
        PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
        assertNotNull(psiFile);
        final FindModel findModel = new FindModel();
        findModel.setStringToFind("TargetWord");
        findModel.setWholeWordsOnly(true);
        findModel.setFromCursor(false);
        findModel.setGlobal(true);
        findModel.setMultipleFiles(true);
        findModel.setCustomScope(true);
        ThrowableRunnable test = () -> assertSize(lineCount, findUsages(findModel));
        findModel.setCustomScope(GlobalSearchScope.fileScope(psiFile));
        PlatformTestUtil.startPerformanceTest("slow", 400, test).attempts(2).cpuBound().usesAllCPUCores().useLegacyScaling().assertTiming();
        findModel.setCustomScope(new LocalSearchScope(psiFile));
        PlatformTestUtil.startPerformanceTest("slow", 400, test).attempts(2).cpuBound().usesAllCPUCores().useLegacyScaling().assertTiming();
    } finally {
        fixture.tearDown();
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LightVirtualFile(com.intellij.testFramework.LightVirtualFile) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) TempDirTestFixture(com.intellij.testFramework.fixtures.TempDirTestFixture) ThrowableRunnable(com.intellij.util.ThrowableRunnable) LightTempDirTestFixtureImpl(com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl)

Example 44 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class DeclarationJoinLinesHandler method tryJoinLines.

@Override
public int tryJoinLines(final Document document, final PsiFile file, final int start, final int end) {
    PsiElement elementAtStartLineEnd = file.findElementAt(start);
    PsiElement elementAtNextLineStart = file.findElementAt(end);
    if (elementAtStartLineEnd == null || elementAtNextLineStart == null)
        return -1;
    // first line.
    if (!(elementAtStartLineEnd instanceof PsiJavaToken))
        return -1;
    PsiJavaToken lastFirstLineToken = (PsiJavaToken) elementAtStartLineEnd;
    if (lastFirstLineToken.getTokenType() != JavaTokenType.SEMICOLON)
        return -1;
    if (!(lastFirstLineToken.getParent() instanceof PsiLocalVariable))
        return -1;
    PsiLocalVariable var = (PsiLocalVariable) lastFirstLineToken.getParent();
    if (!(var.getParent() instanceof PsiDeclarationStatement))
        return -1;
    PsiDeclarationStatement decl = (PsiDeclarationStatement) var.getParent();
    if (decl.getDeclaredElements().length > 1)
        return -1;
    //second line.
    if (!(elementAtNextLineStart instanceof PsiJavaToken))
        return -1;
    PsiJavaToken firstNextLineToken = (PsiJavaToken) elementAtNextLineStart;
    if (firstNextLineToken.getTokenType() != JavaTokenType.IDENTIFIER)
        return -1;
    if (!(firstNextLineToken.getParent() instanceof PsiReferenceExpression))
        return -1;
    PsiReferenceExpression ref = (PsiReferenceExpression) firstNextLineToken.getParent();
    PsiElement refResolved = ref.resolve();
    PsiManager psiManager = ref.getManager();
    if (!psiManager.areElementsEquivalent(refResolved, var))
        return -1;
    if (!(ref.getParent() instanceof PsiAssignmentExpression))
        return -1;
    PsiAssignmentExpression assignment = (PsiAssignmentExpression) ref.getParent();
    if (!(assignment.getParent() instanceof PsiExpressionStatement))
        return -1;
    if (ReferencesSearch.search(var, new LocalSearchScope(assignment.getRExpression()), false).findFirst() != null) {
        return -1;
    }
    final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
    final PsiExpression initializerExpression = getInitializerExpression(var, assignment);
    if (initializerExpression == null)
        return -1;
    PsiExpressionStatement statement = (PsiExpressionStatement) assignment.getParent();
    int startOffset = decl.getTextRange().getStartOffset();
    try {
        PsiDeclarationStatement newDecl = factory.createVariableDeclarationStatement(var.getName(), var.getType(), initializerExpression);
        PsiVariable newVar = (PsiVariable) newDecl.getDeclaredElements()[0];
        if (var.getModifierList().getText().length() > 0) {
            PsiUtil.setModifierProperty(newVar, PsiModifier.FINAL, true);
        }
        newVar.getModifierList().replace(var.getModifierList());
        PsiVariable variable = (PsiVariable) newDecl.getDeclaredElements()[0];
        final int offsetBeforeEQ = variable.getNameIdentifier().getTextRange().getEndOffset();
        final int offsetAfterEQ = variable.getInitializer().getTextRange().getStartOffset() + 1;
        newDecl = (PsiDeclarationStatement) CodeStyleManager.getInstance(psiManager).reformatRange(newDecl, offsetBeforeEQ, offsetAfterEQ);
        PsiElement child = statement.getLastChild();
        while (child instanceof PsiComment || child instanceof PsiWhiteSpace) {
            child = child.getPrevSibling();
        }
        if (child != null && child.getNextSibling() != null) {
            newDecl.addRangeBefore(child.getNextSibling(), statement.getLastChild(), null);
        }
        decl.replace(newDecl);
        statement.delete();
        return startOffset + newDecl.getTextRange().getEndOffset() - newDecl.getTextRange().getStartOffset();
    } catch (IncorrectOperationException e) {
        LOG.error(e);
        return -1;
    }
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 45 with LocalSearchScope

use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.

the class MoveInnerProcessor method performRefactoring.

protected void performRefactoring(@NotNull final UsageInfo[] usages) {
    final PsiManager manager = PsiManager.getInstance(myProject);
    final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final RefactoringElementListener elementListener = getTransaction().getElementListener(myInnerClass);
    try {
        PsiField field = null;
        if (myParameterNameOuterClass != null) {
            // pass outer as a parameter
            field = factory.createField(myFieldNameOuterClass, factory.createType(myOuterClass));
            field = addOuterField(field);
            myInnerClass = field.getContainingClass();
            addFieldInitializationToConstructors(myInnerClass, field, myParameterNameOuterClass);
        }
        ChangeContextUtil.encodeContextInfo(myInnerClass, false);
        myInnerClass = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(myInnerClass);
        final MoveInnerOptions moveInnerOptions = new MoveInnerOptions(myInnerClass, myOuterClass, myTargetContainer, myNewClassName);
        final MoveInnerHandler handler = MoveInnerHandler.EP_NAME.forLanguage(myInnerClass.getLanguage());
        final PsiClass newClass;
        try {
            newClass = handler.copyClass(moveInnerOptions);
        } catch (IncorrectOperationException e) {
            RefactoringUIUtil.processIncorrectOperation(myProject, e);
            return;
        }
        // replace references in a new class to old inner class with references to itself
        for (PsiReference ref : ReferencesSearch.search(myInnerClass, new LocalSearchScope(newClass), true)) {
            PsiElement element = ref.getElement();
            if (element.getParent() instanceof PsiJavaCodeReferenceElement) {
                PsiJavaCodeReferenceElement parentRef = (PsiJavaCodeReferenceElement) element.getParent();
                PsiElement parentRefElement = parentRef.resolve();
                if (parentRefElement instanceof PsiClass) {
                    // reference to inner class inside our inner
                    final PsiReferenceList referenceList = PsiTreeUtil.getTopmostParentOfType(parentRef, PsiReferenceList.class);
                    if (referenceList == null || referenceList.getParent() != newClass) {
                        parentRef.getQualifier().delete();
                        continue;
                    }
                }
            }
            ref.bindToElement(newClass);
        }
        List<PsiReference> referencesToRebind = new ArrayList<>();
        for (UsageInfo usage : usages) {
            if (usage.isNonCodeUsage)
                continue;
            PsiElement refElement = usage.getElement();
            PsiReference[] references = refElement.getReferences();
            for (PsiReference reference : references) {
                if (reference.isReferenceTo(myInnerClass)) {
                    referencesToRebind.add(reference);
                }
            }
        }
        myInnerClass.delete();
        // correct references in usages
        for (UsageInfo usage : usages) {
            // should pass outer as parameter
            if (usage.isNonCodeUsage || myParameterNameOuterClass == null)
                continue;
            MoveInnerClassUsagesHandler usagesHandler = MoveInnerClassUsagesHandler.EP_NAME.forLanguage(usage.getElement().getLanguage());
            if (usagesHandler != null) {
                usagesHandler.correctInnerClassUsage(usage, myOuterClass);
            }
        }
        for (PsiReference reference : referencesToRebind) {
            reference.bindToElement(newClass);
        }
        for (UsageInfo usage : usages) {
            final PsiElement element = usage.getElement();
            final PsiElement parent = element != null ? element.getParent() : null;
            if (parent instanceof PsiNewExpression) {
                final PsiMethod resolveConstructor = ((PsiNewExpression) parent).resolveConstructor();
                for (PsiMethod method : newClass.getConstructors()) {
                    if (resolveConstructor == method) {
                        final PsiElement place = usage.getElement();
                        if (place != null) {
                            VisibilityUtil.escalateVisibility(method, place);
                        }
                        break;
                    }
                }
            }
        }
        if (field != null) {
            final PsiExpression paramAccessExpression = factory.createExpressionFromText(myParameterNameOuterClass, null);
            for (final PsiMethod constructor : newClass.getConstructors()) {
                final PsiStatement[] statements = constructor.getBody().getStatements();
                if (statements.length > 0) {
                    if (statements[0] instanceof PsiExpressionStatement) {
                        PsiExpression expression = ((PsiExpressionStatement) statements[0]).getExpression();
                        if (expression instanceof PsiMethodCallExpression) {
                            @NonNls String text = ((PsiMethodCallExpression) expression).getMethodExpression().getText();
                            if ("this".equals(text) || "super".equals(text)) {
                                ChangeContextUtil.decodeContextInfo(expression, myOuterClass, paramAccessExpression);
                            }
                        }
                    }
                }
            }
            PsiExpression accessExpression = factory.createExpressionFromText(myFieldNameOuterClass, null);
            ChangeContextUtil.decodeContextInfo(newClass, myOuterClass, accessExpression);
        } else {
            ChangeContextUtil.decodeContextInfo(newClass, null, null);
        }
        if (myOpenInEditor) {
            EditorHelper.openInEditor(newClass);
        }
        if (myMoveCallback != null) {
            myMoveCallback.refactoringCompleted();
        }
        elementListener.elementMoved(newClass);
        List<NonCodeUsageInfo> nonCodeUsages = new ArrayList<>();
        for (UsageInfo usage : usages) {
            if (usage instanceof NonCodeUsageInfo) {
                nonCodeUsages.add((NonCodeUsageInfo) usage);
            }
        }
        myNonCodeUsages = nonCodeUsages.toArray(new NonCodeUsageInfo[nonCodeUsages.size()]);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
Also used : NonCodeUsageInfo(com.intellij.refactoring.util.NonCodeUsageInfo) UsageInfo(com.intellij.usageView.UsageInfo) NonCodeUsageInfo(com.intellij.refactoring.util.NonCodeUsageInfo) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) NonNls(org.jetbrains.annotations.NonNls) RefactoringElementListener(com.intellij.refactoring.listeners.RefactoringElementListener) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Aggregations

LocalSearchScope (com.intellij.psi.search.LocalSearchScope)113 SearchScope (com.intellij.psi.search.SearchScope)31 NotNull (org.jetbrains.annotations.NotNull)22 PsiElement (com.intellij.psi.PsiElement)19 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)19 Project (com.intellij.openapi.project.Project)18 Nullable (org.jetbrains.annotations.Nullable)13 ArrayList (java.util.ArrayList)12 VirtualFile (com.intellij.openapi.vfs.VirtualFile)11 UsageInfo (com.intellij.usageView.UsageInfo)11 TextRange (com.intellij.openapi.util.TextRange)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)9 com.intellij.psi (com.intellij.psi)8 PsiReference (com.intellij.psi.PsiReference)8 PsiFile (com.intellij.psi.PsiFile)7 ReferencesSearch (com.intellij.psi.search.searches.ReferencesSearch)7 AnalysisScope (com.intellij.analysis.AnalysisScope)6 Processor (com.intellij.util.Processor)6 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)5 Ref (com.intellij.openapi.util.Ref)4