use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class ConvertToInstanceMethodProcessor method prepareTypeParameterReplacement.
private void prepareTypeParameterReplacement() throws IncorrectOperationException {
if (myTypeParameterReplacements == null)
return;
final Collection<PsiTypeParameter> typeParameters = myTypeParameterReplacements.keySet();
for (final PsiTypeParameter parameter : typeParameters) {
for (final PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(myMethod), false)) {
if (reference.getElement() instanceof PsiJavaCodeReferenceElement) {
reference.getElement().putCopyableUserData(BIND_TO_TYPE_PARAMETER, myTypeParameterReplacements.get(parameter));
}
}
}
final Set<PsiTypeParameter> methodTypeParameters = myTypeParameterReplacements.keySet();
for (final PsiTypeParameter methodTypeParameter : methodTypeParameters) {
methodTypeParameter.delete();
}
}
use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class ExtractMethodProcessor method doExtract.
public void doExtract() throws IncorrectOperationException {
PsiMethod newMethod = generateEmptyMethod();
myExpression = myInputVariables.replaceWrappedReferences(myElements, myExpression);
renameInputVariables();
LOG.assertTrue(myElements[0].isValid());
PsiCodeBlock body = newMethod.getBody();
myMethodCall = generateMethodCall(null, true);
LOG.assertTrue(myElements[0].isValid());
final PsiStatement exitStatementCopy = prepareMethodBody(newMethod, true);
if (myExpression == null) {
if (myNeedChangeContext && isNeedToChangeCallContext()) {
for (PsiElement element : myElements) {
ChangeContextUtil.encodeContextInfo(element, false);
}
}
if (myNullConditionalCheck) {
final String varName = myOutputVariable.getName();
if (isDeclaredInside(myOutputVariable)) {
declareVariableAtMethodCallLocation(varName);
} else {
PsiExpressionStatement assignmentExpression = (PsiExpressionStatement) myElementFactory.createStatementFromText(varName + "=x;", null);
assignmentExpression = (PsiExpressionStatement) addToMethodCallLocation(assignmentExpression);
myMethodCall = (PsiMethodCallExpression) ((PsiAssignmentExpression) assignmentExpression.getExpression()).getRExpression().replace(myMethodCall);
}
declareNecessaryVariablesAfterCall(myOutputVariable);
PsiIfStatement ifStatement;
if (myHasReturnStatementOutput) {
ifStatement = (PsiIfStatement) myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
} else if (myGenerateConditionalExit) {
if (myFirstExitStatementCopy instanceof PsiReturnStatement && ((PsiReturnStatement) myFirstExitStatementCopy).getReturnValue() != null) {
ifStatement = (PsiIfStatement) myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
} else {
ifStatement = (PsiIfStatement) myElementFactory.createStatementFromText("if (" + varName + "==null) " + myFirstExitStatementCopy.getText(), null);
}
} else {
ifStatement = (PsiIfStatement) myElementFactory.createStatementFromText("if (" + varName + "==null) return;", null);
}
ifStatement = (PsiIfStatement) addToMethodCallLocation(ifStatement);
CodeStyleManager.getInstance(myProject).reformat(ifStatement);
} else if (myNotNullConditionalCheck) {
String varName = myOutputVariable != null ? myOutputVariable.getName() : "x";
varName = declareVariableAtMethodCallLocation(varName, myReturnType instanceof PsiPrimitiveType ? ((PsiPrimitiveType) myReturnType).getBoxedType(myCodeFragmentMember) : myReturnType);
addToMethodCallLocation(myElementFactory.createStatementFromText("if (" + varName + " != null) return " + varName + ";", null));
} else if (myGenerateConditionalExit) {
PsiIfStatement ifStatement = (PsiIfStatement) myElementFactory.createStatementFromText("if (a) b;", null);
ifStatement = (PsiIfStatement) addToMethodCallLocation(ifStatement);
myMethodCall = (PsiMethodCallExpression) ifStatement.getCondition().replace(myMethodCall);
myFirstExitStatementCopy = (PsiStatement) ifStatement.getThenBranch().replace(myFirstExitStatementCopy);
CodeStyleManager.getInstance(myProject).reformat(ifStatement);
} else if (myOutputVariable != null || isArtificialOutputUsed()) {
boolean toDeclare = isArtificialOutputUsed() ? !(myArtificialOutputVariable instanceof PsiField) : isDeclaredInside(myOutputVariable);
String name = isArtificialOutputUsed() ? myArtificialOutputVariable.getName() : myOutputVariable.getName();
if (!toDeclare) {
PsiExpressionStatement statement = (PsiExpressionStatement) myElementFactory.createStatementFromText(name + "=x;", null);
statement = (PsiExpressionStatement) myStyleManager.reformat(statement);
statement = (PsiExpressionStatement) addToMethodCallLocation(statement);
PsiAssignmentExpression assignment = (PsiAssignmentExpression) statement.getExpression();
myMethodCall = (PsiMethodCallExpression) assignment.getRExpression().replace(myMethodCall);
} else {
declareVariableAtMethodCallLocation(name);
}
} else if (myHasReturnStatementOutput) {
PsiStatement statement = myElementFactory.createStatementFromText("return x;", null);
statement = (PsiStatement) addToMethodCallLocation(statement);
myMethodCall = (PsiMethodCallExpression) ((PsiReturnStatement) statement).getReturnValue().replace(myMethodCall);
} else {
PsiStatement statement = myElementFactory.createStatementFromText("x();", null);
statement = (PsiStatement) addToMethodCallLocation(statement);
myMethodCall = (PsiMethodCallExpression) ((PsiExpressionStatement) statement).getExpression().replace(myMethodCall);
}
if (myHasReturnStatement && !myHasReturnStatementOutput && !hasNormalExit()) {
PsiStatement statement = myElementFactory.createStatementFromText("return;", null);
addToMethodCallLocation(statement);
} else if (!myGenerateConditionalExit && exitStatementCopy != null) {
addToMethodCallLocation(exitStatementCopy);
}
if (!myNullConditionalCheck && !myNotNullConditionalCheck) {
declareNecessaryVariablesAfterCall(myOutputVariable);
}
deleteExtracted();
} else {
PsiExpression expression2Replace = myExpression;
if (myExpression instanceof PsiAssignmentExpression) {
expression2Replace = ((PsiAssignmentExpression) myExpression).getRExpression();
} else if (myExpression instanceof PsiPostfixExpression || myExpression instanceof PsiPrefixExpression) {
final IElementType elementType = myExpression instanceof PsiPostfixExpression ? ((PsiPostfixExpression) myExpression).getOperationTokenType() : ((PsiPrefixExpression) myExpression).getOperationTokenType();
if (elementType == JavaTokenType.PLUSPLUS || elementType == JavaTokenType.MINUSMINUS) {
PsiExpression operand = myExpression instanceof PsiPostfixExpression ? ((PsiPostfixExpression) myExpression).getOperand() : ((PsiPrefixExpression) myExpression).getOperand();
expression2Replace = ((PsiBinaryExpression) myExpression.replace(myElementFactory.createExpressionFromText(operand.getText() + " + x", operand))).getROperand();
}
}
myExpression = (PsiExpression) IntroduceVariableBase.replace(expression2Replace, myMethodCall, myProject);
myMethodCall = PsiTreeUtil.getParentOfType(myExpression.findElementAt(myExpression.getText().indexOf(myMethodCall.getText())), PsiMethodCallExpression.class);
declareNecessaryVariablesAfterCall(myOutputVariable);
}
if (myAnchor instanceof PsiField) {
((PsiField) myAnchor).normalizeDeclaration();
}
adjustFinalParameters(newMethod);
int i = 0;
for (VariableData data : myVariableDatum) {
if (!data.passAsParameter)
continue;
final PsiParameter psiParameter = newMethod.getParameterList().getParameters()[i++];
final PsiType paramType = psiParameter.getType();
for (PsiReference reference : ReferencesSearch.search(psiParameter, new LocalSearchScope(body))) {
final PsiElement element = reference.getElement();
if (element != null) {
final PsiElement parent = element.getParent();
if (parent instanceof PsiTypeCastExpression) {
final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) parent;
final PsiTypeElement castType = typeCastExpression.getCastType();
if (castType != null && Comparing.equal(castType.getType(), paramType)) {
RedundantCastUtil.removeCast(typeCastExpression);
}
}
}
}
}
if (myNullness != null && PsiUtil.resolveClassInType(newMethod.getReturnType()) != null && PropertiesComponent.getInstance(myProject).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, true)) {
final NullableNotNullManager notNullManager = NullableNotNullManager.getInstance(myProject);
AddNullableNotNullAnnotationFix annotationFix;
switch(myNullness) {
case NOT_NULL:
annotationFix = new AddNullableNotNullAnnotationFix(notNullManager.getDefaultNotNull(), newMethod);
break;
case NULLABLE:
annotationFix = new AddNullableNotNullAnnotationFix(notNullManager.getDefaultNullable(), newMethod);
break;
default:
annotationFix = null;
}
if (annotationFix != null) {
annotationFix.invoke(myProject, myTargetClass.getContainingFile(), newMethod, newMethod);
}
}
myExtractedMethod = addExtractedMethod(newMethod);
if (isNeedToChangeCallContext() && myNeedChangeContext) {
ChangeContextUtil.decodeContextInfo(myExtractedMethod, myTargetClass, RefactoringChangeUtil.createThisExpression(myManager, null));
if (myMethodCall.resolveMethod() != myExtractedMethod) {
final PsiReferenceExpression methodExpression = myMethodCall.getMethodExpression();
RefactoringChangeUtil.qualifyReference(methodExpression, myExtractedMethod, PsiUtil.getEnclosingStaticElement(methodExpression, myTargetClass) != null ? myTargetClass : null);
}
}
}
use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class JavaClassInheritorsSearcher method processInheritors.
private static boolean processInheritors(@NotNull final ClassInheritorsSearch.SearchParameters parameters, @NotNull final Processor<PsiClass> consumer) {
@NotNull final PsiClass baseClass = parameters.getClassToProcess();
if (baseClass instanceof PsiAnonymousClass || isFinal(baseClass))
return true;
final SearchScope searchScope = parameters.getScope();
Project project = PsiUtilCore.getProjectInReadAction(baseClass);
if (isJavaLangObject(baseClass)) {
return AllClassesSearch.search(searchScope, project, parameters.getNameCondition()).forEach(aClass -> {
ProgressManager.checkCanceled();
return isJavaLangObject(aClass) || consumer.process(aClass);
});
}
if (searchScope instanceof LocalSearchScope) {
return processLocalScope(project, parameters, (LocalSearchScope) searchScope, baseClass, consumer);
}
Iterable<PsiClass> cached = getOrComputeSubClasses(project, baseClass, searchScope);
for (final PsiClass subClass : cached) {
ProgressManager.checkCanceled();
if (subClass instanceof PsiAnonymousClass && !parameters.isIncludeAnonymous()) {
continue;
}
if (ReadAction.compute(() -> checkCandidate(subClass, parameters) && !consumer.process(subClass))) {
return false;
}
}
return true;
}
use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class JavaOverridingMethodsSearcher method execute.
@Override
public boolean execute(@NotNull final OverridingMethodsSearch.SearchParameters parameters, @NotNull final Processor<PsiMethod> consumer) {
final PsiMethod method = parameters.getMethod();
Project project = ReadAction.compute(method::getProject);
final SearchScope searchScope = parameters.getScope();
if (searchScope instanceof LocalSearchScope) {
return processLocalScope((LocalSearchScope) searchScope, method, project, consumer);
}
Iterable<PsiMethod> cached = HighlightingCaches.getInstance(project).OVERRIDING_METHODS.get(method);
if (cached == null) {
cached = compute(method, project);
// for non-physical elements ignore the cache completely because non-physical elements created so often/unpredictably so I can't figure out when to clear caches in this case
if (ReadAction.compute(method::isPhysical)) {
HighlightingCaches.getInstance(project).OVERRIDING_METHODS.put(method, cached);
}
}
for (final PsiMethod subMethod : cached) {
ProgressManager.checkCanceled();
if (!ReadAction.compute(() -> PsiSearchScopeUtil.isInScope(searchScope, subMethod))) {
continue;
}
if (!consumer.process(subMethod) || !parameters.isCheckDeep()) {
return false;
}
}
return true;
}
use of com.intellij.psi.search.LocalSearchScope in project kotlin by JetBrains.
the class AndroidLintGlobalInspectionContext method performPreRunActivities.
@Override
public void performPreRunActivities(@NotNull List<Tools> globalTools, @NotNull List<Tools> localTools, @NotNull final GlobalInspectionContext context) {
final Project project = context.getProject();
if (!ProjectFacetManager.getInstance(project).hasFacets(AndroidFacet.ID)) {
return;
}
final List<Issue> issues = AndroidLintExternalAnnotator.getIssuesFromInspections(project, null);
if (issues.size() == 0) {
return;
}
final Map<Issue, Map<File, List<ProblemData>>> problemMap = new HashMap<Issue, Map<File, List<ProblemData>>>();
final AnalysisScope scope = context.getRefManager().getScope();
if (scope == null) {
return;
}
final IntellijLintClient client = IntellijLintClient.forBatch(project, problemMap, scope, issues);
final LintDriver lint = new LintDriver(new IntellijLintIssueRegistry(), client);
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
ProgressWrapper.unwrap(indicator).setText("Running Android Lint");
}
EnumSet<Scope> lintScope;
//noinspection ConstantConditions
if (!IntellijLintProject.SUPPORT_CLASS_FILES) {
lintScope = EnumSet.copyOf(Scope.ALL);
// Can't run class file based checks
lintScope.remove(Scope.CLASS_FILE);
lintScope.remove(Scope.ALL_CLASS_FILES);
lintScope.remove(Scope.JAVA_LIBRARIES);
} else {
lintScope = Scope.ALL;
}
List<VirtualFile> files = null;
final List<Module> modules = Lists.newArrayList();
int scopeType = scope.getScopeType();
switch(scopeType) {
case AnalysisScope.MODULE:
{
SearchScope searchScope = scope.toSearchScope();
if (searchScope instanceof ModuleWithDependenciesScope) {
ModuleWithDependenciesScope s = (ModuleWithDependenciesScope) searchScope;
if (!s.isSearchInLibraries()) {
modules.add(s.getModule());
}
}
break;
}
case AnalysisScope.FILE:
case AnalysisScope.VIRTUAL_FILES:
case AnalysisScope.UNCOMMITTED_FILES:
{
files = Lists.newArrayList();
SearchScope searchScope = scope.toSearchScope();
if (searchScope instanceof LocalSearchScope) {
final LocalSearchScope localSearchScope = (LocalSearchScope) searchScope;
final PsiElement[] elements = localSearchScope.getScope();
final List<VirtualFile> finalFiles = files;
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (PsiElement element : elements) {
if (element instanceof PsiFile) {
// should be the case since scope type is FILE
Module module = ModuleUtilCore.findModuleForPsiElement(element);
if (module != null && !modules.contains(module)) {
modules.add(module);
}
VirtualFile virtualFile = ((PsiFile) element).getVirtualFile();
if (virtualFile != null) {
finalFiles.add(virtualFile);
}
}
}
}
});
} else {
final List<VirtualFile> finalList = files;
scope.accept(new PsiElementVisitor() {
@Override
public void visitFile(PsiFile file) {
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
finalList.add(virtualFile);
}
}
});
}
if (files.isEmpty()) {
files = null;
} else {
// Lint will compute it lazily based on actual files in the request
lintScope = null;
}
break;
}
case AnalysisScope.PROJECT:
{
modules.addAll(Arrays.asList(ModuleManager.getInstance(project).getModules()));
break;
}
case AnalysisScope.CUSTOM:
case AnalysisScope.MODULES:
case AnalysisScope.DIRECTORY:
{
// Handled by the getNarrowedComplementaryScope case below
break;
}
case AnalysisScope.INVALID:
break;
default:
Logger.getInstance(this.getClass()).warn("Unexpected inspection scope " + scope + ", " + scopeType);
}
if (modules.isEmpty()) {
for (Module module : ModuleManager.getInstance(project).getModules()) {
if (scope.containsModule(module)) {
modules.add(module);
}
}
if (modules.isEmpty() && files != null) {
for (VirtualFile file : files) {
Module module = ModuleUtilCore.findModuleForFile(file, project);
if (module != null && !modules.contains(module)) {
modules.add(module);
}
}
}
if (modules.isEmpty()) {
AnalysisScope narrowed = scope.getNarrowedComplementaryScope(project);
for (Module module : ModuleManager.getInstance(project).getModules()) {
if (narrowed.containsModule(module)) {
modules.add(module);
}
}
}
}
LintRequest request = new IntellijLintRequest(client, project, files, modules, false);
request.setScope(lintScope);
lint.analyze(request);
myResults = problemMap;
}
Aggregations