Java Code Examples for com.intellij.codeInspection.ProblemHighlightType

The following are top voted examples for showing how to use com.intellij.codeInspection.ProblemHighlightType. 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: yii2support   File: UndetectableTableInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpClass(PhpClass clazz) {
            PhpIndex index = PhpIndex.getInstance(problemsHolder.getProject());
            if (DatabaseUtils.HasConnections(problemsHolder.getProject()) &&
                    ClassUtils.isClassInheritsOrEqual(clazz, ClassUtils.getClass(index, "\\yii\\db\\ActiveRecord"))) {
                String table = DatabaseUtils.getTableByActiveRecordClass(clazz);
                if (table == null) {
                    problemsHolder.registerProblem(clazz.getFirstChild(), "Can not detect database table for class " + clazz.getFQN(), ProblemHighlightType.WEAK_WARNING);
                } else if (! DatabaseUtils.isTableExists(table, problemsHolder.getProject())) {
                    problemsHolder.registerProblem(clazz.getFirstChild(), "Table '" + table + "' not found in database connections", ProblemHighlightType.WEAK_WARNING);

                }
            }
            super.visitPhpClass(clazz);
        }
    };
}
 
Example 2
Project: yii2support   File: MissingActiveRecordInActiveQueryInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean isOnTheFly) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpClass(PhpClass clazz) {
            if (clazz.getSuperClass() != null && clazz.getSuperClass().getFQN().equals("\\yii\\db\\ActiveQuery")) {
                PhpIndex index = PhpIndex.getInstance(clazz.getProject());

                PhpClass activeRecordClass = ClassUtils.findClassInSeeTags(index, clazz, "\\yii\\db\\BaseActiveRecord");
                if (activeRecordClass == null) {
                    problemsHolder.registerProblem(clazz.getFirstChild(),
                            "Can not find connected ActiveRecord class.\nYou should add @see tag with linked ActiveRecord",
                            ProblemHighlightType.WEAK_WARNING);
                }
            }
            super.visitPhpClass(clazz);

        }
    };
}
 
Example 3
Project: idea-php-typo3-plugin   File: LegacyClassesForIDEInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpClassReference(ClassReference classReference) {
            if (classReference.getFQN() != null && LegacyClassesForIDEIndex.isLegacyClass(classReference.getProject(), classReference.getFQN())) {
                problemsHolder.registerProblem(classReference, "Legacy class usage", ProblemHighlightType.LIKE_DEPRECATED, new LegacyClassesForIdeQuickFix());
            }

            super.visitPhpClassReference(classReference);
        }

        @Override
        public void visitPhpClassConstantReference(ClassConstantReference constantReference) {
            super.visitPhpClassConstantReference(constantReference);
        }
    };
}
 
Example 4
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 6 votes vote down vote up
protected ProblemDescriptor createProblem(
    @NotNull final ValidateContext context,
    @NotNull final Node problemNode,
    @NotNull final XmlRule rule
) {
    final PsiElement problemPsi = context.mapNodeToPsi(problemNode);
    final ProblemHighlightType highlightType = this.computePriority(rule);

    return context.getManager().createProblemDescriptor(
        problemPsi,
        rule.getDescription(),
        true,
        highlightType,
        context.isOnTheFly()
    );
}
 
Example 5
Project: lua-for-idea   File: UnassignedVariableAccessInspection.java   Source Code and License 6 votes vote down vote up
protected void check(LuaControlFlowOwner owner, ProblemsHolder problemsHolder) {
    try {
        Instruction[] flow = owner.getControlFlow();
        if (flow == null) return;
        ReadWriteVariableInstruction[] reads = ControlFlowUtil.getReadsWithoutPriorWrites(flow);
        for (ReadWriteVariableInstruction read : reads) {
            PsiElement element = read.getElement();
            if (element instanceof LuaReferenceElement) {
                if (((LuaReferenceElement) element).getElement() instanceof LuaGlobal)
                    if (((LuaReferenceElement) element).multiResolve(false).length == 0) {

                        if (element.getTextLength() > 0)
                            problemsHolder.registerProblem(element, "Unassigned variable usage",
                                    ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
                    }
            }
        }
    } catch (Exception ignored) {
    }
}
 
Example 6
Project: lua-for-idea   File: LuaUnreachableStatementInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new LuaElementVisitor() {
        public void visitFile(PsiFile file) {
            if (!(file instanceof LuaPsiFile)) return;

            LuaStatementElement[] statements = ((LuaPsiFile) file).getStatements();
            for (int i = 0; i < statements.length - 1; i++) {
                checkPair(statements[i], statements[i + 1]);
            }
        }

        private void checkPair(LuaStatementElement prev, LuaStatementElement statement) {
            if (!ControlFlowUtils.statementMayCompleteNormally(prev)) {
                holder.registerProblem(statement,
                        buildErrorString(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
            }

        }
    };
}
 
Example 7
Project: intellij-ce-playground   File: GroovyTypeCheckVisitor.java   Source Code and License 6 votes vote down vote up
protected void processAssignmentWithinMultipleAssignment(@NotNull GrExpression lhs,
                                                         @NotNull GrExpression rhs,
                                                         @NotNull GrExpression context) {
  final PsiType targetType = lhs.getType();
  final PsiType actualType = rhs.getType();
  if (targetType == null || actualType == null) return;

  final ConversionResult result = TypesUtil.canAssignWithinMultipleAssignment(targetType, actualType, context);
  if (result == ConversionResult.OK) return;
  registerError(
    rhs,
    GroovyBundle.message("cannot.assign", actualType.getPresentableText(), targetType.getPresentableText()),
    LocalQuickFix.EMPTY_ARRAY,
    result == ConversionResult.ERROR ? ProblemHighlightType.GENERIC_ERROR : ProblemHighlightType.GENERIC_ERROR_OR_WARNING
  );
}
 
Example 8
Project: arma-intellij-plugin   File: CommandCamelCaseInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitCommand(@NotNull SQFPsiCommand o) {
	super.visitCommand(o);
	for (String command : SQFStatic.LIST_COMMANDS) {
		if (o.getText().equalsIgnoreCase(command)) {
			if (!o.getText().equals(command)) {
				holder.registerProblem(
						o, SQFStatic.getSQFBundle().getString("Inspections.CommandCamelCase.annotator-problem-description"),
						ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
						new CamelCaseFixAction(o)
				);
			}
			break;
		}
	}
}
 
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: UseVirtualFileEqualsInspection.java   Source Code and License 6 votes vote down vote up
@Override
public PsiElementVisitor buildInternalVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
  return new JavaElementVisitor() {
    @Override
    public void visitBinaryExpression(@NotNull PsiBinaryExpression expression) {
      super.visitBinaryExpression(expression);
      if (!ComparisonUtils.isEqualityComparison(expression)) {
        return;
      }
      final PsiExpression lhs = expression.getLOperand();
      final PsiExpression rhs = expression.getROperand();
      if (rhs == null ||
          lhs.textMatches(PsiKeyword.NULL) || rhs.textMatches(PsiKeyword.NULL) ||
          lhs.textMatches(PsiKeyword.THIS) || rhs.textMatches(PsiKeyword.THIS)) {
        return;
      }
      
      if (InheritanceUtil.isInheritor(lhs.getType(), VirtualFile.class.getName()) || InheritanceUtil.isInheritor(rhs.getType(), VirtualFile.class.getName())) {
        holder.registerProblem(expression, "VirtualFile objects should be compared by equals(), not ==", ProblemHighlightType.GENERIC_ERROR_OR_WARNING);

      }
    }
  };
}
 
Example 11
Project: intellij-ce-playground   File: GroovyTypeCheckVisitor.java   Source Code and License 6 votes vote down vote up
private void highlightInapplicableMethodUsage(@NotNull GroovyResolveResult methodResolveResult,
                                              @NotNull CallInfo info,
                                              @NotNull PsiMethod method) {
  final PsiClass containingClass =
    method instanceof GrGdkMethod ? ((GrGdkMethod)method).getStaticMethod().getContainingClass() : method.getContainingClass();

  PsiType[] argumentTypes = info.getArgumentTypes();
  if (containingClass == null) {
    registerCannotApplyError(method.getName(), info);
    return;
  }
  final String typesString = buildArgTypesList(argumentTypes);
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(method.getProject());
  final PsiClassType containingType = factory.createType(containingClass, methodResolveResult.getSubstitutor());
  final String canonicalText = containingType.getInternalCanonicalText();
  String message =
    method.isConstructor() ? GroovyBundle.message("cannot.apply.constructor", method.getName(), canonicalText, typesString)
                           : GroovyBundle.message("cannot.apply.method1", method.getName(), canonicalText, typesString);

  registerError(
    info.getElementToHighlight(),
    message,
    genCastFixes(GrClosureSignatureUtil.createSignature(methodResolveResult), argumentTypes, info.getArgumentList()),
    ProblemHighlightType.GENERIC_ERROR
  );
}
 
Example 12
Project: intellij-ce-playground   File: GroovyPostHighlightingPass.java   Source Code and License 6 votes vote down vote up
@Override
public void doApplyInformationToEditor() {
  if (myUnusedDeclarations == null || myUnusedImports == null) {
    return;
  }

  AnnotationHolder annotationHolder = new AnnotationHolderImpl(new AnnotationSession(myFile));
  List<HighlightInfo> infos = new ArrayList<HighlightInfo>(myUnusedDeclarations);
  for (GrImportStatement unusedImport : myUnusedImports) {
    Annotation annotation = annotationHolder.createWarningAnnotation(calculateRangeToUse(unusedImport), GroovyInspectionBundle.message("unused.import"));
    annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
    annotation.registerFix(GroovyQuickFixFactory.getInstance().createOptimizeImportsFix(false));
    infos.add(HighlightInfo.fromAnnotation(annotation));
  }

  UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, myFile.getTextLength(), infos, getColorsScheme(), getId());

  if (myUnusedImports != null && !myUnusedImports.isEmpty()) {
    IntentionAction fix = GroovyQuickFixFactory.getInstance().createOptimizeImportsFix(true);
    if (fix.isAvailable(myProject, myEditor, myFile) && myFile.isWritable()) {
      fix.invoke(myProject, myEditor, myFile);
    }
  }
}
 
Example 13
Project: intellij-ce-playground   File: PyNestedDecoratorsInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitPyFunction(final PyFunction node) {
  PyDecoratorList decolist = node.getDecoratorList();
  if (decolist != null) {
    PyDecorator[] decos = decolist.getDecorators();
    if (decos.length > 1) {
      for (int i = decos.length - 1; i >= 1; i -= 1) {
        PyDecorator deco = decos[i];
        String deconame = deco.getName();
        if ((PyNames.CLASSMETHOD.equals(deconame) || PyNames.STATICMETHOD.equals(deconame)) && deco.isBuiltin()) {
          registerProblem(
            decos[i-1],
            PyBundle.message("INSP.decorator.receives.unexpected.builtin"),
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING, null, new RemoveDecoratorQuickFix()
          );
        }
      }
    }
  }
}
 
Example 14
Project: intellij-ce-playground   File: PyCompatibilityInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitPyArgumentList(final PyArgumentList node) { //PY-5588
  final List<PyElement> problemElements = new ArrayList<PyElement>();
  if (node.getParent() instanceof PyClass) {
    for (final PyExpression expression : node.getArguments()) {
      if (expression instanceof PyKeywordArgument)
        problemElements.add(expression);
    }
  }
  final String errorMessage = "This syntax available only since py3";
  final boolean isPy3 = LanguageLevel.forElement(node).isPy3K();
  if (shouldBeCompatibleWithPy2() || !isPy3) {
    for (final PyElement problemElement : problemElements)
      myHolder.registerProblem(problemElement, errorMessage, isPy3? ProblemHighlightType.GENERIC_ERROR_OR_WARNING :
                                                      ProblemHighlightType.GENERIC_ERROR);
  }
}
 
Example 15
Project: intellij-ce-playground   File: PyTypeCheckerInspection.java   Source Code and License 6 votes vote down vote up
private void checkCallSite(@Nullable PyCallSiteExpression callSite) {
  final List<PyTypeChecker.AnalyzeCallResults> resultsSet = PyTypeChecker.analyzeCallSite(callSite, myTypeEvalContext);
  final List<Map<PyExpression, Pair<String, ProblemHighlightType>>> problemsSet = new ArrayList<Map<PyExpression, Pair<String, ProblemHighlightType>>>();
  for (PyTypeChecker.AnalyzeCallResults results : resultsSet) {
    problemsSet.add(checkMapping(results.getReceiver(), results.getArguments()));
  }
  if (!problemsSet.isEmpty()) {
    Map<PyExpression, Pair<String, ProblemHighlightType>> minProblems = Collections.min(problemsSet, new Comparator<Map<PyExpression, Pair<String, ProblemHighlightType>>>() {
      @Override
      public int compare(Map<PyExpression, Pair<String, ProblemHighlightType>> o1,
                         Map<PyExpression, Pair<String, ProblemHighlightType>> o2) {
        return o1.size() - o2.size();
      }
    });
    for (Map.Entry<PyExpression, Pair<String, ProblemHighlightType>> entry : minProblems.entrySet()) {
      registerProblem(entry.getKey(), entry.getValue().getFirst(), entry.getValue().getSecond());
    }
  }
}
 
Example 16
Project: intellij-ce-playground   File: RegExpAnnotator.java   Source Code and License 6 votes vote down vote up
@Override
public void visitRegExpNamedGroupRef(RegExpNamedGroupRef groupRef) {
  if (!myLanguageHosts.supportsNamedGroupRefSyntax(groupRef)) {
    myHolder.createErrorAnnotation(groupRef, "This named group reference syntax is not supported");
    return;
  }
  if (groupRef.getGroupName() == null) {
    return;
  }
  final RegExpGroup group = groupRef.resolve();
  if (group == null) {
    final Annotation a = myHolder.createErrorAnnotation(groupRef, "Unresolved named group reference");
    if (a != null) {
      // IDEA-9381
      a.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
    }
  }
  else if (PsiTreeUtil.isAncestor(group, groupRef, true)) {
    myHolder.createWarningAnnotation(groupRef, "Group reference is nested into the named group it refers to");
  }
}
 
Example 17
Project: intellij-ce-playground   File: XPathAnnotator.java   Source Code and License 6 votes vote down vote up
private static void markUnresolvedVariable(XPathVariableReference reference, AnnotationHolder holder) {
  final String referencedName = reference.getReferencedName();
  // missing name is already flagged by parser
  if (referencedName.length() > 0) {
    final TextRange range = reference.getTextRange().shiftRight(1).grown(-1);
    final Annotation ann = holder.createErrorAnnotation(range, "Unresolved variable '" + referencedName + "'");
    ann.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
    final VariableContext variableContext = ContextProvider.getContextProvider(reference).getVariableContext();
    if (variableContext != null) {
      final IntentionAction[] fixes = variableContext.getUnresolvedVariableFixes(reference);
      for (IntentionAction fix : fixes) {
        ann.registerFix(fix);
      }
    }
  }
}
 
Example 18
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 19
Project: intellij-ce-playground   File: GrReassignedInClosureLocalVarInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
protected BaseInspectionVisitor buildVisitor() {
  return new BaseInspectionVisitor() {
    @Override
    public void visitReferenceExpression(GrReferenceExpression referenceExpression) {
      super.visitReferenceExpression(referenceExpression);

      if (!PsiUtil.isLValue(referenceExpression)) return;
      final PsiElement resolved = referenceExpression.resolve();
      if (!PsiUtil.isLocalVariable(resolved)) return;

      final PsiType checked = GrReassignedLocalVarsChecker.getReassignedVarType(referenceExpression, false);
      if (checked == null) return;

      final GrControlFlowOwner varFlowOwner = ControlFlowUtils.findControlFlowOwner(resolved);
      final GrControlFlowOwner refFlorOwner = ControlFlowUtils.findControlFlowOwner(referenceExpression);
      if (isOtherScopeAndType(referenceExpression, checked, varFlowOwner, refFlorOwner)) {
        String flowDescription = getFlowDescription(refFlorOwner);
        final String message = GroovyInspectionBundle
          .message("local.var.0.is.reassigned", ((GrNamedElement)resolved).getName(), flowDescription);
        registerError(referenceExpression, message, LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
      }
    }
  };
}
 
Example 20
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 21
Project: intellij-ce-playground   File: XPathAnnotator.java   Source Code and License 6 votes vote down vote up
@Override
public void visitXPath2TypeElement(XPath2TypeElement o) {
  final ContextProvider contextProvider = o.getXPathContext();
  checkPrefixReferences(myHolder, o, contextProvider);

  if (o.getDeclaredType() == XPathType.UNKNOWN) {
    final PsiReference[] references = o.getReferences();
    for (PsiReference reference : references) {
      if (reference instanceof XsltReferenceContributor.SchemaTypeReference ) {
        if (!reference.isSoft() && reference.resolve() == null) {
          final String message = ((EmptyResolveMessageProvider)reference).getUnresolvedMessagePattern();
          final Annotation annotation =
            myHolder.createErrorAnnotation(reference.getRangeInElement().shiftRight(o.getTextOffset()), message);
          annotation.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
        }
      }
    }
  }
  super.visitXPath2TypeElement(o);
}
 
Example 22
Project: intellij-ce-playground   File: UnusedDefineInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitDefine(RncDefine pattern) {
  final RncGrammar grammar = PsiTreeUtil.getParentOfType(pattern, RncGrammar.class);
  final PsiFile file = pattern.getContainingFile();
  if (grammar != null) {
    if (processRncUsages(pattern, new LocalSearchScope(grammar))) return;
  } else {
    if (processRncUsages(pattern, new LocalSearchScope(file))) return;
  }

  final PsiElementProcessor.CollectElements<XmlFile> collector = new PsiElementProcessor.CollectElements<XmlFile>();
  RelaxIncludeIndex.processBackwardDependencies((XmlFile)file, collector);

  if (processRncUsages(pattern, new LocalSearchScope(collector.toArray()))) return;

  final ASTNode astNode = ((RncDefineImpl)pattern).getNameNode();
  myHolder.registerProblem(astNode.getPsi(), "Unreferenced define", ProblemHighlightType.LIKE_UNUSED_SYMBOL, new MyFix<RncDefine>(pattern));
}
 
Example 23
Project: epigraph   File: UnusedImportInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
  return new SchemaVisitor() {
    @Override
    public void visitImports(@NotNull SchemaImports schemaTypeImports) {
      super.visitImports(schemaTypeImports);

      Set<SchemaImportStatement> unusedImports = ImportsManager.findUnusedImports((SchemaFile) schemaTypeImports.getContainingFile());
      for (SchemaImportStatement unusedImport : unusedImports) {
        holder.registerProblem(unusedImport,
            InspectionBundle.message("import.unused.problem.descriptor"),
            ProblemHighlightType.LIKE_UNUSED_SYMBOL,
            OptimizeImportsQuickFix.INSTANCE);
      }
    }
  };
}
 
Example 24
Project: intellij-ce-playground   File: UnnecessaryQualifierForThisInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitThisExpression(
  @NotNull PsiThisExpression thisExpression) {
  super.visitThisExpression(thisExpression);
  final PsiJavaCodeReferenceElement qualifier =
    thisExpression.getQualifier();
  if (qualifier == null) {
    return;
  }
  final PsiElement referent = qualifier.resolve();
  if (!(referent instanceof PsiClass)) {
    return;
  }
  final PsiClass containingClass =
    ClassUtils.getContainingClass(thisExpression);
  if (containingClass == null) {
    return;
  }
  if (!containingClass.equals(referent)) {
    return;
  }
  registerError(qualifier, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
 
Example 25
Project: intellij-ce-playground   File: GrPackageInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
protected BaseInspectionVisitor buildVisitor() {
  return new BaseInspectionVisitor() {
    @Override
    public void visitFile(GroovyFileBase file) {
      if (!(file instanceof GroovyFile)) return;

      if (!myCheckScripts && file.isScript()) return;

      String expectedPackage = ResolveUtil.inferExpectedPackageName(file);
      String actual = file.getPackageName();
      if (!expectedPackage.equals(actual)) {

        PsiElement toHighlight = getElementToHighlight((GroovyFile)file);
        if (toHighlight == null) return;

        registerError(toHighlight, "Package name mismatch. Actual: '" + actual + "', expected: '" + expectedPackage+"'",
                      new LocalQuickFix[]{new ChangePackageQuickFix(expectedPackage), GroovyQuickFixFactory.getInstance().createGrMoveToDirFix(actual)},
                      ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
      }
    }
  };
}
 
Example 26
Project: intellij-ce-playground   File: UndesirableClassUsageInspection.java   Source Code and License 6 votes vote down vote up
@Override
@NotNull
public PsiElementVisitor buildInternalVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
  return new JavaElementVisitor() {
    @Override
    public void visitNewExpression(PsiNewExpression expression) {
      PsiJavaCodeReferenceElement ref = expression.getClassReference();
      if (ref == null) return;

      PsiElement res = ref.resolve();
      if (res == null) return;

      String name = ((PsiClass)res).getQualifiedName();
      if (name == null) return;

      String replacement = CLASSES.get(name);
      if (replacement == null) return;

      holder.registerProblem(expression, "Please use '" + replacement + "' instead", ProblemHighlightType.LIKE_DEPRECATED);
    }
  };
}
 
Example 27
Project: intellij-ce-playground   File: RedundantFieldInitializationInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitField(@NotNull PsiField field) {
  super.visitField(field);
  if (!field.hasInitializer() || field.hasModifierProperty(PsiModifier.FINAL)) {
    return;
  }
  final PsiExpression initializer = field.getInitializer();
  if (initializer == null) {
    return;
  }
  final String text = initializer.getText();
  final PsiType type = field.getType();
  if (PsiType.BOOLEAN.equals(type)) {
    if (onlyWarnOnNull || !PsiKeyword.FALSE.equals(text)) {
      return;
    }
  } else if (type instanceof PsiPrimitiveType) {
    if (onlyWarnOnNull || !ExpressionUtils.isZero(initializer)) {
      return;
    }
  } else if (!PsiType.NULL.equals(initializer.getType())) {
    return;
  }
  registerError(initializer, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
 
Example 28
Project: intellij-ce-playground   File: UnnecessarySuperConstructorInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitMethodCallExpression(
  @NotNull PsiMethodCallExpression call) {
  super.visitMethodCallExpression(call);
  final PsiReferenceExpression methodExpression =
    call.getMethodExpression();
  final String methodText = methodExpression.getText();
  if (!PsiKeyword.SUPER.equals(methodText)) {
    return;
  }
  final PsiExpressionList argumentList = call.getArgumentList();
  final PsiExpression[] args = argumentList.getExpressions();
  if (args.length != 0) {
    return;
  }
  registerError(call, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
 
Example 29
Project: intellij-ce-playground   File: UnnecessaryEnumModifierInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitClass(@NotNull PsiClass aClass) {
  if (!aClass.isEnum() || !ClassUtils.isInnerClass(aClass) || !aClass.hasModifierProperty(PsiModifier.STATIC)) {
    return;
  }
  final PsiModifierList modifiers = aClass.getModifierList();
  if (modifiers == null) {
    return;
  }
  final PsiElement[] children = modifiers.getChildren();
  for (final PsiElement child : children) {
    final String text = child.getText();
    if (PsiModifier.STATIC.equals(text)) {
      registerError(child, ProblemHighlightType.LIKE_UNUSED_SYMBOL, child, aClass);
    }
  }
}
 
Example 30
Project: intellij-ce-playground   File: UnnecessaryExplicitNumericCastInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitTypeCastExpression(PsiTypeCastExpression expression) {
  super.visitTypeCastExpression(expression);
  final PsiType castType = expression.getType();
  if (!ClassUtils.isPrimitiveNumericType(castType)) {
    return;
  }
  final PsiExpression operand = expression.getOperand();
  if (operand == null) {
    return;
  }
  final PsiType operandType = operand.getType();
  if (castType.equals(operandType) || isPrimitiveNumericCastNecessary(expression)) {
    return;
  }
  final PsiTypeElement typeElement = expression.getCastType();
  if (typeElement != null) {
    registerError(typeElement, ProblemHighlightType.LIKE_UNUSED_SYMBOL, operand);
  }
}
 
Example 31
Project: intellij-ce-playground   File: GroovyUnusedCatchParameterInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitCatchClause(GrCatchClause catchClause) {
  super.visitCatchClause(catchClause);
  final GrOpenBlock block = catchClause.getBody();
  if (block == null) {
    return;
  }
  final GrParameter parameter = catchClause.getParameter();
  if (parameter == null) {
    return;
  }
  if (GrExceptionUtil.ignore(parameter)) return;
  final CatchParameterUsedVisitor visitor = new CatchParameterUsedVisitor(parameter);
  block.accept(visitor);
  if (!visitor.isUsed()) {
    final PsiElement nameIdentifier = parameter.getNameIdentifierGroovy();
    registerError(nameIdentifier, "Unused catch parameter '#ref' #loc", new LocalQuickFix[]{QuickFixFactory.getInstance().createRenameElementFix(parameter, "ignored")},
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
  }
}
 
Example 32
Project: intellij-ce-playground   File: DontUseNewPairInspection.java   Source Code and License 6 votes vote down vote up
@Override
public PsiElementVisitor buildInternalVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
  return new JavaElementVisitor() {
    @Override
    public void visitNewExpression(PsiNewExpression expression) {
      final PsiType type = expression.getType();
      final PsiExpressionList params = expression.getArgumentList();
      if (type instanceof PsiClassType
          && ((PsiClassType)type).rawType().equalsToText(PAIR_FQN)
          && params != null
          && expression.getArgumentList() != null
          //&& !PsiUtil.getLanguageLevel(expression).isAtLeast(LanguageLevel.JDK_1_7) //diamonds
      ) {
        final PsiType[] types = ((PsiClassType)type).getParameters();
        if (Arrays.equals(types, params.getExpressionTypes())) {
          holder.registerProblem(expression, "Replace to Pair.create()", ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
                                 new ChangeToPairCreateQuickFix());
        }
      }
      super.visitNewExpression(expression);
    }
  };
}
 
Example 33
Project: intellij-ce-playground   File: GroovyEmptyCatchBlockInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void visitCatchClause(GrCatchClause catchClause) {
  super.visitCatchClause(catchClause);
  final GrOpenBlock body = catchClause.getBody();
  if (body == null || !isEmpty(body)) {
    return;
  }

  final GrParameter parameter = catchClause.getParameter();
  if (parameter == null) return;
  if (myIgnore && GrExceptionUtil.ignore(parameter)) return;

  LocalQuickFix fix = QuickFixFactory.getInstance().createRenameElementFix(parameter, "ignored");
  final LocalQuickFix[] fixes = myIgnore
                                ? new LocalQuickFix[]{fix}
                                : LocalQuickFix.EMPTY_ARRAY;
  registerError(catchClause.getFirstChild(), "Empty '#ref' block #loc", fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
 
Example 34
Project: ijaas   File: JavaSrcUpdateHandler.java   Source Code and License 5 votes vote down vote up
private static String toProblemType(ProblemHighlightType type) {
  switch (type) {
    case ERROR:
    case GENERIC_ERROR:
    case LIKE_UNKNOWN_SYMBOL:
      return Problem.ERROR;
    default:
      return Problem.WARNING;
  }
}
 
Example 35
Project: yii2support   File: PropertiesInspection.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean isOnTheFly) {


    return new PhpElementVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            if (element instanceof PhpDocComment && DatabaseUtils.HasConnections(element.getProject())) {
                PhpDocComment docComment = (PhpDocComment) element;
                PhpIndex index = PhpIndex.getInstance(element.getProject());

                PhpClass phpClass = DatabaseUtils.getClassByClassPhpDoc(docComment);
                if (phpClass != null && ClassUtils.isClassInheritsOrEqual(phpClass, ClassUtils.getClass(index, "\\yii\\db\\BaseActiveRecord"))) {
                    Collection<Field> fields = phpClass.getFields();
                    String table = DatabaseUtils.getTableByActiveRecordClass(phpClass);
                    ArrayList<VirtualProperty> notDeclaredColumns = DatabaseUtils.getNotDeclaredColumns(table, fields, element.getProject());
                    if (notDeclaredColumns.size() > 0) {
                        MissingPropertiesQuickFix qFix = new MissingPropertiesQuickFix(notDeclaredColumns, docComment);
                        String str1 = notDeclaredColumns.size() > 1 ? "properties" : "property";
                        problemsHolder.registerProblem(docComment, "Class " + phpClass.getFQN() +
                                " is missing " + notDeclaredColumns.size() + " " + str1 + " that corresponds to database columns", ProblemHighlightType.WEAK_WARNING, qFix);
                    }

                    ArrayList<PhpDocPropertyTag> unusedProperties = DatabaseUtils.getUnusedProperties(table, docComment.getPropertyTags(), phpClass);
                    if (unusedProperties.size() > 0) {
                        for (PhpDocPropertyTag tag: unusedProperties) {
                            problemsHolder.registerProblem(tag, "Property is unused in class " + phpClass.getFQN(), ProblemHighlightType.LIKE_UNUSED_SYMBOL);
                        }
                    }
                }

            }
            super.visitElement(element);
        }


    };
}
 
Example 36
Project: laravel-insight   File: UsingAsTypeInspection.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(
    @NotNull final ProblemsHolder problemsHolder,
    final boolean isOnTheFly
) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpMethod(final Method method) {
            final PhpReturnType  returnType                     = method.getReturnType();
            final ClassReference methodReturnTypeClassReference = (returnType != null) ? returnType.getClassReference() : null;

            if (FluentUtil.isUsingDirectly(methodReturnTypeClassReference)) {
                problemsHolder.registerProblem(methodReturnTypeClassReference, messageDirectInstantiation, ProblemHighlightType.WEAK_WARNING);
            }
        }

        @Override
        public void visitPhpFunction(final Function function) {
            final PhpReturnType functionReturnType = function.getReturnType();
            if ((functionReturnType != null) && FluentUtil.isUsingDirectly(functionReturnType.getClassReference())) {
                problemsHolder.registerProblem(functionReturnType, messageDirectInstantiation, ProblemHighlightType.WEAK_WARNING);
            }
        }

        @Override
        public void visitPhpParameter(final Parameter parameter) {
            if (FluentUtil.isUsingDirectly(parameter)) {
                problemsHolder.registerProblem(parameter, messageDirectInstantiation, ProblemHighlightType.WEAK_WARNING);
            }
        }

        @Override
        public void visitPhpDocType(final PhpDocType type) {
            if (FluentUtil.isUsingDirectly(type)) {
                problemsHolder.registerProblem(type, messageDirectInstantiation, ProblemHighlightType.WEAK_WARNING);
            }
        }
    };
}
 
Example 37
Project: laravel-insight   File: ColumnWithoutAnnotationInspection.java   Source Code and License 5 votes vote down vote up
static void registerPropertyUndefined(
    @NotNull final ProblemsHolder problemsHolder,
    @NotNull final PhpClass primaryClass,
    @NotNull final PsiElement issuedElement,
    @NotNull final String propertyName,
    @NotNull final String propertyType
) {
    problemsHolder.registerProblem(issuedElement,
                                   String.format(messagePropertyUndefined, propertyName),
                                   ProblemHighlightType.WEAK_WARNING,
                                   new PropertyQuickFix(primaryClass, propertyName, propertyType));
}
 
Example 38
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 5 votes vote down vote up
protected ProblemDescriptor createValidationFailedProblem(
    @NotNull final ValidateContext context,
    @NotNull final PsiElement file,
    @NotNull final XmlRule failedRule,
    @NotNull final Exception failure
) {

    return context.getManager().createProblemDescriptor(
        file,
        "XmlRule '" + failedRule.getID() + "' has failed to validate: " + failure.getMessage(),
        true,
        ProblemHighlightType.GENERIC_ERROR,
        context.isOnTheFly()
    );
}
 
Example 39
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 5 votes vote down vote up
@NotNull
protected ProblemHighlightType computePriority(@NotNull final XmlRule rule) {
    switch (rule.getPriority()) {
        case LOW:
            return ProblemHighlightType.WEAK_WARNING;
        default:
            return ProblemHighlightType.ERROR;
    }
}
 
Example 40
Project: intellij-plugin   File: CoffigYamlAnnotator.java   Source Code and License 5 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) {
    if (isConfigFile(psiElement) && psiElement instanceof YAMLKeyValue && isYamlLeaf(psiElement)) {
        if (hasNoConfigurationObject(psiElement) && hasNoExplicitReference(psiElement)) {
            TextRange range = new TextRange(psiElement.getTextRange().getStartOffset(), psiElement.getTextRange().getStartOffset() + ((YAMLKeyValue) psiElement).getKeyText().length());
            Annotation warningAnnotation = annotationHolder.createWarningAnnotation(range, "Unused configuration property");
            warningAnnotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
        }
    }
}
 
Example 41
Project: Android-Room-Support-Plugin-For-Android-Studio   File: RoomQueryCodeInspection.java   Source Code and License 5 votes vote down vote up
private void RunInsertQueryCodeInspection(PsiMethod method, ProblemsHolder holder) {
    if (method.getParameterList().getParameters().length == 0) {
        holder.registerProblem(method.getModifierList(),
                "Error: Method annotated with @Insert but does not have any parameters to insert."
                , ProblemHighlightType.GENERIC_ERROR);
    }
}
 
Example 42
Project: Android-Room-Support-Plugin-For-Android-Studio   File: RoomQueryCodeInspection.java   Source Code and License 5 votes vote down vote up
private void RunDeleteQueryCodeInspection(PsiMethod method, ProblemsHolder holder) {
    if (method.getParameterList().getParameters().length == 0) {
        holder.registerProblem(method.getModifierList(),
                "Error: Method annotated with @Delete but does not have any parameters to delete."
                , ProblemHighlightType.GENERIC_ERROR);
    }
}
 
Example 43
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 44
Project: dotplugin   File: DotAnnotator.java   Source Code and License 5 votes vote down vote up
/**
 * The method annotates all nodes which are used in edges but not declared explicitly
 *
 * @param element element you would like to annotate
 * @param holder  annotation holder
 */
@Override
public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
    if (element instanceof DotDotgraphStmtImpl) {
        for (DotId id : getNotMentionedNodeIds(element)) {
            TextRange range = new TextRange(id.getTextRange().getStartOffset(),
                    id.getTextRange().getEndOffset());
            Annotation annotation = holder.createInfoAnnotation(range, "No such such node specified in graph");
            annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
        }

    }

}
 
Example 45
Project: intellij-ce-playground   File: GroovyTypeCheckVisitor.java   Source Code and License 5 votes vote down vote up
private void processResult(@NotNull ConversionResult result,
                           @NotNull PsiElement elementToHighlight,
                           @NotNull @PropertyKey(resourceBundle = GroovyBundle.BUNDLE) String messageKey,
                           @NotNull PsiType lType,
                           @NotNull PsiType rType) {
  if (result == ConversionResult.OK) return;
  registerError(
    elementToHighlight,
    GroovyBundle.message(messageKey, rType.getPresentableText(), lType.getPresentableText()),
    LocalQuickFix.EMPTY_ARRAY,
    result == ConversionResult.ERROR ? ProblemHighlightType.GENERIC_ERROR : ProblemHighlightType.GENERIC_ERROR_OR_WARNING
  );
}
 
Example 46
Project: intellij-ce-playground   File: JavacQuirksInspectionVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public void visitIdentifier(PsiIdentifier identifier) {
  super.visitIdentifier(identifier);
  if ("_".equals(identifier.getText()) &&
      mySdkVersion != null && mySdkVersion.isAtLeast(JavaSdkVersion.JDK_1_8) &&
      myLanguageLevel.isLessThan(LanguageLevel.JDK_1_9)) {
    final String message = JavaErrorMessages.message("underscore.identifier.warn");
    myHolder.registerProblem(identifier, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
  }
}
 
Example 47
Project: intellij-ce-playground   File: ProblemDescriptorImpl.java   Source Code and License 5 votes vote down vote up
public ProblemDescriptorImpl(@NotNull PsiElement startElement,
                             @NotNull PsiElement endElement,
                             @NotNull String descriptionTemplate,
                             LocalQuickFix[] fixes,
                             @NotNull ProblemHighlightType highlightType,
                             boolean isAfterEndOfLine,
                             @Nullable TextRange rangeInElement,
                             boolean onTheFly) {
  this(startElement, endElement, descriptionTemplate, fixes, highlightType, isAfterEndOfLine, rangeInElement, null, onTheFly);
}
 
Example 48
Project: intellij-ce-playground   File: GroovyTypeCheckVisitor.java   Source Code and License 5 votes vote down vote up
private void checkOperator(@NotNull CallInfo<? extends GrBinaryExpression> info) {
  if (hasErrorElements(info.getCall())) return;

  if (isSpockTimesOperator(info.getCall())) return;

  GroovyResolveResult[] results = info.multiResolve();
  GroovyResolveResult resolveResult = info.advancedResolve();

  if (isOperatorWithSimpleTypes(info.getCall(), resolveResult)) return;

  if (!checkCannotInferArgumentTypes(info)) return;

  if (resolveResult.getElement() != null) {
    checkMethodApplicability(resolveResult, true, info);
  }
  else if (results.length > 0) {
    for (GroovyResolveResult result : results) {
      if (!checkMethodApplicability(result, false, info)) return;
    }

    registerError(
      info.getElementToHighlight(),
      ProblemHighlightType.GENERIC_ERROR,
      GroovyBundle.message("method.call.is.ambiguous")
    );
  }
}
 
Example 49
Project: intellij-ce-playground   File: ProblemDescriptorImpl.java   Source Code and License 5 votes vote down vote up
public ProblemDescriptorImpl(@NotNull PsiElement startElement,
                             @NotNull PsiElement endElement,
                             @NotNull String descriptionTemplate,
                             LocalQuickFix[] fixes,
                             @NotNull ProblemHighlightType highlightType,
                             boolean isAfterEndOfLine,
                             @Nullable TextRange rangeInElement,
                             final boolean tooltip,
                             @Nullable HintAction hintAction,
                             boolean onTheFly) {
  super(startElement, endElement, descriptionTemplate, fixes, highlightType, isAfterEndOfLine, rangeInElement, tooltip, onTheFly);
  myHintAction = hintAction;
}
 
Example 50
Project: intellij-ce-playground   File: BaseInspectionVisitor.java   Source Code and License 5 votes vote down vote up
protected void registerError(@NotNull PsiElement location,
                             ProblemHighlightType highlightType,
                             Object... args) {
  final LocalQuickFix[] fix = createFixes(location);
  final String description = StringUtil.notNullize(inspection.buildErrorString(args));
  registerError(location, description, fix, highlightType);
}
 
Example 51
Project: intellij-ce-playground   File: PyPropertyDefinitionInspection.java   Source Code and License 5 votes vote down vote up
private void checkForSelf(PyParameterList paramList) {
  PyParameter[] parameters = paramList.getParameters();
  final PyClass cls = PsiTreeUtil.getParentOfType(paramList, PyClass.class);
  if (cls != null && cls.isSubclass("type")) return;
  if (parameters.length > 0 && !PyNames.CANONICAL_SELF.equals(parameters[0].getName())) {
    registerProblem(
      parameters[0], PyBundle.message("INSP.accessor.first.param.is.$0", PyNames.CANONICAL_SELF), ProblemHighlightType.WEAK_WARNING,
      null,
      new RenameParameterQuickFix(PyNames.CANONICAL_SELF));
  }
}
 
Example 52
Project: intellij-ce-playground   File: PyShadowingNamesInspection.java   Source Code and License 5 votes vote down vote up
private void processElement(@NotNull PsiNameIdentifierOwner element) {
  final ScopeOwner owner = ScopeUtil.getScopeOwner(element);
  if (owner instanceof PyClass) {
    return;
  }
  final String name = element.getName();
  if (name != null) {
    final PsiElement identifier = element.getNameIdentifier();
    final PsiElement problemElement = identifier != null ? identifier : element;
    if ("_".equals(name)) {
      return;
    }
    if (owner != null) {
      final ScopeOwner nextOwner = ScopeUtil.getScopeOwner(owner);
      if (nextOwner != null) {
        final ResolveProcessor processor = new ResolveProcessor(name);
        PyResolveUtil.scopeCrawlUp(processor, nextOwner, null, name, null, null);
        final PsiElement resolved = processor.getResult();
        if (resolved != null) {
          final PyComprehensionElement comprehension = PsiTreeUtil.getParentOfType(resolved, PyComprehensionElement.class);
          if (comprehension != null && PyUtil.isOwnScopeComprehension(comprehension)) {
            return;
          }
          final Scope scope = ControlFlowCache.getScope(owner);
          if (scope.isGlobal(name) || scope.isNonlocal(name)) {
            return;
          }
          registerProblem(problemElement, String.format("Shadows name '%s' from outer scope", name),
                          ProblemHighlightType.WEAK_WARNING, null, new PyRenameElementQuickFix());
        }
      }
    }
  }
}
 
Example 53
Project: intellij-ce-playground   File: PyDeprecationInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void visitPyReferenceExpression(PyReferenceExpression node) {
  final PyExceptPart exceptPart = PsiTreeUtil.getParentOfType(node, PyExceptPart.class);
  if (exceptPart != null) {
    final PyExpression exceptClass = exceptPart.getExceptClass();
    if (exceptClass != null && "ImportError".equals(exceptClass.getText())) return;
  }
  final PsiPolyVariantReference reference = node.getReference(getResolveContext());
  if (reference == null) return;
  final PsiElement resolveResult = reference.resolve();
  final PyFromImportStatement importStatement = PsiTreeUtil.getParentOfType(node, PyFromImportStatement.class);
  if (importStatement != null) {
    final PsiElement element = importStatement.resolveImportSource();
    if (resolveResult != null && element != resolveResult.getContainingFile()) return;
  }
  String deprecationMessage = null;
  if (resolveResult instanceof PyFunction) {
    deprecationMessage = ((PyFunction) resolveResult).getDeprecationMessage();
  }
  else if (resolveResult instanceof PyFile) {
    deprecationMessage = ((PyFile)resolveResult).getDeprecationMessage();
  }
  if (deprecationMessage != null) {
    ASTNode nameElement = node.getNameElement();
    registerProblem(nameElement == null ? node : nameElement.getPsi(), deprecationMessage, ProblemHighlightType.LIKE_DEPRECATED);
  }
}
 
Example 54
Project: intellij-ce-playground   File: PyInconsistentIndentationInspection.java   Source Code and License 5 votes vote down vote up
private void reportProblem(final String descriptionTemplate, final int problemStart, final int problemLength) {
  PsiElement elt = myFile.findElementAt(problemStart);
  int startOffset = problemStart - elt.getTextRange().getStartOffset();
  int endOffset = startOffset + problemLength;
  myProblems.add(myManager.createProblemDescriptor(elt, new TextRange(startOffset, endOffset),
                                                   descriptionTemplate,
                                                   ProblemHighlightType.GENERIC_ERROR_OR_WARNING, myOnTheFly,
                                                   new ConvertIndentsFix(false), new ConvertIndentsFix(true)));
}
 
Example 55
Project: intellij-ce-playground   File: PyUnboundLocalVariableInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void visitPyNonlocalStatement(final PyNonlocalStatement node) {
  for (PyTargetExpression var : node.getVariables()) {
    final String name = var.getName();
    final ScopeOwner owner = ScopeUtil.getDeclarationScopeOwner(var, name);
    if (owner == null || owner instanceof PyFile) {
      registerProblem(var, PyBundle.message("INSP.unbound.nonlocal.variable", name),
                      ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    }
  }
}
 
Example 56
Project: intellij-ce-playground   File: GroovyTypeCheckVisitor.java   Source Code and License 5 votes vote down vote up
@Override
public void visitCastExpression(GrTypeCastExpression expression) {
  super.visitCastExpression(expression);

  final GrExpression operand = expression.getOperand();
  if (operand == null) return;
  final PsiType actualType = operand.getType();
  if (actualType == null) return;

  if (expression.getCastTypeElement() == null) return;
  final PsiType expectedType = expression.getCastTypeElement().getType();
  
  final ConversionResult result = TypesUtil.canCast(expectedType, actualType, expression);
  if (result == ConversionResult.OK) return;
  final ProblemHighlightType highlightType = result == ConversionResult.ERROR
                                             ? ProblemHighlightType.GENERIC_ERROR
                                             : ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
  final String message = GroovyBundle.message(
    "cannot.cast",
    actualType.getPresentableText(),
    expectedType.getPresentableText()
  );
  registerError(
    expression,
    highlightType,
    message
  );
}
 
Example 57
Project: intellij-ce-playground   File: PyTypeCheckerInspection.java   Source Code and License 5 votes vote down vote up
@NotNull
private Map<PyExpression, Pair<String, ProblemHighlightType>> checkMapping(@Nullable PyExpression receiver,
                                                                           @NotNull Map<PyExpression, PyNamedParameter> mapping) {
  final Map<PyExpression, Pair<String, ProblemHighlightType>> problems = new HashMap<PyExpression, Pair<String, ProblemHighlightType>>();
  final Map<PyGenericType, PyType> substitutions = new LinkedHashMap<PyGenericType, PyType>();
  boolean genericsCollected = false;
  for (Map.Entry<PyExpression, PyNamedParameter> entry : mapping.entrySet()) {
    final PyNamedParameter param = entry.getValue();
    final PyExpression arg = entry.getKey();
    if (param.isPositionalContainer() || param.isKeywordContainer()) {
      continue;
    }
    final PyType paramType = myTypeEvalContext.getType(param);
    if (paramType == null) {
      continue;
    }
    final PyType argType = myTypeEvalContext.getType(arg);
    if (!genericsCollected) {
      substitutions.putAll(PyTypeChecker.unifyReceiver(receiver, myTypeEvalContext));
      genericsCollected = true;
    }
    final Pair<String, ProblemHighlightType> problem = checkTypes(paramType, argType, myTypeEvalContext, substitutions);
    if (problem != null) {
      problems.put(arg, problem);

    }
  }
  return problems;
}
 
Example 58
Project: intellij-ce-playground   File: RegExpAnnotator.java   Source Code and License 5 votes vote down vote up
public void visitRegExpProperty(RegExpProperty property) {
  final ASTNode category = property.getCategoryNode();
  if (category == null) {
    return;
  }
  if(!myLanguageHosts.isValidCategory(category.getPsi(), category.getText())) {
    final Annotation a = myHolder.createErrorAnnotation(category, "Unknown character category");
    if (a != null) {
      // IDEA-9381
      a.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
    }
  }
}
 
Example 59
Project: intellij-ce-playground   File: RegExpAnnotator.java   Source Code and License 5 votes vote down vote up
public void visitRegExpBackref(final RegExpBackref backref) {
  final RegExpGroup group = backref.resolve();
  if (group == null) {
    final Annotation a = myHolder.createErrorAnnotation(backref, "Unresolved back reference");
    if (a != null) {
      // IDEA-9381
      a.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
    }
  }
  else if (PsiTreeUtil.isAncestor(group, backref, true)) {
    myHolder.createWarningAnnotation(backref, "Back reference is nested into the capturing group it refers to");
  }
}
 
Example 60
Project: intellij-ce-playground   File: RegExpAnnotator.java   Source Code and License 5 votes vote down vote up
@Override
public void visitPosixBracketExpression(RegExpPosixBracketExpression posixBracketExpression) {
  final String className = posixBracketExpression.getClassName();
  if (!POSIX_CHARACTER_CLASSES.contains(className)) {
    final Annotation annotation = myHolder.createErrorAnnotation(posixBracketExpression, "Unknown POSIX character class");
    if (annotation != null) {
      annotation.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
    }
  }
}