Java Code Examples for com.intellij.codeInspection.InspectionManager

The following are top voted examples for showing how to use com.intellij.codeInspection.InspectionManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 6 votes vote down vote up
private void createProblemDescriptorWithQuickFixes(PsiModifierListOwner owner,
                                                   InspectionManager manager,
                                                   Collection<ProblemDescriptor> problemDescriptors,
                                                   PsiElement element) {
    if (element.isPhysical()) {
        LocalQuickFix[] localQuickFixes = createQuickFixes(owner, isRemoveRedundantAnnotations());
        ProblemDescriptor problemDescriptor = manager.createProblemDescriptor(
                element,
                MISSING_NULLABLE_NONNULL_ANNOTATION,
                localQuickFixes,
                GENERIC_ERROR_OR_WARNING,
                true,
                false);
        problemDescriptors.add(problemDescriptor);
    }
}
 
Example 2
Project: idea-php-dotenv-plugin   File: DuplicateKeyInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
private ProblemsHolder analyzeFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    DotEnvPsiElementsVisitor visitor = new DotEnvPsiElementsVisitor();
    file.acceptChildren(visitor);

    ProblemsHolder problemsHolder = new ProblemsHolder(manager, file, isOnTheFly);

    Map<String, PsiElement> existingKeys = new HashMap<>();
    Set<PsiElement> markedElements = new HashSet<>();
    for(KeyValuePsiElement keyValue : visitor.getCollectedItems()) {
        if(existingKeys.containsKey(keyValue.getKey())) {
            problemsHolder.registerProblem(keyValue.getElement(), "Duplicate key");

            PsiElement markedElement = existingKeys.get(keyValue.getKey());
            if(!markedElements.contains(markedElement)) {
                problemsHolder.registerProblem(markedElement, "Duplicate key");
                markedElements.add(markedElement);
            }
        } else {
            existingKeys.put(keyValue.getKey(), keyValue.getElement());
        }
    }

    return problemsHolder;
}
 
Example 3
Project: intellij-ce-playground   File: ViewOfflineResultsAction.java   Source Code and License 6 votes vote down vote up
@NotNull
public static InspectionResultsView showOfflineView(@NotNull Project project,
                                                    @NotNull Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap,
                                                    @NotNull InspectionProfile inspectionProfile,
                                                    @NotNull String title) {
  final AnalysisScope scope = new AnalysisScope(project);
  final InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(project);
  final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
  context.setExternalProfile(inspectionProfile);
  context.setCurrentScope(scope);
  context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>());
  final InspectionResultsView view = new InspectionResultsView(project, inspectionProfile, scope, context,
                                                               new OfflineInspectionRVContentProvider(resMap, project));
  ((RefManagerImpl)context.getRefManager()).startOfflineView();
  view.update();
  TreeUtil.selectFirstNode(view.getTree());
  context.addView(view, title);
  return view;
}
 
Example 4
Project: intellij-ce-playground   File: BuildoutUnresolvedPartInspection.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
  List<ProblemDescriptor> problems = Lists.newArrayList();
  if (file.getFileType().equals(BuildoutCfgFileType.INSTANCE)) {
    Visitor visitor = new Visitor();
    file.accept(visitor);

    for (BuildoutPartReference ref : visitor.getUnresolvedParts()) {
      ProblemDescriptor d = manager
        .createProblemDescriptor(ref.getElement(), ref.getRangeInElement(), PyBundle.message("buildout.unresolved.part.inspection.msg"),
                                 ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false);
      problems.add(d);
    }
  }
  return problems.toArray(new ProblemDescriptor[problems.size()]);
}
 
Example 5
Project: intellij-ce-playground   File: DomElementsInspection.java   Source Code and License 6 votes vote down vote up
/**
 * not intended to be overridden or called by implementors
 */
@Nullable
protected ProblemDescriptor[] checkDomFile(@NotNull final DomFileElement<T> domFileElement,
                                           @NotNull final InspectionManager manager,
                                           @SuppressWarnings("UnusedParameters") final boolean isOnTheFly) {
  final DomElementAnnotationsManager annotationsManager = DomElementAnnotationsManager.getInstance(manager.getProject());

  final List<DomElementProblemDescriptor> list = annotationsManager.checkFileElement(domFileElement, this, isOnTheFly);
  if (list.isEmpty()) return ProblemDescriptor.EMPTY_ARRAY;

  List<ProblemDescriptor> problems =
    ContainerUtil.concat(list, new Function<DomElementProblemDescriptor, Collection<? extends ProblemDescriptor>>() {
      @Override
      public Collection<ProblemDescriptor> fun(final DomElementProblemDescriptor s) {
        return annotationsManager.createProblemDescriptors(manager, s);
      }
    });
  return problems.toArray(new ProblemDescriptor[problems.size()]);
}
 
Example 6
Project: intellij-ce-playground   File: DomHighlightingLiteTest.java   Source Code and License 6 votes vote down vote up
public void testHighlightStatus_OtherInspections() throws Throwable {
  myElement.setFileDescription(new DomFileDescription<DomElement>(DomElement.class, "a"));
  final MyDomElementsInspection inspection = new MyDomElementsInspection() {

    @Override
    public ProblemDescriptor[] checkFile(@NotNull final PsiFile file, @NotNull final InspectionManager manager,
                                         final boolean isOnTheFly) {
      myAnnotationsManager.appendProblems(myElement, createHolder(), this.getClass());
      return new ProblemDescriptor[0];
    }

    @Override
    public void checkFileElement(final DomFileElement fileElement, final DomElementAnnotationHolder holder) {
    }
  };
  HighlightDisplayKey.register(inspection.getShortName());
  myInspectionProfile.setInspectionTools(new LocalInspectionToolWrapper(inspection));

  myAnnotationsManager.appendProblems(myElement, createHolder(), MockAnnotatingDomInspection.class);
  assertEquals(DomHighlightStatus.ANNOTATORS_FINISHED, myAnnotationsManager.getHighlightStatus(myElement));

  myAnnotationsManager.appendProblems(myElement, createHolder(), inspection.getClass());
  assertEquals(DomHighlightStatus.INSPECTIONS_FINISHED, myAnnotationsManager.getHighlightStatus(myElement));
}
 
Example 7
Project: intellij-ce-playground   File: DomHighlightingLiteTest.java   Source Code and License 6 votes vote down vote up
public void testHighlightStatus_OtherInspections2() throws Throwable {
  myElement.setFileDescription(new DomFileDescription<DomElement>(DomElement.class, "a"));
  final MyDomElementsInspection inspection = new MyDomElementsInspection() {

    @Override
    public ProblemDescriptor[] checkFile(@NotNull final PsiFile file, @NotNull final InspectionManager manager,
                                         final boolean isOnTheFly) {
      myAnnotationsManager.appendProblems(myElement, createHolder(), this.getClass());
      return new ProblemDescriptor[0];
    }

    @Override
    public void checkFileElement(final DomFileElement fileElement, final DomElementAnnotationHolder holder) {
    }
  };
  HighlightDisplayKey.register(inspection.getShortName());
  LocalInspectionToolWrapper toolWrapper = new LocalInspectionToolWrapper(inspection);
  myInspectionProfile.setInspectionTools(toolWrapper);
  myInspectionProfile.setEnabled(toolWrapper, false);

  myAnnotationsManager.appendProblems(myElement, createHolder(), MockAnnotatingDomInspection.class);
  assertEquals(DomHighlightStatus.INSPECTIONS_FINISHED, myAnnotationsManager.getHighlightStatus(myElement));
}
 
Example 8
Project: intellij-ce-playground   File: RegistrationProblemsInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
private ProblemDescriptor[] checkPluginXml(XmlFile xmlFile, InspectionManager manager, boolean isOnTheFly) {
  final XmlDocument document = xmlFile.getDocument();
  if (document == null) {
    return null;
  }

  final XmlTag rootTag = document.getRootTag();
  assert rootTag != null;

  final RegistrationChecker checker = new RegistrationChecker(manager, xmlFile, isOnTheFly);

  DescriptorUtil.processComponents(rootTag, checker);

  DescriptorUtil.processActions(rootTag, checker);

  return checker.getProblems();
}
 
Example 9
Project: intellij-ce-playground   File: UseJBColorInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) {
  final Project project = manager.getProject();
  final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
  final PsiClass jbColorClass = facade.findClass(JBColor.class.getName(), GlobalSearchScope.allScope(project));
  final PsiType type = expression.getType();
  if (type != null && jbColorClass != null) {
    if (!facade.getResolveHelper().isAccessible(jbColorClass, expression, jbColorClass)) return null;
    final PsiExpressionList arguments = expression.getArgumentList();
    if (arguments != null) {
      if ("java.awt.Color".equals(type.getCanonicalText())) {
        final PsiElement parent = expression.getParent();
        if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiNewExpression) {
          final PsiType parentType = ((PsiNewExpression)parent.getParent()).getType();
          if (parentType == null || JBColor.class.getName().equals(parentType.getCanonicalText())) return null;
        }
          return manager.createProblemDescriptor(expression, "Replace with JBColor", new ConvertToJBColorQuickFix(),
                                                 ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly);
      }
    }
  }
  return null;
}
 
Example 10
Project: intellij-ce-playground   File: InspectionDescriptionNotFoundInspection.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkClass(@NotNull PsiClass psiClass, @NotNull InspectionManager manager, boolean isOnTheFly) {
  final Project project = psiClass.getProject();
  final PsiIdentifier nameIdentifier = psiClass.getNameIdentifier();
  final Module module = ModuleUtilCore.findModuleForPsiElement(psiClass);

  if (nameIdentifier == null || module == null || !PsiUtil.isInstantiable(psiClass)) return null;

  final PsiClass base = JavaPsiFacade.getInstance(project).findClass(INSPECTION_PROFILE_ENTRY, GlobalSearchScope.allScope(project));
  if (base == null || !psiClass.isInheritor(base, true) || isPathMethodsAreOverridden(psiClass)) return null;

  final InspectionDescriptionInfo info = InspectionDescriptionInfo.create(module, psiClass);
  if (!info.isValid() || info.hasDescriptionFile()) return null;

  final PsiElement problemElement = getProblemElement(psiClass, info.getShortNameMethod());
  final ProblemDescriptor problemDescriptor = manager
    .createProblemDescriptor(problemElement == null ? nameIdentifier : problemElement,
                             "Inspection does not have a description", isOnTheFly,
                             new LocalQuickFix[]{new CreateHtmlDescriptionFix(info.getFilename(), module, DescriptionType.INSPECTION)},
                             ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
  return new ProblemDescriptor[]{problemDescriptor};
}
 
Example 11
Project: intellij-ce-playground   File: GroovyRangeTypeCheckTest.java   Source Code and License 6 votes vote down vote up
public void doTest() {
  myFixture.configureByFile(getTestName(false) + ".groovy");

  final int offset = myFixture.getEditor().getCaretModel().getOffset();
  final PsiElement atCaret = myFixture.getFile().findElementAt(offset);
  final GrRangeExpression range = PsiTreeUtil.getParentOfType(atCaret, GrRangeExpression.class);
  final GroovyRangeTypeCheckInspection inspection = new GroovyRangeTypeCheckInspection();

  final GroovyFix fix = inspection.buildFix(range);

  LocalQuickFix[] fixes = {fix};
  final ProblemDescriptor descriptor = InspectionManager.getInstance(getProject()).createProblemDescriptor(range, "bla-bla", false, fixes, ProblemHighlightType.WEAK_WARNING);
  WriteCommandAction.runWriteCommandAction(null, new Runnable() {
    @Override
    public void run() {
      fix.applyFix(myFixture.getProject(), descriptor);
      PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
    }
  });


  myFixture.checkResultByFile(getTestName(false) + "_after.groovy");
}
 
Example 12
Project: polygene-java   File: MixinsAnnotationDeclaredOnMixinType.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkClass( @NotNull PsiClass psiClass,
                                       @NotNull InspectionManager manager,
                                       boolean isOnTheFly )
{
    PsiAnnotation mixinsAnnotation = getMixinsAnnotation( psiClass );
    if( mixinsAnnotation == null )
    {
        return null;
    }

    if( psiClass.isInterface() )
    {
        return null;
    }

    String message = message( "mixins.annotation.declared.on.mixin.type.error.declared.on.class" );
    RemoveInvalidMixinClassReferenceFix fix = new RemoveInvalidMixinClassReferenceFix( mixinsAnnotation );
    ProblemDescriptor problemDescriptor = manager.createProblemDescriptor( mixinsAnnotation, message, fix,
                                                                           GENERIC_ERROR_OR_WARNING );
    return new ProblemDescriptor[]{ problemDescriptor };

}
 
Example 13
Project: polygene-java   File: StructureAnnotationDeclaredCorrectlyInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
protected final ProblemDescriptor[] verifyAnnotationDeclaredCorrectly( @NotNull PsiVariable psiVariable,
                                                                       @NotNull PsiAnnotation structureAnnotation,
                                                                       @NotNull InspectionManager manager )
{
    StructureAnnotationDeclarationValidationResult annotationCheck =
        validateStructureAnnotationDeclaration( psiVariable );
    switch( annotationCheck )
    {
    case invalidInjectionType:
        String message = message(
            "injections.structure.annotation.declared.correctly.error.invalid.injection.type",
            psiVariable.getType().getCanonicalText()
        );
        AbstractFix removeStructureAnnotationFix = createRemoveAnnotationFix( structureAnnotation );
        ProblemDescriptor problemDescriptor = manager.createProblemDescriptor(
            structureAnnotation, message, removeStructureAnnotationFix, GENERIC_ERROR_OR_WARNING
        );
        return new ProblemDescriptor[]{ problemDescriptor };
    }

    return null;
}
 
Example 14
Project: intellij-pants-plugin   File: PythonPluginInspection.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
  if (PantsUtil.isBUILDFileName(file.getName()) && !PantsUtil.isPythonAvailable() && PantsUtil.isPantsProject(file.getProject())) {
    LocalQuickFix[] fixes = new LocalQuickFix[]{new AddPythonPluginQuickFix()};
    ProblemDescriptor descriptor = manager.createProblemDescriptor(
      file.getNavigationElement(),
      PantsBundle.message("pants.info.python.plugin.missing"),
      isOnTheFly,
      fixes,
      ProblemHighlightType.GENERIC_ERROR_OR_WARNING
    );
    return new ProblemDescriptor[]{descriptor};
  }
  return null;
}
 
Example 15
Project: intellij-pants-plugin   File: BuildFileTypeInspection.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
  if (PantsUtil.isBUILDFileName(file.getName()) && PantsUtil.isPythonAvailable() && PantsUtil.isPantsProject(file.getProject())) {
    if (file.getFileType() != PythonFileType.INSTANCE) {
      LocalQuickFix[] fixes = new LocalQuickFix[]{new TypeAssociationFix()};
      ProblemDescriptor descriptor = manager.createProblemDescriptor(
        file.getNavigationElement(),
        PantsBundle.message("pants.info.mistreated.build.file"),
        isOnTheFly,
        fixes,
        ProblemHighlightType.GENERIC_ERROR_OR_WARNING
      );
      return new ProblemDescriptor[]{descriptor};
    }
  }
  return null;
}
 
Example 16
Project: tools-idea   File: ViewOfflineResultsAction.java   Source Code and License 6 votes vote down vote up
@NotNull
public static InspectionResultsView showOfflineView(@NotNull Project project,
                                                    @NotNull Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap,
                                                    final InspectionProfile inspectionProfile,
                                                    final String title) {
  final AnalysisScope scope = new AnalysisScope(project);
  final InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(project);
  final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
  context.setExternalProfile(inspectionProfile);
  context.setCurrentScope(scope);
  context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>());
  final InspectionResultsView view = new InspectionResultsView(project, inspectionProfile, scope, context,
                                                               new OfflineInspectionRVContentProvider(resMap, project));
  ((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted();
  view.update();
  TreeUtil.selectFirstNode(view.getTree());
  if (context.getContentManager() != null) { //test
    context.addView(view, title);
  }
  return view;
}
 
Example 17
Project: tools-idea   File: DomElementsInspection.java   Source Code and License 6 votes vote down vote up
/**
 * not intended to be overridden or called by implementors
 */
@Nullable
protected ProblemDescriptor[] checkDomFile(@NotNull final DomFileElement<T> domFileElement,
                                           @NotNull final InspectionManager manager,
                                           @SuppressWarnings("UnusedParameters") final boolean isOnTheFly) {
  final DomElementAnnotationsManager annotationsManager = DomElementAnnotationsManager.getInstance(manager.getProject());

  final List<DomElementProblemDescriptor> list = annotationsManager.checkFileElement(domFileElement, this, isOnTheFly);
  if (list.isEmpty()) return ProblemDescriptor.EMPTY_ARRAY;

  List<ProblemDescriptor> problems =
    ContainerUtil.concat(list, new Function<DomElementProblemDescriptor, Collection<? extends ProblemDescriptor>>() {
      public Collection<ProblemDescriptor> fun(final DomElementProblemDescriptor s) {
        return annotationsManager.createProblemDescriptors(manager, s);
      }
    });
  return problems.toArray(new ProblemDescriptor[problems.size()]);
}
 
Example 18
Project: tools-idea   File: DomHighlightingLiteTest.java   Source Code and License 6 votes vote down vote up
public void testHighlightStatus_OtherInspections() throws Throwable {
  myElement.setFileDescription(new DomFileDescription(DomElement.class, "a"));
  final MyDomElementsInspection inspection = new MyDomElementsInspection() {

    @Override
    public ProblemDescriptor[] checkFile(@NotNull final PsiFile file, @NotNull final InspectionManager manager,
                                         final boolean isOnTheFly) {
      myAnnotationsManager.appendProblems(myElement, createHolder(), this.getClass());
      return new ProblemDescriptor[0];
    }

    @Override
    public void checkFileElement(final DomFileElement fileElement, final DomElementAnnotationHolder holder) {
    }
  };
  HighlightDisplayKey.register(inspection.getShortName());
  myInspectionProfile.setInspectionTools(new LocalInspectionToolWrapper(inspection));

  myAnnotationsManager.appendProblems(myElement, createHolder(), MockAnnotatingDomInspection.class);
  assertEquals(DomHighlightStatus.ANNOTATORS_FINISHED, myAnnotationsManager.getHighlightStatus(myElement));

  myAnnotationsManager.appendProblems(myElement, createHolder(), inspection.getClass());
  assertEquals(DomHighlightStatus.INSPECTIONS_FINISHED, myAnnotationsManager.getHighlightStatus(myElement));
}
 
Example 19
Project: tools-idea   File: DomHighlightingLiteTest.java   Source Code and License 6 votes vote down vote up
public void testHighlightStatus_OtherInspections2() throws Throwable {
  myElement.setFileDescription(new DomFileDescription(DomElement.class, "a"));
  final MyDomElementsInspection inspection = new MyDomElementsInspection() {

    @Override
    public ProblemDescriptor[] checkFile(@NotNull final PsiFile file, @NotNull final InspectionManager manager,
                                         final boolean isOnTheFly) {
      myAnnotationsManager.appendProblems(myElement, createHolder(), this.getClass());
      return new ProblemDescriptor[0];
    }

    @Override
    public void checkFileElement(final DomFileElement fileElement, final DomElementAnnotationHolder holder) {
    }
  };
  HighlightDisplayKey.register(inspection.getShortName());
  LocalInspectionToolWrapper toolWrapper = new LocalInspectionToolWrapper(inspection);
  myInspectionProfile.setInspectionTools(toolWrapper);
  myInspectionProfile.setEnabled(toolWrapper, false);

  myAnnotationsManager.appendProblems(myElement, createHolder(), MockAnnotatingDomInspection.class);
  assertEquals(DomHighlightStatus.INSPECTIONS_FINISHED, myAnnotationsManager.getHighlightStatus(myElement));
}
 
Example 20
Project: tools-idea   File: RegistrationProblemsInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
private ProblemDescriptor[] checkPluginXml(XmlFile xmlFile, InspectionManager manager, boolean isOnTheFly) {
  final XmlDocument document = xmlFile.getDocument();
  if (document == null) {
    return null;
  }

  final XmlTag rootTag = document.getRootTag();
  assert rootTag != null;

  final RegistrationChecker checker = new RegistrationChecker(manager, xmlFile, isOnTheFly);

  DescriptorUtil.processComponents(rootTag, checker);

  DescriptorUtil.processActions(rootTag, checker);

  return checker.getProblems();
}
 
Example 21
Project: tools-idea   File: UseJBColorInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) {
  final Project project = manager.getProject();
  final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
  final PsiClass jbColorClass = facade.findClass(JBColor.class.getName(), GlobalSearchScope.allScope(project));
  final PsiType type = expression.getType();
  if (type != null && jbColorClass != null) {
    if (!facade.getResolveHelper().isAccessible(jbColorClass, expression, jbColorClass)) return null;
    final PsiExpressionList arguments = expression.getArgumentList();
    if (arguments != null) {
      if ("java.awt.Color".equals(type.getCanonicalText())) {
        final PsiElement parent = expression.getParent();
        if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiNewExpression) {
          final PsiType parentType = ((PsiNewExpression)parent.getParent()).getType();
          if (parentType == null || JBColor.class.getName().equals(parentType.getCanonicalText())) return null;
        }
          return manager.createProblemDescriptor(expression, "Replace with JBColor", new ConvertToJBColorQuickFix(),
                                                 ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly);
      }
    }
  }
  return null;
}
 
Example 22
Project: tools-idea   File: GroovyRangeTypeCheckTest.java   Source Code and License 6 votes vote down vote up
public void doTest() {
  myFixture.configureByFile(getTestName(false) + ".groovy");

  final int offset = myFixture.getEditor().getCaretModel().getOffset();
  final PsiElement atCaret = myFixture.getFile().findElementAt(offset);
  final GrRangeExpression range = PsiTreeUtil.getParentOfType(atCaret, GrRangeExpression.class);
  final GroovyRangeTypeCheckInspection inspection = new GroovyRangeTypeCheckInspection();

  final GroovyFix fix = inspection.buildFix(range);

  LocalQuickFix[] fixes = {fix};
  final ProblemDescriptor descriptor = InspectionManager.getInstance(getProject()).createProblemDescriptor(range, "bla-bla", false, fixes, ProblemHighlightType.WEAK_WARNING);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      fix.applyFix(myFixture.getProject(), descriptor);
      PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
    }
  });


  myFixture.checkResultByFile(getTestName(false) + "_after.groovy");
}
 
Example 23
Project: idea-gitignore   File: IgnoreRelativeEntryInspection.java   Source Code and License 6 votes vote down vote up
/**
 * Checks if entries are relative.
 *
 * @param file       current working file yo check
 * @param manager    {@link InspectionManager} to ask for {@link ProblemDescriptor}'s from
 * @param isOnTheFly true if called during on the fly editor highlighting. Called from Inspect Code action
 *                   otherwise
 * @return <code>null</code> if no problems found or not applicable at file level
 */
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file,
                                     @NotNull InspectionManager manager, boolean isOnTheFly) {
    if (!(file instanceof IgnoreFile)) {
        return null;
    }

    final ProblemsHolder problemsHolder = new ProblemsHolder(manager, file, isOnTheFly);

    file.acceptChildren(new IgnoreVisitor() {
        @Override
        public void visitEntry(@NotNull IgnoreEntry entry) {
            String path = entry.getText().replaceAll("\\\\(.)", "$1");
            if (path.contains("./")) {
                problemsHolder.registerProblem(entry, IgnoreBundle.message("codeInspection.relativeEntry.message"),
                        new IgnoreRelativeEntryFix(entry));
            }
            super.visitEntry(entry);
        }
    });

    return problemsHolder.getResultsArray();
}
 
Example 24
Project: intellij-latte   File: ModifierNotAllowedInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}
	final List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LatteMacroTag) {
				boolean result = checkClassicMacro((LatteMacroTag) element);
				if (result) {
					ProblemDescriptor problem = manager.createProblemDescriptor(element, "Modifiers are not allowed here", true, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly);
					problems.add(problem);
				}
			} else {
				super.visitElement(element);
			}
		}
	});


	return problems.toArray(new ProblemDescriptor[problems.size()]);
}
 
Example 25
Project: intellij-plugin-save-actions   File: InspectionProcessor.java   Source Code and License 6 votes vote down vote up
@Override
protected void run() {
    InspectionManager inspectionManager = InspectionManager.getInstance(project);
    GlobalInspectionContext context = inspectionManager.createNewGlobalContext(false);
    InspectionToolWrapper toolWrapper = new LocalInspectionToolWrapper(inspectionTool);
    List<ProblemDescriptor> problemDescriptors;
    try {
        problemDescriptors = InspectionEngine.runInspectionOnFile(psiFile, toolWrapper, context);
    } catch (IndexNotReadyException exception) {
        return;
    }
    for (ProblemDescriptor problemDescriptor : problemDescriptors) {
        QuickFix[] fixes = problemDescriptor.getFixes();
        if (fixes != null) {
            writeQuickFixes(problemDescriptor, fixes);
        }
    }
}
 
Example 26
Project: intellij-haxe   File: HaxeUnresolvedSymbolInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
  final List<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>();
  new HaxeAnnotatingVisitor() {
    @Override
    protected void handleUnresolvedReference(HaxeReferenceExpression reference) {
      PsiElement nameIdentifier = reference.getReferenceNameElement();
      if (nameIdentifier == null) return;
      result.add(manager.createProblemDescriptor(
        nameIdentifier,
        TextRange.from(0, nameIdentifier.getTextLength()),
        getDisplayName(),
        ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
        isOnTheFly
      ));
    }
  }.visitFile(file);
  return ArrayUtil.toObjectArray(result, ProblemDescriptor.class);
}
 
Example 27
Project: guards   File: GuardsInheritanceInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkMethod(@NotNull PsiMethod method, @NotNull InspectionManager manager, boolean isOnTheFly) {
    return ProblemDescriptor.EMPTY_ARRAY;
    //ProblemsHolder problems = new ProblemsHolder(InspectionManager.getInstance(method.getProject()), method.getContainingFile(), isOnTheFly);
    //for( PsiAnnotation annotation : method.getModifierList().getAnnotations() ) {
    //
    //    GuardModel guardInfo = GuardInfo.forPsiAnnotation(annotation);
    //    if ( guardInfo.isGuard() ) {
    //        if ( DEBUG ) {
    //            //manager.createProblemDescriptor()
    //            //problems.registerProblem(annotation, "Guard: " + guardInfo, ProblemHighlightType.INFORMATION);
    //        }
    //        System.out.println(guardInfo);
    //    }
    //}
    //return problems.getResultsArray();
}
 
Example 28
Project: intellij-xquery   File: UnusedVariableInspection.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(PsiFile file, InspectionManager manager, boolean isOnTheFly) {
    if (!(file instanceof XQueryFile)) {
        return null;
    }

    List<XQueryVarName> unusedVariables = new ArrayList<XQueryVarName>();

    XQueryFile xQueryFile = (XQueryFile) file;
    for (XQueryVarName varName : xQueryFile.getVariableNames()) {
        if (isReference(varName) || isPublicDeclaredVariable(varName)) continue;
        if (variableIsNotUsed(varName, xQueryFile))
            unusedVariables.add(varName);
    }

    if (unusedVariables.size() > 0) {
        return buildProblemDescriptionsForUnusedVariables(manager, unusedVariables);
    } else {
        return null;
    }

}
 
Example 29
Project: intellij-xquery   File: InvalidVersionInspection.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    if (!(file instanceof XQueryFile)) {
        return null;
    }

    XQueryVersionDecl versionDecl = PsiTreeUtil.findChildOfType(file, XQueryVersionDecl.class);
    XQueryVersion version = versionDecl != null ? versionDecl.getVersion() : null;
    if (version != null) {
        String versionString = version.getVersionString();
        XQueryLanguageVersion languageVersion = XQueryLanguageVersion.valueFor(versionString);
        if (languageVersion == null) {
            ProblemDescriptor problem = manager.createProblemDescriptor(versionDecl.getVersion(), getDescription(versionString), (LocalQuickFix) null,
                    WEAK_WARNING, true);
            return new ProblemDescriptor[]{problem};
        }
    }

    return null;
}
 
Example 30
Project: intellij-xquery   File: DefaultFunctionNamespaceSameAsModuleNamespace.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(PsiFile file, InspectionManager manager, boolean isOnTheFly) {
    if (!(file instanceof XQueryFile)) {
        return null;
    }
    XQueryFile xQueryFile = (XQueryFile) file;
    XQueryModuleDecl moduleDeclaration = xQueryFile.getModuleDeclaration();
    XQueryDefaultFunctionNamespaceDecl defaultNamespaceFunctionDeclaration = xQueryFile.getDefaultNamespaceFunctionDeclaration();

    if (moduleDeclaration != null && defaultNamespaceFunctionDeclaration != null) {
        String namespace = moduleDeclaration.getNamespace();
        XQueryURILiteral uriLiteral = defaultNamespaceFunctionDeclaration.getURILiteral();
        String defaultFunctionNamespace = uriLiteral != null ? removeQuotOrAposIfNeeded(uriLiteral.getText()) : null;
        if (!StringUtils.equals(defaultFunctionNamespace, namespace) && !FN.getNamespace().equals(defaultFunctionNamespace)) {
            return createProblemDescriptor(manager, uriLiteral);
        }
    }

    return null;
}
 
Example 31
Project: intellij-xquery   File: NamespacePrefixFromFileName.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(PsiFile file, InspectionManager manager, boolean isOnTheFly) {
    if (!(file instanceof XQueryFile)) {
        return null;
    }

    final XQueryModuleDecl moduleDeclaration = ((XQueryFile) file).getModuleDeclaration();

    if (moduleDeclaration != null && moduleDeclaration.getNamespacePrefix() != null
            && moduleDeclaration.getURILiteral() != null
            && !namespacePrefixIsDerivedFromFileName(moduleDeclaration)) {
        ProblemDescriptor[] problemDescriptors = new ProblemDescriptor[1];
        problemDescriptors[0] = manager.createProblemDescriptor(moduleDeclaration.getNamespacePrefix(), "Namespace prefix should be derived from file name part in URI", (LocalQuickFix) null,
                GENERIC_ERROR_OR_WARNING, true);

        return problemDescriptors;
    } else {
        return null;
    }
}
 
Example 32
Project: needsmoredojo   File: MismatchedImportsInspection.java   Source Code and License 6 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, boolean isOnTheFly)
{
    if(!isEnabled(file.getProject()))
    {
        return new ProblemDescriptor[0];
    }

    DefineResolver resolver = new DefineResolver();
    final List<ProblemDescriptor> descriptors = new ArrayList<ProblemDescriptor>();

    Set<JSCallExpression> expressions = resolver.getAllImportBlocks(file);
    for(JSCallExpression expression : expressions)
    {
        addProblemsForBlock(expression, descriptors, file, manager);
    }

    return descriptors.toArray(new ProblemDescriptor[0]);
}
 
Example 33
Project: consulo   File: ViewOfflineResultsAction.java   Source Code and License 6 votes vote down vote up
@Nonnull
public static InspectionResultsView showOfflineView(@Nonnull Project project,
                                                    @Nonnull Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap,
                                                    @Nonnull InspectionProfile inspectionProfile,
                                                    @Nonnull String title) {
  final AnalysisScope scope = new AnalysisScope(project);
  final InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(project);
  final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
  context.setExternalProfile(inspectionProfile);
  context.setCurrentScope(scope);
  context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>());
  final InspectionResultsView view = new InspectionResultsView(project, inspectionProfile, scope, context,
                                                               new OfflineInspectionRVContentProvider(resMap, project));
  ((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted();
  view.update();
  TreeUtil.selectFirstNode(view.getTree());
  context.addView(view, title);
  return view;
}
 
Example 34
Project: consulo-xml   File: DomElementsInspection.java   Source Code and License 6 votes vote down vote up
/**
 * not intended to be overridden or called by implementors
 */
@Nullable
protected ProblemDescriptor[] checkDomFile(@NotNull final DomFileElement<T> domFileElement,
                                           @NotNull final InspectionManager manager,
                                           @SuppressWarnings("UnusedParameters") final boolean isOnTheFly) {
  final DomElementAnnotationsManager annotationsManager = DomElementAnnotationsManager.getInstance(manager.getProject());

  final List<DomElementProblemDescriptor> list = annotationsManager.checkFileElement(domFileElement, this, isOnTheFly);
  if (list.isEmpty()) return ProblemDescriptor.EMPTY_ARRAY;

  List<ProblemDescriptor> problems =
    ContainerUtil.concat(list, new Function<DomElementProblemDescriptor, Collection<? extends ProblemDescriptor>>() {
      public Collection<ProblemDescriptor> fun(final DomElementProblemDescriptor s) {
        return annotationsManager.createProblemDescriptors(manager, s);
      }
    });
  return problems.toArray(new ProblemDescriptor[problems.size()]);
}
 
Example 35
Project: consulo-java   File: Java15APIUsageInspectionBase.java   Source Code and License 6 votes vote down vote up
@Override
public void visitFile(PsiFile file)
{
	for(FileCheckingInspection inspection : point.getExtensions())
	{
		ProblemDescriptor[] descriptors = inspection.checkFile(file, InspectionManager.getInstance(file
				.getProject()), myOnTheFly);
		if(descriptors != null)
		{
			for(ProblemDescriptor descriptor : descriptors)
			{
				myHolder.registerProblem(descriptor);
			}
		}
	}
}
 
Example 36
Project: consulo-java   File: JavaDocReferenceInspection.java   Source Code and License 6 votes vote down vote up
@Nullable
private ProblemDescriptor[] checkMember(final PsiDocCommentOwner docCommentOwner, final InspectionManager manager, final boolean isOnTheFly)
{
	final ArrayList<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
	final PsiDocComment docComment = docCommentOwner.getDocComment();
	if(docComment == null)
	{
		return null;
	}

	final Set<PsiJavaCodeReferenceElement> references = new HashSet<PsiJavaCodeReferenceElement>();
	docComment.accept(getVisitor(references, docCommentOwner, problems, manager, isOnTheFly));
	for(PsiJavaCodeReferenceElement reference : references)
	{
		final List<PsiClass> classesToImport = new ImportClassFix(reference).getClassesToImport();
		final PsiElement referenceNameElement = reference.getReferenceNameElement();
		problems.add(manager.createProblemDescriptor(referenceNameElement != null ? referenceNameElement : reference, cannotResolveSymbolMessage("<code>" + reference.getText() + "</code>"),
				!isOnTheFly || classesToImport.isEmpty() ? null : new AddQualifierFix(classesToImport), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, isOnTheFly));
	}

	return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]);
}
 
Example 37
Project: consulo-java   File: JavaDocLocalInspection.java   Source Code and License 6 votes vote down vote up
private void checkForBadCharacters(PsiDocComment docComment,
                                 final ArrayList<ProblemDescriptor> problems,
                                 final InspectionManager manager, final boolean onTheFly) {
  docComment.accept(new PsiRecursiveElementVisitor(){
    @Override
    public void visitElement(PsiElement element) {
      super.visitElement(element);
      final ASTNode node = element.getNode();
      if (node != null) {
        if (node.getElementType() == JavaDocTokenType.DOC_COMMENT_BAD_CHARACTER) {
          problems.add(manager.createProblemDescriptor(element, "Illegal character", (LocalQuickFix)null, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, onTheFly));
        }
      }
    }
  });
}
 
Example 38
Project: consulo-java   File: JavaDocLocalInspection.java   Source Code and License 6 votes vote down vote up
private void checkForPeriodInDoc(PsiDocComment docComment,
                                 ArrayList<ProblemDescriptor> problems,
                                 InspectionManager manager, boolean onTheFly) {
  if (IGNORE_JAVADOC_PERIOD) return;
  PsiDocTag[] tags = docComment.getTags();
  int dotIndex = docComment.getText().indexOf('.');
  int tagOffset = 0;
  if (dotIndex >= 0) {      //need to find first valid tag
    final PsiDocCommentOwner owner = PsiTreeUtil.getParentOfType(docComment, PsiDocCommentOwner.class);
    for (PsiDocTag tag : tags) {
      final String tagName = tag.getName();
      final JavadocTagInfo tagInfo = JavadocManager.SERVICE.getInstance(tag.getProject()).getTagInfo(tagName);
      if (tagInfo != null && tagInfo.isValidInContext(owner) && !tagInfo.isInline()) {
        tagOffset = tag.getTextOffset();
        break;
      }
    }
  }

  if (dotIndex == -1 || tagOffset > 0 && dotIndex + docComment.getTextOffset() > tagOffset) {
    problems.add(manager.createProblemDescriptor(docComment.getFirstChild(),
                                                 InspectionsBundle.message("inspection.javadoc.problem.descriptor1"),
                                                 null,
                                                 ProblemHighlightType.GENERIC_ERROR_OR_WARNING, onTheFly, false));
  }
}
 
Example 39
Project: consulo-java   File: JavaDocLocalInspection.java   Source Code and License 6 votes vote down vote up
private boolean checkTagInfo(InspectionManager inspectionManager, JavadocTagInfo tagInfo, PsiDocTag tag, boolean isOnTheFly, ArrayList<ProblemDescriptor> problems) {
  final String tagName = tag.getName();
  final StringTokenizer tokenizer = new StringTokenizer(myAdditionalJavadocTags, ", ");
  while (tokenizer.hasMoreTokens()) {
    if (Comparing.strEqual(tagName, tokenizer.nextToken())) return true;
  }

  final PsiElement nameElement = tag.getNameElement();
  if (nameElement != null) {
    if (tagInfo == null) {
      problems.add(
        createDescriptor(nameElement, InspectionsBundle.message("inspection.javadoc.problem.wrong.tag", "<code>" + tagName + "</code>"),
                         new AddUnknownTagToCustoms(tag.getName()), inspectionManager, isOnTheFly));
    }
    else {
      problems.add(createDescriptor(nameElement, InspectionsBundle.message("inspection.javadoc.problem.disallowed.tag",
                                                                           "<code>" + tagName + "</code>"),
                                    new AddUnknownTagToCustoms(tag.getName()), inspectionManager, isOnTheFly));
    }
  }
  return false;
}
 
Example 40
Project: consulo-java   File: FileHeaderChecker.java   Source Code and License 6 votes vote down vote up
static ProblemDescriptor checkFileHeader(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean onTheFly)
{
	TIntObjectHashMap<String> offsetToProperty = new TIntObjectHashMap<>();
	FileTemplate defaultTemplate = FileTemplateManager.getInstance(file.getProject()).getDefaultTemplate(JavaTemplateUtil.FILE_HEADER_TEMPLATE_NAME);
	Pattern pattern = FileTemplateUtil.getTemplatePattern(defaultTemplate, file.getProject(), offsetToProperty);
	Matcher matcher = pattern.matcher(file.getViewProvider().getContents());
	if(!matcher.matches())
	{
		return null;
	}

	PsiComment element = PsiTreeUtil.findElementOfClassAtRange(file, matcher.start(1), matcher.end(1), PsiComment.class);
	if(element == null)
	{
		return null;
	}

	LocalQuickFix[] fixes = createQuickFix(matcher, offsetToProperty, file.getProject(), onTheFly);
	String description = InspectionsBundle.message("default.file.template.description");
	return manager.createProblemDescriptor(element, description, onTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
 
Example 41
Project: consulo-java   File: InvalidPropertyKeyInspection.java   Source Code and License 6 votes vote down vote up
private static void appendPropertyKeyNotFoundProblem(@NotNull String bundleName,
                                                     @NotNull String key,
                                                     @NotNull PsiLiteralExpression expression,
                                                     @NotNull InspectionManager manager,
                                                     @NotNull List<ProblemDescriptor> problems,
                                                     boolean onTheFly) {
  final String description = CodeInsightBundle.message("inspection.unresolved.property.key.reference.message", key);
  final List<PropertiesFile> propertiesFiles = filterNotInLibrary(expression.getProject(), JavaI18nUtil.propertiesFilesByBundleName(bundleName, expression));
  problems.add(
    manager.createProblemDescriptor(
      expression,
      description,
      propertiesFiles.isEmpty() ? null : new JavaCreatePropertyFix(expression, key, propertiesFiles),
      ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, onTheFly
    )
  );
}
 
Example 42
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkField(PsiField field, InspectionManager manager, boolean isOnTheFly) {
    if (isFieldMissingNullAnnotation(field, field.getType())) {
        Collection<ProblemDescriptor> problemDescriptors = Lists.newArrayList();
        createProblemDescriptorWithQuickFixes(field, manager, problemDescriptors, field);
        return problemDescriptors.isEmpty()
                ? null
                : problemDescriptors.toArray(new ProblemDescriptor[problemDescriptors.size()]);
    }
    return null;
}
 
Example 43
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkMethod(PsiMethod method, InspectionManager manager, boolean isOnTheFly) {
    if (isNonPrivateMethod(method)) {
        List<ProblemDescriptor> problemDescriptors = new ArrayList<>();
        List<MethodSignatureBackedByPsiMethod> superMethodSignatures = superMethods(method);
        PsiParameter[] parameters = method.getParameterList().getParameters();
        checkMethodParams(manager, problemDescriptors, superMethodSignatures, parameters);
        checkMethodReturnType(method, manager, problemDescriptors);
        return problemDescriptors.isEmpty()
                ? null
                : problemDescriptors.toArray(new ProblemDescriptor[problemDescriptors.size()]);
    }
    return null;
}
 
Example 44
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
private void checkMethodReturnType(PsiMethod method,
                                   InspectionManager manager,
                                   List<ProblemDescriptor> aProblemDescriptors) {
    if (!method.isConstructor()
            && !isIgnoredType(method.getReturnType())
            && !hasAnnotation(method)) {

        PsiTypeElement returnTypeElement = method.getReturnTypeElement();
        if (returnTypeElement == null) {
            return;
        }

        createProblemDescriptorWithQuickFixes(method, manager, aProblemDescriptors, returnTypeElement);
    }
}
 
Example 45
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
private void checkMethodParams(InspectionManager manager,
                               List<ProblemDescriptor> aProblemDescriptors,
                               List<MethodSignatureBackedByPsiMethod> aSuperMethodSignatures,
                               PsiParameter[] aParameters) {
    for (int i = 0, parametersLength = aParameters.length; i < parametersLength; i++) {
        PsiParameter parameter = aParameters[i];
        if (parameterNeedsAnnotation(parameter)) {
            if (!hasAnnotation(parameter) && !hasAnnotationInHierarchy(i, aSuperMethodSignatures)) {
                createProblemDescriptorWithQuickFixes(parameter, manager, aProblemDescriptors, parameter);
            }
        }
    }
}
 
Example 46
Project: idea-php-dotenv-plugin   File: DuplicateKeyInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    if(!(file instanceof DotEnvFile)) {
        return null;
    }

    return analyzeFile(file, manager, isOnTheFly).getResultsArray();
}
 
Example 47
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(
    final @NotNull PsiFile file,
    final @NotNull InspectionManager manager,
    final boolean isOnTheFly
) {
    if (!TypeSystemUtils.isTypeSystemXmlFile(file)) {
        return null;
    }
    final XmlFile xmlFile = (XmlFile) file;

    if (!TypeSystemValidationUtils.isCustomExtensionFile(file)) {
        return null;
    }

    final ValidateContext sharedContext = ValidateContextImpl.createFileContext(manager, isOnTheFly, xmlFile);
    if (sharedContext == null) {
        return null;
    }

    final List<ProblemDescriptor> result = new ArrayList<>();
    for (XmlRule nextRule : this.getRules()) {
        try {
            this.validateOneRule(nextRule, sharedContext, result);
        } catch (XPathExpressionException e) {
            result.add(this.createValidationFailedProblem(sharedContext, xmlFile, nextRule, e));
        }
    }

    return result.toArray(new ProblemDescriptor[result.size()]);
}
 
Example 48
Project: hybris-integration-intellij-idea-plugin   File: ValidateContextImpl.java   Source Code and License 5 votes vote down vote up
public ValidateContextImpl(
    @NotNull final InspectionManager manager,
    @NotNull final XmlFile psiFile,
    @NotNull final Document document,
    final boolean isOnTheFly
) {
    this.inspectionManager = manager;
    this.xmlFile = psiFile;
    this.document = document;
    this.isOnTheFly = isOnTheFly;
}
 
Example 49
Project: hybris-integration-intellij-idea-plugin   File: ValidateContextImpl.java   Source Code and License 5 votes vote down vote up
@Nullable
public static ValidateContext createFileContext(
    @NotNull final InspectionManager manager,
    final boolean isOnTheFly,
    @SuppressWarnings("TypeMayBeWeakened") @NotNull final XmlFile psiFile
) {
    final Document mappedDocument;
    try (StringReader reader = new StringReader(psiFile.getText())) {
        mappedDocument = buildMappedDocument(new InputSource(reader));
    } catch (SAXException | IOException e) {
        //cause will be probably reported by xml integration
        return null;
    }
    return new ValidateContextImpl(manager, psiFile, mappedDocument, isOnTheFly);
}
 
Example 50
Project: webstorm-plugin-flow-typecheck   File: FlowTypeCheckInspection.java   Source Code and License 5 votes vote down vote up
@NotNull
public ProblemDescriptor[] checkFile(@NotNull final PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
    log.info("Flow inspection running");
    return TypeCheck.errors(file).stream()
            .map(error -> manager.createProblemDescriptor(
                    file,
                    error.range(),
                    error.message(),
                    ProblemHighlightType.ERROR,
                    isOnTheFly))
            .toArray(ProblemDescriptor[]::new);
}
 
Example 51
Project: intellij-ce-playground   File: InspectionTestCase.java   Source Code and License 5 votes vote down vote up
protected GlobalInspectionContextImpl runTool(final String testDir,
                                              final String jdkName,
                                              boolean runDeadCodeFirst,
                                              @NotNull InspectionToolWrapper toolWrapper,
                                              @NotNull InspectionToolWrapper... additional) {
  final VirtualFile[] sourceDir = new VirtualFile[1];
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      try {
        setupRootModel(testDir, sourceDir, jdkName);
      }
      catch (Exception e) {
        LOG.error(e);
      }
    }
  });
  AnalysisScope scope = createAnalysisScope(sourceDir[0].getParent());

  InspectionManagerEx inspectionManager = (InspectionManagerEx)InspectionManager.getInstance(getProject());
  InspectionToolWrapper[] toolWrappers = runDeadCodeFirst ? new InspectionToolWrapper []{getUnusedDeclarationWrapper(), toolWrapper} : new InspectionToolWrapper []{toolWrapper};
  toolWrappers = ArrayUtil.mergeArrays(toolWrappers, additional);
  final GlobalInspectionContextForTests globalContext =
    CodeInsightTestFixtureImpl.createGlobalContextForTool(scope, getProject(), inspectionManager, toolWrappers);

  InspectionTestUtil.runTool(toolWrapper, scope, globalContext);
  return globalContext;
}
 
Example 52
Project: intellij-ce-playground   File: GlobalJavaInspectionContextImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void performPostRunActivities(@NotNull List<InspectionToolWrapper> needRepeatSearchRequest, @NotNull final GlobalInspectionContext context) {
  JobDescriptor progress = context.getStdJobDescriptors().FIND_EXTERNAL_USAGES;
  progress.setTotalAmount(getRequestCount());

  do {
    processSearchRequests(context);
    InspectionToolWrapper[] requestors = needRepeatSearchRequest.toArray(new InspectionToolWrapper[needRepeatSearchRequest.size()]);
    InspectionManager inspectionManager = InspectionManager.getInstance(context.getProject());
    for (InspectionToolWrapper toolWrapper : requestors) {
      boolean result = false;
      if (toolWrapper instanceof GlobalInspectionToolWrapper) {
        InspectionToolPresentation presentation = ((GlobalInspectionContextImpl)context).getPresentation(toolWrapper);
        result = ((GlobalInspectionToolWrapper)toolWrapper).getTool().queryExternalUsagesRequests(inspectionManager, context, presentation);
      }
      if (!result) {
        needRepeatSearchRequest.remove(toolWrapper);
      }
    }
    int oldSearchRequestCount = progress.getTotalAmount();
    int oldDoneAmount = progress.getDoneAmount();
    int totalAmount = oldSearchRequestCount + getRequestCount();
    progress.setTotalAmount(totalAmount);
    progress.setDoneAmount(oldDoneAmount);
  }
  while (!needRepeatSearchRequest.isEmpty());
}
 
Example 53
Project: intellij-ce-playground   File: InspectionProfileTest.java   Source Code and License 5 votes vote down vote up
public void testGlobalInspectionContext() throws Exception {
  InspectionProfileImpl profile = new InspectionProfileImpl("Foo");
  profile.disableAllTools(getProject());
  profile.enableTool(new UnusedDeclarationInspectionBase(true).getShortName(), getProject());

  GlobalInspectionContextImpl context = ((InspectionManagerEx)InspectionManager.getInstance(getProject())).createNewGlobalContext(false);
  context.setExternalProfile(profile);
  context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>());
}
 
Example 54
Project: intellij-ce-playground   File: CleanupIntention.java   Source Code and License 5 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
  if (!FileModificationService.getInstance().preparePsiElementForWrite(file)) return;
  final InspectionManager managerEx = InspectionManager.getInstance(project);
  final GlobalInspectionContextBase globalContext = (GlobalInspectionContextBase)managerEx.createNewGlobalContext(false);
  final AnalysisScope scope = getScope(project, file);
  if (scope != null) {
    final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
    globalContext.codeCleanup(project, scope, profile, getText(), null, false);
  }
}
 
Example 55
Project: intellij-ce-playground   File: CodeInsightTestFixtureImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void testInspection(@NotNull String testDir, @NotNull InspectionToolWrapper toolWrapper) {
  VirtualFile sourceDir = copyDirectoryToProject(new File(testDir, "src").getPath(), "src");
  AnalysisScope scope = new AnalysisScope(getPsiManager().findDirectory(sourceDir));

  scope.invalidate();

  InspectionManagerEx inspectionManager = (InspectionManagerEx)InspectionManager.getInstance(getProject());
  GlobalInspectionContextForTests globalContext = createGlobalContextForTool(scope, getProject(), inspectionManager, toolWrapper);

  InspectionTestUtil.runTool(toolWrapper, scope, globalContext);
  InspectionTestUtil.compareToolResults(globalContext, toolWrapper, false, new File(getTestDataPath(), testDir).getPath());
}
 
Example 56
Project: intellij-ce-playground   File: QuickFixAction.java   Source Code and License 5 votes vote down vote up
private static void refreshViews(@NotNull Project project, @NotNull Set<PsiElement> selectedElements, @NotNull InspectionToolWrapper toolWrapper) {
  InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(project);
  final Set<GlobalInspectionContextImpl> runningContexts = managerEx.getRunningContexts();
  for (GlobalInspectionContextImpl context : runningContexts) {
    for (PsiElement element : selectedElements) {
      context.ignoreElement(toolWrapper.getTool(), element);
    }
    context.refreshViews();
  }
}
 
Example 57
Project: intellij-ce-playground   File: CodeCleanupAction.java   Source Code and License 5 votes vote down vote up
@Override
protected void runInspections(Project project, AnalysisScope scope) {
  final InspectionProfile profile = myExternalProfile != null ? myExternalProfile : InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
  final InspectionManager managerEx = InspectionManager.getInstance(project);
  final GlobalInspectionContextBase globalContext = (GlobalInspectionContextBase)managerEx.createNewGlobalContext(false);
  globalContext.codeCleanup(project, scope, profile, getTemplatePresentation().getText(), null, false);
}
 
Example 58
Project: intellij-ce-playground   File: CodeInspectionOnEditorAction.java   Source Code and License 5 votes vote down vote up
protected static void analyze(Project project, PsiFile psiFile) {
  FileDocumentManager.getInstance().saveAllDocuments();
  final InspectionManagerEx inspectionManagerEx = (InspectionManagerEx)InspectionManager.getInstance(project);
  final AnalysisScope scope = new AnalysisScope(psiFile);
  final GlobalInspectionContextImpl inspectionContext = inspectionManagerEx.createNewGlobalContext(false);
  inspectionContext.setCurrentScope(scope);
  final InspectionProfile inspectionProfile =
    InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
  inspectionContext.setExternalProfile(inspectionProfile);
  inspectionContext.doInspections(scope);
}
 
Example 59
Project: intellij-ce-playground   File: WholeFileLocalInspectionsPassFactory.java   Source Code and License 5 votes vote down vote up
@Override
@Nullable
public TextEditorHighlightingPass createHighlightingPass(@NotNull final PsiFile file, @NotNull final Editor editor) {
  TextRange textRange = FileStatusMap.getDirtyTextRange(editor, Pass.LOCAL_INSPECTIONS);
  if (textRange == null ||
      !InspectionProjectProfileManager.getInstance(file.getProject()).isProfileLoaded() ||
      myFileTools.containsKey(file) && !myFileTools.get(file)) {
    return null;
  }

  return new LocalInspectionsPass(file, editor.getDocument(), 0, file.getTextLength(), LocalInspectionsPass.EMPTY_PRIORITY_RANGE, true,
                                  new DefaultHighlightInfoProcessor()) {
    @NotNull
    @Override
    List<LocalInspectionToolWrapper> getInspectionTools(@NotNull InspectionProfileWrapper profile) {
      List<LocalInspectionToolWrapper> tools = super.getInspectionTools(profile);
      List<LocalInspectionToolWrapper> result = new ArrayList<LocalInspectionToolWrapper>(tools.size());
      for (LocalInspectionToolWrapper tool : tools) {
        if (tool.runForWholeFile()) result.add(tool);
      }
      myFileTools.put(file, !result.isEmpty());
      return result;
    }

    @Override
    protected String getPresentableName() {
      return DaemonBundle.message("pass.whole.inspections");
    }

    @Override
    void inspectInjectedPsi(@NotNull List<PsiElement> elements,
                            boolean onTheFly,
                            @NotNull ProgressIndicator indicator,
                            @NotNull InspectionManager iManager,
                            boolean inVisibleRange,
                            @NotNull List<LocalInspectionToolWrapper> wrappers) {
      // already inspected in LIP
    }
  };
}
 
Example 60
Project: intellij-ce-playground   File: PyInconsistentIndentationInspection.java   Source Code and License 5 votes vote down vote up
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
  if (file.getLanguage() instanceof PythonLanguage) {
    return new IndentValidator(file, manager, isOnTheFly).invoke();
  }
  return ProblemDescriptor.EMPTY_ARRAY;
}