use of com.intellij.psi.PsiElementVisitor in project intellij-community by JetBrains.
the class GrUnnecessaryPublicModifierInspection method buildVisitor.
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new PsiElementVisitor() {
@Override
public void visitElement(PsiElement modifier) {
if (modifier.getNode().getElementType() != GroovyTokenTypes.kPUBLIC)
return;
PsiElement list = modifier.getParent();
if (!(list instanceof GrModifierList))
return;
PsiElement parent = list.getParent();
// It may be put there explicitly to prevent getter/setter generation.
if (parent instanceof GrVariableDeclaration)
return;
holder.registerProblem(modifier, GroovyInspectionBundle.message("unnecessary.modifier.description", PsiModifier.PUBLIC), ProblemHighlightType.LIKE_UNUSED_SYMBOL, FIX);
}
};
}
use of com.intellij.psi.PsiElementVisitor in project intellij-community by JetBrains.
the class InconsistentLineSeparatorsInspection method buildVisitor.
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new PsiElementVisitor() {
@Override
public void visitFile(PsiFile file) {
if (!file.getLanguage().equals(file.getViewProvider().getBaseLanguage())) {
// We want to process a virtual file once than, hence, ignore all non-base psi files.
return;
}
final Project project = holder.getProject();
final String projectLineSeparator = FileDocumentManager.getInstance().getLineSeparator(null, project);
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null || !AbstractConvertLineSeparatorsAction.shouldProcess(virtualFile, project)) {
return;
}
final String curLineSeparator = LoadTextUtil.detectLineSeparator(virtualFile, true);
if (curLineSeparator != null && !curLineSeparator.equals(projectLineSeparator)) {
holder.registerProblem(file, "Line separators in the current file (" + StringUtil.escapeStringCharacters(curLineSeparator) + ") " + "differ from the project defaults (" + StringUtil.escapeStringCharacters(projectLineSeparator) + ")", SET_PROJECT_LINE_SEPARATORS);
}
}
};
}
use of com.intellij.psi.PsiElementVisitor 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;
}
use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.
the class ExceptionsAnnotatingAndHandlingInspector method buildVisitor.
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
return new BasePhpElementVisitor() {
@Override
public void visitPhpFinally(@NotNull Finally element) {
PhpLanguageLevel phpVersion = PhpProjectConfigurationFacade.getInstance(holder.getProject()).getLanguageLevel();
if (!phpVersion.hasFeature(PhpLanguageFeature.FINALLY)) {
return;
}
final HashSet<PsiElement> processedRegistry = new HashSet<>();
final HashMap<PhpClass, HashSet<PsiElement>> exceptions = CollectPossibleThrowsUtil.collectNestedAndWorkflowExceptions(element, processedRegistry, holder);
/* report individual statements */
if (exceptions.size() > 0) {
final Set<PsiElement> reportedExpressions = new HashSet<>();
for (final Set<PsiElement> pool : exceptions.values()) {
pool.stream().filter(expression -> !reportedExpressions.contains(expression)).forEach(expression -> {
holder.registerProblem(this.getReportingTarget(expression), messageFinallyExceptions, ProblemHighlightType.GENERIC_ERROR);
reportedExpressions.add(expression);
});
pool.clear();
}
reportedExpressions.clear();
exceptions.clear();
}
/* report try-blocks */
if (processedRegistry.size() > 0) {
processedRegistry.stream().filter(statement -> statement instanceof Try).forEach(statement -> holder.registerProblem(statement.getFirstChild(), messageFinallyExceptions, ProblemHighlightType.GENERIC_ERROR));
processedRegistry.clear();
}
}
@Override
public void visitPhpMethod(@NotNull Method method) {
if (method.isAbstract() || this.isTestContext(method)) {
return;
}
// __toString has magic methods validation, must not raise exceptions
final PsiElement methodName = NamedElementUtil.getNameIdentifier(method);
if (null == methodName || method.getName().equals("__toString")) {
return;
}
/* collect announced cases */
final HashSet<PhpClass> annotatedExceptions = new HashSet<>();
final boolean hasPhpDoc = method.getDocComment() != null;
if (!ThrowsResolveUtil.resolveThrownExceptions(method, annotatedExceptions)) {
return;
}
HashSet<PsiElement> processedRegistry = new HashSet<>();
HashMap<PhpClass, HashSet<PsiElement>> throwsExceptions = CollectPossibleThrowsUtil.collectNestedAndWorkflowExceptions(method, processedRegistry, holder);
processedRegistry.clear();
/* exclude annotated exceptions, identify which has not been thrown */
final Set<PhpClass> annotatedButNotThrownExceptions = new HashSet<>(annotatedExceptions);
/* release bundled expressions */
/* actualize un-thrown exceptions registry */
annotatedExceptions.stream().filter(key -> hasPhpDoc && throwsExceptions.containsKey(key)).forEach(annotated -> {
/* release bundled expressions */
throwsExceptions.get(annotated).clear();
throwsExceptions.remove(annotated);
/* actualize un-thrown exceptions registry */
annotatedButNotThrownExceptions.remove(annotated);
});
/* do reporting now: exceptions annotated, but not thrown */
if (REPORT_NON_THROWN_EXCEPTIONS && annotatedButNotThrownExceptions.size() > 0) {
final List<String> toReport = annotatedButNotThrownExceptions.stream().map(PhpNamedElement::getFQN).collect(Collectors.toList());
final String message = messagePatternUnthrown.replace("%c%", String.join(", ", toReport));
holder.registerProblem(methodName, message, ProblemHighlightType.WEAK_WARNING);
toReport.clear();
}
annotatedButNotThrownExceptions.clear();
/* do reporting now: exceptions thrown but not annotated */
if (throwsExceptions.size() > 0) {
/* deeper analysis needed */
HashMap<PhpClass, HashSet<PsiElement>> unhandledExceptions = new HashMap<>();
if (!annotatedExceptions.isEmpty() && hasPhpDoc) {
/* filter what to report based on annotated exceptions */
for (final PhpClass annotated : annotatedExceptions) {
for (final Map.Entry<PhpClass, HashSet<PsiElement>> throwsExceptionsPair : throwsExceptions.entrySet()) {
final PhpClass thrown = throwsExceptionsPair.getKey();
/* already reported */
if (unhandledExceptions.containsKey(thrown)) {
continue;
}
/* check thrown parents, as annotated not processed here */
final HashSet<PhpClass> thrownVariants = InterfacesExtractUtil.getCrawlInheritanceTree(thrown, true);
if (!thrownVariants.contains(annotated)) {
unhandledExceptions.put(thrown, throwsExceptionsPair.getValue());
throwsExceptions.put(thrown, null);
}
thrownVariants.clear();
}
}
} else {
/* report all, as nothing is annotated */
for (Map.Entry<PhpClass, HashSet<PsiElement>> throwsExceptionsPair : throwsExceptions.entrySet()) {
final PhpClass thrown = throwsExceptionsPair.getKey();
/* already reported */
if (unhandledExceptions.containsKey(thrown)) {
continue;
}
unhandledExceptions.put(thrown, throwsExceptionsPair.getValue());
throwsExceptions.put(thrown, null);
}
}
if (unhandledExceptions.size() > 0) {
for (final Map.Entry<PhpClass, HashSet<PsiElement>> unhandledExceptionsPair : unhandledExceptions.entrySet()) {
final String thrown = unhandledExceptionsPair.getKey().getFQN();
final Set<PsiElement> blamedExpressions = unhandledExceptionsPair.getValue();
if (!configuration.contains(thrown)) {
final String message = messagePattern.replace("%c%", thrown);
for (final PsiElement blame : blamedExpressions) {
final LocalQuickFix fix = hasPhpDoc ? new MissingThrowAnnotationLocalFix(method, thrown) : null;
holder.registerProblem(this.getReportingTarget(blame), message, ProblemHighlightType.WEAK_WARNING, fix);
}
}
blamedExpressions.clear();
}
unhandledExceptions.clear();
}
throwsExceptions.clear();
}
annotatedExceptions.clear();
}
@NotNull
private PsiElement getReportingTarget(@NotNull PsiElement expression) {
PsiElement result = expression;
if (expression instanceof FunctionReference) {
final PsiElement nameNode = (PsiElement) ((FunctionReference) expression).getNameNode();
if (nameNode != null) {
result = nameNode;
}
} else if (expression instanceof PhpThrow) {
final PsiElement subject = ((PhpThrow) expression).getArgument();
if (subject instanceof NewExpression) {
final PsiElement reference = ((NewExpression) subject).getClassReference();
if (reference != null) {
result = reference;
}
}
}
return result;
}
};
}
use of com.intellij.psi.PsiElementVisitor 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;
}
Aggregations