use of com.intellij.psi.PsiElementVisitor in project intellij-community by JetBrains.
the class GlobalMatchingVisitor method match.
/**
* Identifies the match between given element of program tree and pattern element
*
* @param el1 the pattern for matching
* @param el2 the tree element for matching
* @return true if equal and false otherwise
*/
@Override
public boolean match(final PsiElement el1, final PsiElement el2) {
if (el1 == el2)
return true;
if (el1 == null) {
// absence of pattern element is match
return true;
}
if (el2 == null) {
// absence of match element needs check if allowed.
return allowsAbsenceOfMatch(el1);
}
// copy changed data to local stack
PsiElement prevElement = myElement;
myElement = el2;
try {
PsiElementVisitor visitor = getVisitorForElement(el1);
if (visitor != null) {
el1.accept(visitor);
}
} catch (ClassCastException ex) {
myResult = false;
} finally {
myElement = prevElement;
}
return myResult;
}
use of com.intellij.psi.PsiElementVisitor in project intellij-community by JetBrains.
the class AlphaUnsortedPropertiesFileInspection method buildVisitor.
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new PsiElementVisitor() {
@Override
public void visitFile(PsiFile file) {
final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(file);
if (!(propertiesFile instanceof PropertiesFileImpl)) {
return;
}
for (AlphaUnsortedPropertiesFileInspectionSuppressor filter : AlphaUnsortedPropertiesFileInspectionSuppressor.EP_NAME.getExtensions()) {
if (filter.suppressInspectionFor(propertiesFile)) {
return;
}
}
final ResourceBundle resourceBundle = propertiesFile.getResourceBundle();
final String resourceBundleBaseName = resourceBundle.getBaseName();
if (!isResourceBundleAlphaSortedExceptOneFile(resourceBundle, propertiesFile)) {
final List<PropertiesFile> allFiles = resourceBundle.getPropertiesFiles();
holder.registerProblem(file, String.format(MESSAGE_TEMPLATE_WHOLE_RESOURCE_BUNDLE, resourceBundleBaseName), ProblemHighlightType.INFO, new PropertiesSorterQuickFix(true, allFiles.toArray(new PropertiesFile[allFiles.size()])));
return;
}
if (!propertiesFile.isAlphaSorted()) {
holder.registerProblem(file, "Properties file is alphabetically unsorted", ProblemHighlightType.INFO, new PropertiesSorterQuickFix(true, propertiesFile));
}
}
};
}
use of com.intellij.psi.PsiElementVisitor in project intellij-community by JetBrains.
the class RestStructureViewElement method getChildren.
@NotNull
public StructureViewTreeElement[] getChildren() {
final Set<RestElement> childrenElements = new LinkedHashSet<>();
myElement.acceptChildren(new PsiElementVisitor() {
@Override
public void visitElement(PsiElement element) {
if (element instanceof RestTitle && ((RestTitle) element).getName() != null)
childrenElements.add((RestElement) element);
else
element.acceptChildren(this);
}
});
StructureViewTreeElement[] children = new StructureViewTreeElement[childrenElements.size()];
int i = 0;
for (RestElement element : childrenElements) {
children[i] = new RestStructureViewElement(element);
i += 1;
}
return children;
}
use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.
the class SummerTimeUnsafeTimeManipulationInspector method buildVisitor.
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new BasePhpElementVisitor() {
@Override
public void visitPhpBinaryExpression(@NotNull BinaryExpression expression) {
if (targetOperations.contains(expression.getOperationType())) {
final PsiElement left = expression.getLeftOperand();
final PsiElement right = expression.getRightOperand();
if (right != null && this.isTargetMagicNumber(right) && this.isTargetContext(right)) {
if (!this.isTestContext(expression)) {
holder.registerProblem(expression, message);
}
} else if (left != null && this.isTargetMagicNumber(left) && this.isTargetContext(left)) {
if (!this.isTestContext(expression)) {
holder.registerProblem(expression, message);
}
}
}
}
@Override
public void visitPhpSelfAssignmentExpression(@NotNull SelfAssignmentExpression expression) {
if (targetAssignments.contains(expression.getOperationType())) {
final PsiElement value = expression.getValue();
if (value != null && this.isTargetMagicNumber(value) && !this.isTestContext(expression)) {
holder.registerProblem(expression, message);
}
}
}
private boolean isTargetContext(@NotNull PsiElement magicNumber) {
boolean result = magicNumber.textMatches("86400");
if (!result) {
PsiElement expression = magicNumber.getParent();
while (expression instanceof ParenthesizedExpression || expression instanceof BinaryExpression) {
expression = expression.getParent();
}
result = PsiTreeUtil.findChildrenOfType(expression, PhpExpression.class).stream().filter(OpenapiTypesUtil::isNumber).anyMatch(candidate -> {
final String text = candidate.getText();
return text.equals("60") || text.endsWith("3600");
});
}
return result;
}
private boolean isTargetMagicNumber(@NotNull PsiElement candidate) {
boolean result = false;
if (OpenapiTypesUtil.isNumber(candidate)) {
result = candidate.textMatches("24") || candidate.textMatches("86400");
}
return result;
}
};
}
use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.
the class ForeachSourceInspector method buildVisitor.
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
return new BasePhpElementVisitor() {
@Override
public void visitPhpForeach(@NotNull ForeachStatement foreach) {
final PsiElement source = ExpressionSemanticUtil.getExpressionTroughParenthesis(foreach.getArray());
if (source instanceof PhpTypedElement && !isEnsuredByPyParentIf(foreach, source)) {
this.analyseContainer(source);
}
}
/* should cover is_array/is_iterable in direct parent if of the loop, while PS types resolving gets improved */
private boolean isEnsuredByPyParentIf(@NotNull ForeachStatement foreach, @NotNull PsiElement source) {
boolean result = false;
if (foreach.getPrevPsiSibling() == null) {
final PsiElement ifCandidate = foreach.getParent() instanceof GroupStatement ? foreach.getParent().getParent() : null;
final PsiElement conditions;
if (ifCandidate instanceof If) {
conditions = ((If) ifCandidate).getCondition();
} else if (ifCandidate instanceof ElseIf) {
conditions = ((ElseIf) ifCandidate).getCondition();
} else {
conditions = null;
}
if (conditions != null) {
for (final PsiElement candidate : PsiTreeUtil.findChildrenOfType(conditions, source.getClass())) {
if (OpeanapiEquivalenceUtil.areEqual(candidate, source)) {
final PsiElement call = candidate.getParent() instanceof ParameterList ? candidate.getParent().getParent() : null;
if (OpenapiTypesUtil.isFunctionReference(call)) {
final String functionName = ((FunctionReference) call).getName();
if (functionName != null && (functionName.equals("is_array") || functionName.equals("is_iterable"))) {
result = true;
break;
}
}
}
}
}
}
return result;
}
private void analyseContainer(@NotNull PsiElement container) {
final PhpType resolvedType = OpenapiResolveUtil.resolveType((PhpTypedElement) container, container.getProject());
if (resolvedType == null) {
return;
}
final Set<String> types = new HashSet<>();
resolvedType.filterUnknown().getTypes().forEach(t -> types.add(Types.getType(t)));
if (types.isEmpty()) {
/* false-positives: pre-defined variables */
if (container instanceof Variable) {
final String variableName = ((Variable) container).getName();
if (ExpressionCostEstimateUtil.predefinedVars.contains(variableName)) {
return;
}
}
if (REPORT_UNRECOGNIZED_TYPES) {
holder.registerProblem(container, patternNotRecognized, ProblemHighlightType.WEAK_WARNING);
}
return;
}
/* false-positives: multiple return types checked only in function/method; no global context */
final PsiElement scope = ExpressionSemanticUtil.getBlockScope(container);
if (types.size() > 1 && !(scope instanceof Function)) {
types.clear();
return;
}
/* false-positives: mixed parameter type, parameter overridden before foreach */
if (types.size() > 1 && scope instanceof Function && container instanceof Variable) {
final String parameter = ((Variable) container).getName();
final PhpEntryPointInstruction start = ((Function) scope).getControlFlow().getEntryPoint();
final PhpAccessVariableInstruction[] uses = PhpControlFlowUtil.getFollowingVariableAccessInstructions(start, parameter, false);
for (final PhpAccessVariableInstruction instruction : uses) {
final PhpPsiElement expression = instruction.getAnchor();
/* when matched itself, stop processing */
if (expression == container) {
break;
}
final PsiElement parent = expression.getParent();
if (parent instanceof AssignmentExpression) {
final PsiElement matchCandidate = ((AssignmentExpression) parent).getVariable();
if (matchCandidate != null && OpeanapiEquivalenceUtil.areEqual(matchCandidate, container)) {
types.clear();
return;
}
}
}
}
/* false-positives: array type parameter declaration adds mixed */
if (types.size() > 1 && scope instanceof Function && container instanceof ArrayAccessExpression) {
final PsiElement candidate = ((ArrayAccessExpression) container).getValue();
if (candidate instanceof Variable && types.contains(Types.strMixed) && types.contains(Types.strArray)) {
types.remove(Types.strMixed);
}
}
/* gracefully request to specify exact types which can appear (mixed, object) */
if (types.contains(Types.strMixed)) {
/* false-positive: mixed definitions from stub functions */
boolean isStubFunction = false;
if (OpenapiTypesUtil.isFunctionReference(container)) {
final PsiElement function = OpenapiResolveUtil.resolveReference((FunctionReference) container);
final String filePath = function == null ? null : function.getContainingFile().getVirtualFile().getCanonicalPath();
isStubFunction = filePath != null && filePath.contains(".jar!") && filePath.contains("/stubs/");
}
/* false-positive: mixed definition from array type */
if (!isStubFunction && !types.contains(Types.strArray) && REPORT_MIXED_TYPES) {
final String message = String.format(patternMixedTypes, Types.strMixed);
holder.registerProblem(container, message, ProblemHighlightType.WEAK_WARNING);
}
types.remove(Types.strMixed);
}
if (types.contains(Types.strObject)) {
if (REPORT_MIXED_TYPES) {
final String message = String.format(patternMixedTypes, Types.strObject);
holder.registerProblem(container, message, ProblemHighlightType.WEAK_WARNING);
}
types.remove(Types.strObject);
}
/* respect patter when returned array and bool|null for indicating failures*/
if (types.size() == 2 && types.contains(Types.strArray)) {
types.remove(Types.strBoolean);
types.remove(Types.strNull);
}
/* do not process foreach-compatible types */
types.remove(Types.strArray);
types.remove(Types.strIterable);
types.remove("\\Traversable");
types.remove("\\Iterator");
types.remove("\\IteratorAggregate");
/* don't process mysterious empty set type */
types.remove(Types.strEmptySet);
/* iterate rest of types */
if (!types.isEmpty()) {
final PhpIndex index = PhpIndex.getInstance(holder.getProject());
for (final String type : types) {
/* report if scalar type is met */
if (!type.startsWith("\\")) {
holder.registerProblem(container, String.format(patternScalar, type), ProblemHighlightType.GENERIC_ERROR);
continue;
}
/* check classes for the Traversable interface in the inheritance chain */
final List<PhpClass> classes = OpenapiResolveUtil.resolveClassesAndInterfacesByFQN(type, index);
if (!classes.isEmpty()) {
boolean hasTraversable = false;
for (final PhpClass clazz : classes) {
final Set<PhpClass> interfaces = InterfacesExtractUtil.getCrawlInheritanceTree(clazz, false);
if (!interfaces.isEmpty()) {
hasTraversable = interfaces.stream().anyMatch(i -> i.getFQN().equals("\\Traversable"));
interfaces.clear();
if (hasTraversable) {
break;
}
}
}
classes.clear();
if (!hasTraversable) {
holder.registerProblem(container, String.format(patternObject, type));
}
}
}
types.clear();
}
}
};
}
Aggregations