use of com.intellij.psi.search.SearchScope in project android 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();
// Running a single inspection that's not lint? If so don't run lint
if (localTools.isEmpty() && globalTools.size() == 1) {
Tools tool = globalTools.get(0);
if (!tool.getShortName().startsWith(LINT_INSPECTION_PREFIX)) {
return;
}
}
if (!ProjectFacetManager.getInstance(project).hasFacets(AndroidFacet.ID)) {
return;
}
List<Issue> issues = AndroidLintExternalAnnotator.getIssuesFromInspections(project, null);
if (issues.size() == 0) {
return;
}
// If running a single check by name, turn it on if it's off by default.
if (localTools.isEmpty() && globalTools.size() == 1) {
Tools tool = globalTools.get(0);
String id = tool.getShortName().substring(LINT_INSPECTION_PREFIX.length());
Issue issue = new LintIdeIssueRegistry().getIssue(id);
if (issue != null && !issue.isEnabledByDefault()) {
issues = Collections.singletonList(issue);
issue.setEnabledByDefault(true);
// And turn it back off again in cleanup
myEnabledIssue = issue;
}
}
final Map<Issue, Map<File, List<ProblemData>>> problemMap = new HashMap<>();
AnalysisScope scope = context.getRefManager().getScope();
if (scope == null) {
scope = AndroidLintLintBaselineInspection.ourRerunScope;
if (scope == null) {
return;
}
}
final LintIdeClient client = LintIdeClient.forBatch(project, problemMap, scope, issues);
final LintDriver lint = new LintDriver(new LintIdeIssueRegistry(), client);
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
ProgressWrapper.unwrap(indicator).setText("Running Android Lint");
}
EnumSet<Scope> lintScope;
//noinspection ConstantConditions
if (!LintIdeProject.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 = ReadAction.compute(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(() -> {
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) {
if (virtualFile instanceof StringsVirtualFile) {
StringsVirtualFile f = (StringsVirtualFile) virtualFile;
if (!modules.contains(f.getFacet().getModule())) {
modules.add(f.getFacet().getModule());
}
} else {
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 LintIdeRequest(client, project, files, modules, false);
request.setScope(lintScope);
// Baseline analysis?
myBaseline = null;
for (Module module : modules) {
AndroidModuleModel model = AndroidModuleModel.get(module);
if (model != null) {
GradleVersion version = model.getModelVersion();
if (version != null && version.isAtLeast(2, 3, 0, "beta", 2, true)) {
LintOptions options = model.getAndroidProject().getLintOptions();
try {
File baselineFile = options.getBaselineFile();
if (baselineFile != null && !AndroidLintLintBaselineInspection.ourSkipBaselineNextRun) {
if (!baselineFile.isAbsolute()) {
String path = module.getProject().getBasePath();
if (path != null) {
baselineFile = new File(FileUtil.toSystemDependentName(path), baselineFile.getPath());
}
}
myBaseline = new LintBaseline(client, baselineFile);
lint.setBaseline(myBaseline);
if (!baselineFile.isFile()) {
myBaseline.setWriteOnClose(true);
} else if (AndroidLintLintBaselineInspection.ourUpdateBaselineNextRun) {
myBaseline.setRemoveFixed(true);
myBaseline.setWriteOnClose(true);
}
}
} catch (Throwable unsupported) {
// During 2.3 development some builds may have this method, others may not
}
}
break;
}
}
lint.analyze(request);
AndroidLintLintBaselineInspection.clearNextRunState();
myResults = problemMap;
}
use of com.intellij.psi.search.SearchScope in project kotlin by JetBrains.
the class MoveDeclarationsOutHelper method move.
public static PsiElement[] move(@NotNull PsiElement container, @NotNull PsiElement[] statements, boolean generateDefaultInitializers) {
if (statements.length == 0) {
return statements;
}
Project project = container.getProject();
List<PsiElement> resultStatements = new ArrayList<PsiElement>();
List<KtProperty> propertiesDeclarations = new ArrayList<KtProperty>();
// Dummy element to add new declarations at the beginning
KtPsiFactory psiFactory = KtPsiFactoryKt.KtPsiFactory(project);
PsiElement dummyFirstStatement = container.addBefore(psiFactory.createExpression("dummyStatement"), statements[0]);
try {
SearchScope scope = new LocalSearchScope(container);
int lastStatementOffset = statements[statements.length - 1].getTextRange().getEndOffset();
for (PsiElement statement : statements) {
if (needToDeclareOut(statement, lastStatementOffset, scope)) {
if (statement instanceof KtProperty && ((KtProperty) statement).getInitializer() != null) {
KtProperty property = (KtProperty) statement;
KtProperty declaration = createVariableDeclaration(property, generateDefaultInitializers);
declaration = (KtProperty) container.addBefore(declaration, dummyFirstStatement);
propertiesDeclarations.add(declaration);
container.addAfter(psiFactory.createNewLine(), declaration);
KtBinaryExpression assignment = createVariableAssignment(property);
resultStatements.add(property.replace(assignment));
} else {
PsiElement newStatement = container.addBefore(statement, dummyFirstStatement);
container.addAfter(psiFactory.createNewLine(), newStatement);
container.deleteChildRange(statement, statement);
}
} else {
resultStatements.add(statement);
}
}
} finally {
dummyFirstStatement.delete();
}
ShortenReferences.DEFAULT.process(propertiesDeclarations);
return PsiUtilCore.toPsiElementArray(resultStatements);
}
use of com.intellij.psi.search.SearchScope in project intellij-plugins by JetBrains.
the class CucumberUtil method findPossibleGherkinElementUsages.
/**
* Passes to {@link com.intellij.psi.search.TextOccurenceProcessor} all elements in gherkin files that <em>may</em> have reference to
* provided argument. I.e: calling this function for string literal "(.+)foo" would find step "Given I am foo".
* To extract search text, {@link #getTheBiggestWordToSearchByIndex(String)} is used.
*
* @param stepDefinitionElement step defining element to search refs for.
* @param regexp regexp step should match
* @param processor each text occurence would be reported here
* @param effectiveSearchScope search scope
* @return whether reference was found and passed to processor
* @see #findGherkinReferencesToElement(com.intellij.psi.PsiElement, String, com.intellij.util.Processor, com.intellij.psi.search.SearchScope)
*/
public static boolean findPossibleGherkinElementUsages(@NotNull final PsiElement stepDefinitionElement, @NotNull final String regexp, @NotNull final TextOccurenceProcessor processor, @NotNull final SearchScope effectiveSearchScope) {
final String word = getTheBiggestWordToSearchByIndex(regexp);
if (StringUtil.isEmptyOrSpaces(word)) {
return true;
}
final SearchScope searchScope = CucumberStepSearchUtil.restrictScopeToGherkinFiles(() -> effectiveSearchScope);
final short context = (short) (UsageSearchContext.IN_STRINGS | UsageSearchContext.IN_CODE);
final PsiSearchHelper instance = SERVICE.getInstance(stepDefinitionElement.getProject());
return instance.processElementsWithWord(processor, searchScope, word, context, true);
}
use of com.intellij.psi.search.SearchScope in project intellij-community by JetBrains.
the class ExtractParameterAsLocalVariableFix method doFix.
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
if (!(element instanceof PsiExpression)) {
return;
}
final PsiExpression expression = ParenthesesUtils.stripParentheses((PsiExpression) element);
if (!(expression instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression parameterReference = (PsiReferenceExpression) expression;
final PsiElement target = parameterReference.resolve();
if (!(target instanceof PsiParameter)) {
return;
}
final PsiParameter parameter = (PsiParameter) target;
final PsiElement declarationScope = parameter.getDeclarationScope();
final PsiElement body;
if (declarationScope instanceof PsiMethod) {
final PsiMethod method = (PsiMethod) declarationScope;
body = method.getBody();
} else if (declarationScope instanceof PsiCatchSection) {
final PsiCatchSection catchSection = (PsiCatchSection) declarationScope;
body = catchSection.getCatchBlock();
} else if (declarationScope instanceof PsiLoopStatement) {
final PsiLoopStatement forStatement = (PsiLoopStatement) declarationScope;
final PsiStatement forBody = forStatement.getBody();
if (forBody instanceof PsiBlockStatement) {
final PsiBlockStatement blockStatement = (PsiBlockStatement) forBody;
body = blockStatement.getCodeBlock();
} else {
body = forBody;
}
} else if (declarationScope instanceof PsiLambdaExpression) {
final PsiLambdaExpression lambdaExpression = (PsiLambdaExpression) declarationScope;
body = lambdaExpression.getBody();
} else {
return;
}
if (body == null) {
return;
}
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
final String parameterName = parameterReference.getText();
final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
final String variableName = javaCodeStyleManager.suggestUniqueVariableName(parameterName, parameterReference, true);
final SearchScope scope = parameter.getUseScope();
final Query<PsiReference> search = ReferencesSearch.search(parameter, scope);
final PsiReference reference = search.findFirst();
if (reference == null) {
return;
}
final PsiElement referenceElement = reference.getElement();
if (!(referenceElement instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression firstReference = (PsiReferenceExpression) referenceElement;
final PsiElement[] children = body.getChildren();
final int startIndex;
final int endIndex;
if (body instanceof PsiCodeBlock) {
startIndex = 1;
endIndex = children.length - 1;
} else {
startIndex = 0;
endIndex = children.length;
}
boolean newDeclarationCreated = false;
final StringBuilder buffer = new StringBuilder();
for (int i = startIndex; i < endIndex; i++) {
final PsiElement child = children[i];
newDeclarationCreated |= replaceVariableName(child, firstReference, variableName, parameterName, buffer);
}
if (body instanceof PsiExpression) {
// expression lambda
buffer.insert(0, "return ");
buffer.append(';');
}
final String replacementText;
if (newDeclarationCreated) {
replacementText = "{" + buffer + '}';
} else {
final PsiType type = parameter.getType();
final String className = type.getCanonicalText();
replacementText = '{' + className + ' ' + variableName + " = " + parameterName + ';' + buffer + '}';
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
final PsiCodeBlock block = elementFactory.createCodeBlockFromText(replacementText, declarationScope);
body.replace(block);
codeStyleManager.reformat(declarationScope);
}
use of com.intellij.psi.search.SearchScope in project intellij-community by JetBrains.
the class StaticInheritanceFix method doFix.
@Override
public void doFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) descriptor.getPsiElement();
final PsiClass iface = (PsiClass) referenceElement.resolve();
assert iface != null;
final PsiField[] allFields = iface.getAllFields();
final PsiClass implementingClass = ClassUtils.getContainingClass(referenceElement);
final PsiManager manager = referenceElement.getManager();
assert implementingClass != null;
final PsiFile file = implementingClass.getContainingFile();
ProgressManager.getInstance().run(new Task.Modal(project, "Replacing usages of " + iface.getName(), false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
for (final PsiField field : allFields) {
SearchScope scope = ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
@Override
public SearchScope compute() {
return implementingClass.getUseScope();
}
});
final Query<PsiReference> search = ReferencesSearch.search(field, scope, false);
for (PsiReference reference : search) {
if (!(reference instanceof PsiReferenceExpression)) {
continue;
}
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) reference;
if (!myReplaceInWholeProject) {
boolean isInheritor = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
boolean isInheritor = false;
PsiClass aClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
while (aClass != null) {
isInheritor = InheritanceUtil.isInheritorOrSelf(aClass, implementingClass, true);
if (isInheritor)
break;
aClass = PsiTreeUtil.getParentOfType(aClass, PsiClass.class);
}
return isInheritor;
}
});
if (!isInheritor)
continue;
}
final Runnable runnable = () -> {
if (!FileModificationService.getInstance().preparePsiElementsForWrite(referenceExpression)) {
return;
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final PsiReferenceExpression qualified = (PsiReferenceExpression) elementFactory.createExpressionFromText("xxx." + referenceExpression.getText(), referenceExpression);
final PsiReferenceExpression newReference = (PsiReferenceExpression) referenceExpression.replace(qualified);
final PsiReferenceExpression qualifier = (PsiReferenceExpression) newReference.getQualifierExpression();
assert qualifier != null : DebugUtil.psiToString(newReference, false);
final PsiClass containingClass = field.getContainingClass();
qualifier.bindToElement(containingClass);
};
invokeWriteAction(runnable, file);
}
}
final Runnable runnable = () -> {
PsiClassType classType = JavaPsiFacade.getInstance(project).getElementFactory().createType(iface);
IntentionAction fix = QuickFixFactory.getInstance().createExtendsListFix(implementingClass, classType, false);
fix.invoke(project, null, file);
};
invokeWriteAction(runnable, file);
}
});
}
Aggregations