diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaPredefinedConfigurations.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaPredefinedConfigurations.java index c6b99923ff42..eaa5fd5b83c9 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaPredefinedConfigurations.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaPredefinedConfigurations.java @@ -4,6 +4,7 @@ package com.intellij.structuralsearch; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.structuralsearch.plugin.ui.Configuration; +import org.jetbrains.annotations.NotNull; import static com.intellij.structuralsearch.PredefinedConfigurationUtil.createSearchTemplateInfo; import static com.intellij.structuralsearch.PredefinedConfigurationUtil.createSearchTemplateInfoSimple; @@ -12,6 +13,7 @@ import static com.intellij.structuralsearch.PredefinedConfigurationUtil.createSe * @author Bas Leijdekkers */ final class JavaPredefinedConfigurations { + @NotNull public static Configuration[] createPredefinedTemplates() { return new Configuration[] { // Expression patterns diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaReplaceHandler.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaReplaceHandler.java index 5b0fa61cee4a..11fde5e83c95 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaReplaceHandler.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaReplaceHandler.java @@ -359,7 +359,7 @@ public class JavaReplaceHandler extends StructuralReplaceHandler { } final List unmatchedAnnotations = originalModifierList.getUserData(GlobalMatchingVisitor.UNMATCHED_ELEMENTS_KEY); final PsiElement anchor = replacementModifierList.getFirstChild(); - boolean append = (anchor == null); + boolean append = anchor == null; PsiElement child = originalModifierList.getFirstChild(); while (child != null) { if (child instanceof PsiKeyword) { @@ -417,7 +417,7 @@ public class JavaReplaceHandler extends StructuralReplaceHandler { } @Override - public void replace(final ReplacementInfo info, ReplaceOptions options) { + public void replace(final @NotNull ReplacementInfo info, @NotNull ReplaceOptions options) { final PsiElement elementToReplace = StructuralSearchUtil.getPresentableElement(info.getMatch(0)); if (elementToReplace == null) { return; @@ -689,7 +689,7 @@ public class JavaReplaceHandler extends StructuralReplaceHandler { } @Override - public void postProcess(PsiElement affectedElement, ReplaceOptions options) { + public void postProcess(@NotNull PsiElement affectedElement, @NotNull ReplaceOptions options) { if (!affectedElement.isValid()) { return; } diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaStructuralSearchProfile.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaStructuralSearchProfile.java index 4216c17f88d1..420c6b3ea842 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaStructuralSearchProfile.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/JavaStructuralSearchProfile.java @@ -56,7 +56,7 @@ import java.util.stream.Collectors; public class JavaStructuralSearchProfile extends StructuralSearchProfile { private static final Key> PARAMETER_CONTEXT = new Key<>("PARAMETER_CONTEXT"); - private static final Key PARAMETER_LENGTH = new Key<>(("PARAMETER_LENGTH")); + private static final Key PARAMETER_LENGTH = new Key<>("PARAMETER_LENGTH"); public static final PatternContext DEFAULT_CONTEXT = new PatternContext("default", "Default"); public static final PatternContext MEMBER_CONTEXT = new PatternContext("member", "Class Member"); @@ -73,7 +73,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { ContainerUtil.set(MatchOptions.MODIFIER_ANNOTATION_NAME, MatchOptions.INSTANCE_MODIFIER_NAME, PsiModifier.PACKAGE_LOCAL); @Override - public String getText(PsiElement match, int start, int end) { + public @NotNull String getText(@NotNull PsiElement match, int start, int end) { if (match instanceof PsiIdentifier) { final PsiElement parent = match.getParent(); if (parent instanceof PsiJavaCodeReferenceElement && !(parent instanceof PsiExpression)) { @@ -97,7 +97,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { @Override @NotNull - public String getTypedVarString(final PsiElement element) { + public String getTypedVarString(final @NotNull PsiElement element) { String text; if (element instanceof PsiReceiverParameter) { @@ -131,7 +131,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public String getMeaningfulText(PsiElement element) { + public String getMeaningfulText(@NotNull PsiElement element) { if (element instanceof PsiReferenceExpression && ((PsiReferenceExpression)element).getQualifierExpression() != null) { final PsiElement resolve = ((PsiReferenceExpression)element).resolve(); if (resolve instanceof PsiClass) return element.getText(); @@ -139,7 +139,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { final PsiElement referencedElement = ((PsiReferenceExpression)element).getReferenceNameElement(); final String text = referencedElement != null ? referencedElement.getText() : ""; - if (resolve == null && text.length() > 0 && Character.isUpperCase(text.charAt(0))) { + if (resolve == null && !text.isEmpty() && Character.isUpperCase(text.charAt(0))) { return element.getText(); } return text; @@ -149,31 +149,30 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { @Override @Nullable - public String getAlternativeText(PsiElement node, String previousText) { + public String getAlternativeText(@NotNull PsiElement node, @NotNull String previousText) { // Short class name is matched with fully qualified name - if(node instanceof PsiJavaCodeReferenceElement || node instanceof PsiClass) { + if (node instanceof PsiJavaCodeReferenceElement || node instanceof PsiClass) { final PsiElement element = (node instanceof PsiJavaCodeReferenceElement) ? ((PsiJavaCodeReferenceElement)node).resolve() : node; if (element instanceof PsiClass) { String text = ((PsiClass)element).getQualifiedName(); - if (text != null && text.equals(previousText)) { + if (previousText.equals(text)) { text = ((PsiClass)element).getName(); } - if (text != null) { - return text; - } + return text; } - } else if (node instanceof PsiLiteralExpression || node instanceof PsiComment) { + } + else if (node instanceof PsiLiteralExpression || node instanceof PsiComment) { return node.getText(); } return null; } @Override - public PsiElement updateCurrentNode(PsiElement targetNode) { + public @NotNull PsiElement updateCurrentNode(@NotNull PsiElement targetNode) { if (targetNode instanceof PsiCodeBlock && ((PsiCodeBlock)targetNode).getStatementCount() == 1) { PsiElement targetNodeParent = targetNode.getParent(); if (targetNodeParent instanceof PsiBlockStatement) { @@ -188,7 +187,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public PsiElement extendMatchedByDownUp(PsiElement targetNode) { + public @NotNull PsiElement extendMatchedByDownUp(@NotNull PsiElement targetNode) { if (targetNode instanceof PsiIdentifier) { targetNode = targetNode.getParent(); final PsiElement parent = targetNode.getParent(); @@ -198,7 +197,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public PsiElement extendMatchOnePsiFile(PsiElement file) { + public @NotNull PsiElement extendMatchOnePsiFile(@NotNull PsiElement file) { if (file instanceof PsiIdentifier) { // Searching in previous results file = file.getParent(); @@ -208,7 +207,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { @NotNull @Override - public PsiElement getPresentableElement(PsiElement element) { + public PsiElement getPresentableElement(@NotNull PsiElement element) { element = super.getPresentableElement(element); if (element instanceof PsiReferenceExpression) { final PsiElement parent = element.getParent(); @@ -227,7 +226,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void compile(PsiElement[] elements, @NotNull GlobalCompilingVisitor globalVisitor) { + public void compile(PsiElement @NotNull [] elements, @NotNull GlobalCompilingVisitor globalVisitor) { new JavaCompilingVisitor(globalVisitor).compile(elements); } @@ -264,7 +263,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { @NotNull @Override - public List getCustomPredicates(MatchVariableConstraint constraint, String name, MatchOptions options) { + public List getCustomPredicates(@NotNull MatchVariableConstraint constraint, @NotNull String name, @NotNull MatchOptions options) { final List result = new SmartList<>(); if (!StringUtil.isEmptyOrSpaces(constraint.getNameOfExprType())) { @@ -375,7 +374,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { return result; } - private static boolean shouldTryExpressionPattern(List elements) { + private static boolean shouldTryExpressionPattern(@NotNull List elements) { if (elements.size() >= 1 && elements.size() <= 3) { final PsiElement firstElement = elements.get(0); if (firstElement instanceof PsiDeclarationStatement) { @@ -391,7 +390,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { return false; } - private static boolean shouldTryClassPattern(List elements) { + private static boolean shouldTryClassPattern(@NotNull List elements) { if (elements.isEmpty()) { return false; } @@ -447,7 +446,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { @NotNull @Override - public PsiCodeFragment createCodeFragment(Project project, String text, String contextId) { + public PsiCodeFragment createCodeFragment(@NotNull Project project, @NotNull String text, String contextId) { final PsiCodeFragmentImpl fragment = MEMBER_CONTEXT.getId().equals(contextId) ? (PsiCodeFragmentImpl)JavaCodeFragmentFactory.getInstance(project).createMemberCodeFragment(text, null, true) @@ -457,7 +456,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public String getCodeFragmentText(PsiFile fragment) { + public @NotNull String getCodeFragmentText(@NotNull PsiFile fragment) { final List imports = StringUtil.split(((JavaCodeFragment)fragment).importsToString(), ","); final Map importMap = imports.stream().collect(Collectors.toMap(s -> s.substring(s.lastIndexOf('.') + 1), Function.identity())); @@ -493,7 +492,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public boolean shouldShowProblem(PsiErrorElement error) { + public boolean shouldShowProblem(@NotNull PsiErrorElement error) { final String description = error.getErrorDescription(); final PsiElement parent = error.getParent(); @@ -539,7 +538,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void checkSearchPattern(CompiledPattern pattern) { + public void checkSearchPattern(@NotNull CompiledPattern pattern) { final ValidatingVisitor visitor = new ValidatingVisitor(); final NodeIterator nodes = pattern.getNodes(); while (nodes.hasNext()) { @@ -550,7 +549,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void checkReplacementPattern(Project project, ReplaceOptions options) { + public void checkReplacementPattern(@NotNull Project project, @NotNull ReplaceOptions options) { final MatchOptions matchOptions = options.getMatchOptions(); final LanguageFileType fileType = matchOptions.getFileType(); final Language dialect = matchOptions.getDialect(); @@ -629,12 +628,12 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public Configuration[] getPredefinedTemplates() { + public Configuration @NotNull [] getPredefinedTemplates() { return JavaPredefinedConfigurations.createPredefinedTemplates(); } @Override - public void provideAdditionalReplaceOptions(@NotNull PsiElement node, ReplaceOptions options, ReplacementBuilder builder) { + public void provideAdditionalReplaceOptions(@NotNull PsiElement node, @NotNull ReplaceOptions options, @NotNull ReplacementBuilder builder) { node.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(PsiReferenceExpression expression) { @@ -656,7 +655,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { setParameterContext(parameter, parameter.getNameIdentifier(), parameter.getTypeElement()); } - private void setParameterContext(PsiElement element, PsiElement nameIdentifier, @Nullable PsiElement scopeElement) { + private void setParameterContext(@NotNull PsiElement element, PsiElement nameIdentifier, @Nullable PsiElement scopeElement) { final ParameterInfo nameInfo = builder.findParameterization(nameIdentifier); if (nameInfo == null) return; nameInfo.setArgumentContext(false); @@ -689,7 +688,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void handleSubstitution(ParameterInfo info, MatchResult match, StringBuilder result, ReplacementInfo replacementInfo) { + public void handleSubstitution(@NotNull ParameterInfo info, @NotNull MatchResult match, @NotNull StringBuilder result, @NotNull ReplacementInfo replacementInfo) { if (info.getName().equals(match.getName())) { final String replacementString; boolean forceAddingNewLine = false; @@ -784,7 +783,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void handleNoSubstitution(ParameterInfo info, StringBuilder result) { + public void handleNoSubstitution(@NotNull ParameterInfo info, @NotNull StringBuilder result) { final PsiElement element = info.getElement(); final PsiElement prevSibling = PsiTreeUtil.skipWhitespacesBackward(element); if (prevSibling instanceof PsiJavaToken && isRemovableToken(prevSibling)) { @@ -861,11 +860,11 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public boolean isDocCommentOwner(PsiElement match) { + public boolean isDocCommentOwner(@NotNull PsiElement match) { return match instanceof PsiMember; } - private static String handleParameter(ParameterInfo info, ReplacementInfo replacementInfo, int offset, String template) { + private static String handleParameter(@NotNull ParameterInfo info, ReplacementInfo replacementInfo, int offset, String template) { final MatchResult matchResult = replacementInfo.getNamedMatchResult(info.getName()); assert matchResult != null; @@ -923,7 +922,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile { } @Override - public boolean isApplicableConstraint(String constraintName, @Nullable PsiElement variableNode, boolean completePattern, boolean target) { + public boolean isApplicableConstraint(@NotNull String constraintName, @Nullable PsiElement variableNode, boolean completePattern, boolean target) { switch (constraintName) { case UIUtil.TEXT: return !completePattern; case UIUtil.TEXT_HIERARCHY: diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchUtil.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchUtil.java index 4a262be5b3ef..8266d3d940ec 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchUtil.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchUtil.java @@ -7,6 +7,7 @@ import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.tree.IElementType; +import org.jetbrains.annotations.NotNull; /** * @author Bas Leijdekkers @@ -15,7 +16,8 @@ public final class JavaMatchUtil { private JavaMatchUtil() {} - public static String getCommentText(PsiComment comment) { + @NotNull + public static String getCommentText(@NotNull PsiComment comment) { if (comment instanceof PsiDocComment) { final PsiDocComment docComment = (PsiDocComment)comment; final StringBuilder result = new StringBuilder(); diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java index fe0b8a9eee1d..ddde685f2639 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java @@ -661,7 +661,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { } /** Removes parentheses from the element if it is a parenthesized expression. */ - private static PsiElement unwrap(PsiElement element, MatchContext context) { + private static PsiElement unwrap(PsiElement element, @NotNull MatchContext context) { return context.getOptions().isLooseMatching() && element instanceof PsiExpression ? PsiUtil.skipParenthesizedExprDown((PsiExpression)element) : element; @@ -690,7 +690,8 @@ public class JavaMatchingVisitor extends JavaElementVisitor { return 0; } - private static PsiTypeElement getInnermostComponentTypeElement(PsiTypeElement typeElement) { + @NotNull + private static PsiTypeElement getInnermostComponentTypeElement(@NotNull PsiTypeElement typeElement) { PsiElement child = typeElement.getFirstChild(); while (child instanceof PsiTypeElement) { typeElement = (PsiTypeElement)child; @@ -699,6 +700,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { return typeElement; } + @Contract("!null->!null; null->null") private static PsiElement getInnermostComponent(PsiElement element) { if (!(element instanceof PsiTypeElement)) { return element; @@ -721,7 +723,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { return (referenceElement != null) ? referenceElement : getInnermostComponentTypeElement(typeElement); } - private static PsiTypeElement[] getTypeParameters(PsiJavaCodeReferenceElement referenceElement, Boolean replaceDiamondWithExplicitTypes) { + private static PsiTypeElement[] getTypeParameters(@NotNull PsiJavaCodeReferenceElement referenceElement, Boolean replaceDiamondWithExplicitTypes) { final PsiReferenceParameterList referenceElementParameterList = referenceElement.getParameterList(); if (referenceElementParameterList == null) { return null; @@ -758,7 +760,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { return newParameterList == null ? null : newParameterList.getTypeParameterElements(); } - private Boolean shouldReplaceDiamondWithExplicitTypes(PsiElement element) { + private Boolean shouldReplaceDiamondWithExplicitTypes(@NotNull PsiElement element) { if (!(element instanceof PsiJavaCodeReferenceElement)) { return Boolean.TRUE; } @@ -782,7 +784,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { return Boolean.valueOf(!(typeElement.getType() instanceof PsiDiamondType)); } - private boolean matchType(PsiElement patternType, PsiElement matchedType) { + private boolean matchType(@NotNull PsiElement patternType, PsiElement matchedType) { PsiElement patternElement = getInnermostComponent(patternType); PsiElement matchedElement = patternElement instanceof PsiTypeElement && ((PsiTypeElement)patternElement).isInferredType() ? matchedType @@ -816,7 +818,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { if (wildcardType2.isExtends()) { return myMatchingVisitor.match(patternElement.getLastChild(), matchedElement.getLastChild()); } - else if (!wildcardType2.isBounded()) { + else { return myMatchingVisitor.matchOptionally(patternElement.getLastChild(), null); } } @@ -862,13 +864,10 @@ public class JavaMatchingVisitor extends JavaElementVisitor { regExpPredicate = handler.findRegExpPredicate(); if (regExpPredicate != null) { - regExpPredicate.setNodeTextGenerator(new RegExpPredicate.NodeTextGenerator() { - @Override - public String getText(PsiElement element) { - final StringBuilder builder = new StringBuilder(StructuralSearchUtil.getMeaningfulText(element)); - for (int i = 0; i < matchedArrayDimensions; ++i) builder.append("[]"); - return builder.toString(); - } + regExpPredicate.setNodeTextGenerator(element -> { + final StringBuilder builder = new StringBuilder(StructuralSearchUtil.getMeaningfulText(element)); + for (int i = 0; i < matchedArrayDimensions; ++i) builder.append("[]"); + return builder.toString(); }); } fullTypeResult = true; @@ -921,21 +920,24 @@ public class JavaMatchingVisitor extends JavaElementVisitor { } @Contract(pure = true) + @NotNull private static String getText(@NotNull PsiElement element) { String result; if (element instanceof PsiClass) { result = ((PsiClass)element).getQualifiedName(); if (result == null) result = element.getText(); - } else if (element instanceof PsiJavaCodeReferenceElement) { + } + else if (element instanceof PsiJavaCodeReferenceElement) { result = ((PsiJavaCodeReferenceElement)element).getCanonicalText(); - } else { + } + else { result = element.getText(); } final int index = result.indexOf('<'); return index == -1 ? result : result.substring(0, index); } - private boolean matchWithinHierarchy(PsiElement patternElement, PsiElement matchElement, SubstitutionHandler handler) { + private boolean matchWithinHierarchy(@NotNull PsiElement patternElement, PsiElement matchElement, SubstitutionHandler handler) { patternElement = StructuralSearchUtil.getParentIfIdentifier(patternElement); boolean includeInterfaces = true; boolean includeClasses = true; @@ -1028,7 +1030,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { } } - private void matchArrayOrArguments(PsiNewExpression patternExpression, PsiNewExpression matchExpression) { + private void matchArrayOrArguments(@NotNull PsiNewExpression patternExpression, @NotNull PsiNewExpression matchExpression) { final PsiType type1 = patternExpression.getType(); final PsiType type2 = matchExpression.getType(); if (!myMatchingVisitor.setResult(type1 != null && type2 != null && type1.getArrayDimensions() == type2.getArrayDimensions())) return; @@ -1056,14 +1058,14 @@ public class JavaMatchingVisitor extends JavaElementVisitor { } } - private static boolean areZeroLiterals(PsiExpression[] expressions) { + private static boolean areZeroLiterals(PsiExpression @NotNull [] expressions) { for (PsiExpression expression : expressions) { if (!(expression instanceof PsiLiteralExpression) || !expression.getText().equals("0")) return false; } return true; } - private static boolean matchImplicitQualifier(PsiExpression qualifier, PsiElement reference, MatchContext context) { + private static boolean matchImplicitQualifier(@NotNull PsiExpression qualifier, @NotNull PsiElement reference, @NotNull MatchContext context) { final PsiElement target = reference instanceof PsiMethodCallExpression ? ((PsiMethodCallExpression)reference).resolveMethod() : ((PsiReference)reference).resolve(); @@ -1114,7 +1116,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { } } - private boolean matchTypeParameters(PsiCallExpression call1, PsiCallExpression call2) { + private boolean matchTypeParameters(@NotNull PsiCallExpression call1, @NotNull PsiCallExpression call2) { final PsiReferenceParameterList patternParameterList = call1.getTypeArgumentList(); final PsiTypeElement[] patternTypeElements = patternParameterList.getTypeParameterElements(); if (patternTypeElements.length == 0) { @@ -1227,7 +1229,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { myMatchingVisitor.setResult(matchSwitchBlock(expression)); } - private boolean matchSwitchBlock(PsiSwitchBlock switchBlock) { + private boolean matchSwitchBlock(@NotNull PsiSwitchBlock switchBlock) { final PsiSwitchBlock other = (PsiSwitchBlock)myMatchingVisitor.getElement(); if (!myMatchingVisitor.match(switchBlock.getExpression(), other.getExpression())) { @@ -1257,7 +1259,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { myMatchingVisitor.setResult(matchLabelStatement(statement, (PsiSwitchLabelStatementBase)myMatchingVisitor.getElement())); } - private boolean matchLabelStatement(PsiSwitchLabelStatementBase statement1, PsiSwitchLabelStatementBase statement2) { + private boolean matchLabelStatement(@NotNull PsiSwitchLabelStatementBase statement1, @NotNull PsiSwitchLabelStatementBase statement2) { final PsiExpressionList values1 = statement1.getCaseValues(); final PsiExpressionList values2 = statement2.getCaseValues(); if (statement1.isDefaultCase() && !statement2.isDefaultCase()) { @@ -1274,7 +1276,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { return body.length == 0 || myMatchingVisitor.matchSequentially(body, getBody(statement2)); } - private static PsiElement[] getBody(PsiSwitchLabelStatementBase switchLabelStatement) { + private static PsiElement @NotNull [] getBody(@NotNull PsiSwitchLabelStatementBase switchLabelStatement) { final List result = new SmartList<>(); if (switchLabelStatement instanceof PsiSwitchLabeledRuleStatement) { final PsiStatement body = ((PsiSwitchLabeledRuleStatement)switchLabelStatement).getBody(); @@ -1689,7 +1691,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { } } - private boolean matchAnnotations(PsiElement pattern, PsiElement matched) { + private boolean matchAnnotations(@NotNull PsiElement pattern, PsiElement matched) { // can't use PsiAnnotationOwner api because it is not implemented completely yet (see e.g. ClsTypeParameterImpl) final PsiAnnotation[] annotations = PsiTreeUtil.getChildrenOfType(pattern, PsiAnnotation.class); if (annotations == null) { @@ -1822,7 +1824,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { } @Nullable - private T getExpression(Class aClass, PsiExpression patternExpression) { + private T getExpression(@NotNull Class aClass, @NotNull PsiExpression patternExpression) { PsiElement other = myMatchingVisitor.getElement(); if (!myMatchingVisitor.setResult(other instanceof PsiExpression)) { return null; @@ -1833,7 +1835,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor { return myMatchingVisitor.setResult(aClass.isInstance(other)) ? aClass.cast(other) : null; } - private T getElement(Class aClass) { + private T getElement(@NotNull Class aClass) { final PsiElement other = myMatchingVisitor.getElement(); return myMatchingVisitor.setResult(aClass.isInstance(other)) ? aClass.cast(other) : null; } diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java index b8095fadd086..9391e78e0101 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java @@ -38,17 +38,18 @@ import static com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilin * @author Eugene.Kudelevsky */ public class JavaCompilingVisitor extends JavaRecursiveElementWalkingVisitor { - final GlobalCompilingVisitor myCompilingVisitor; + @NotNull + private final GlobalCompilingVisitor myCompilingVisitor; @NonNls private static final Pattern COMMENT_PATTERN = Pattern.compile("__\\$_\\w+"); - static final Set excludedKeywords = ContainerUtil.newHashSet(PsiKeyword.CLASS, PsiKeyword.INTERFACE, PsiKeyword.ENUM, - PsiKeyword.THROWS, PsiKeyword.EXTENDS, PsiKeyword.IMPLEMENTS); + private static final Set excludedKeywords = ContainerUtil.newHashSet(PsiKeyword.CLASS, PsiKeyword.INTERFACE, PsiKeyword.ENUM, + PsiKeyword.THROWS, PsiKeyword.EXTENDS, PsiKeyword.IMPLEMENTS); - public JavaCompilingVisitor(GlobalCompilingVisitor compilingVisitor) { + public JavaCompilingVisitor(@NotNull GlobalCompilingVisitor compilingVisitor) { myCompilingVisitor = compilingVisitor; } - public void compile(PsiElement[] topLevelElements) { + public void compile(PsiElement @NotNull [] topLevelElements) { final JavaWordOptimizer optimizer = new JavaWordOptimizer(); final CompiledPattern pattern = myCompilingVisitor.getContext().getPattern(); for (PsiElement element : topLevelElements) { @@ -146,8 +147,8 @@ public class JavaCompilingVisitor extends JavaRecursiveElementWalkingVisitor { } @Override - public List getDescendantsOf(String className, boolean includeSelf, Project project) { - final SmartList result = new SmartList<>(); + public @NotNull List getDescendantsOf(@NotNull String className, boolean includeSelf, @NotNull Project project) { + List result = new SmartList<>(); // use project and libraries scope, because super class may be outside the scope of the search final GlobalSearchScope projectAndLibraries = ProjectScope.getAllScope(project); @@ -199,7 +200,7 @@ public class JavaCompilingVisitor extends JavaRecursiveElementWalkingVisitor { comment.putUserData(CompiledPattern.HANDLER_KEY, handler); final RegExpPredicate predicate = handler.findRegExpPredicate(); if (GlobalCompilingVisitor.isSuitablePredicate(predicate, handler)) { - myCompilingVisitor.processTokenizedName(predicate.getRegExp(), true, COMMENT); + myCompilingVisitor.processTokenizedName(predicate.getRegExp(), COMMENT); } } else if (!commentText.isEmpty()) { @@ -210,7 +211,7 @@ public class JavaCompilingVisitor extends JavaRecursiveElementWalkingVisitor { if (handler != null) comment.putUserData(CompiledPattern.HANDLER_KEY, handler); } else { - myCompilingVisitor.processTokenizedName(commentText, false, COMMENT); + myCompilingVisitor.processTokenizedName(commentText, COMMENT); } } } @@ -391,9 +392,8 @@ public class JavaCompilingVisitor extends JavaRecursiveElementWalkingVisitor { for (PsiTypeElement param : typeParameterElements) { if (param.getInnermostComponentReferenceElement() != null && - (myCompilingVisitor.getContext().getPattern().isRealTypedVar( - param.getInnermostComponentReferenceElement().getReferenceNameElement())) - ) { + myCompilingVisitor.getContext().getPattern().isRealTypedVar( + param.getInnermostComponentReferenceElement().getReferenceNameElement())) { myCompilingVisitor.setFilterSimple(param, TypeParameterFilter.getInstance()); } } @@ -566,7 +566,7 @@ public class JavaCompilingVisitor extends JavaRecursiveElementWalkingVisitor { if (element.getParent() instanceof PsiClass && handler instanceof SubstitutionHandler) { final SubstitutionHandler handler2 = (SubstitutionHandler)handler; - return (handler2.isStrictSubtype() || handler2.isSubtype()); + return handler2.isStrictSubtype() || handler2.isSubtype(); } return false; } diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/AnnotationHandler.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/AnnotationHandler.java index 741bc7bb2d75..b20dd1e8a288 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/AnnotationHandler.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/AnnotationHandler.java @@ -4,6 +4,7 @@ package com.intellij.structuralsearch.impl.matcher.handlers; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; import com.intellij.structuralsearch.impl.matcher.filters.AnnotationFilter; +import org.jetbrains.annotations.NotNull; /** * @author Bas @@ -15,7 +16,7 @@ public class AnnotationHandler extends MatchingHandler { } @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { if (!super.match(patternNode,matchedNode,context)) { return false; } diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DeclarationStatementHandler.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DeclarationStatementHandler.java index 164cf117e3b7..1850a9bdeb24 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DeclarationStatementHandler.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DeclarationStatementHandler.java @@ -8,6 +8,7 @@ import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.structuralsearch.impl.matcher.MatchContext; import com.intellij.structuralsearch.impl.matcher.iterators.SsrFilteringNodeIterator; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; @@ -19,7 +20,7 @@ public class DeclarationStatementHandler extends MatchingHandler { private MatchingHandler myCommentHandler; @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { if (patternNode instanceof PsiComment) { return myCommentHandler.match(patternNode, matchedNode, context); } diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DocDataHandler.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DocDataHandler.java index 7da76c083caa..de4b925cd74c 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DocDataHandler.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/DocDataHandler.java @@ -7,6 +7,7 @@ import com.intellij.psi.javadoc.PsiDocTagValue; import com.intellij.psi.javadoc.PsiDocToken; import com.intellij.structuralsearch.impl.matcher.MatchContext; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -22,7 +23,7 @@ public class DocDataHandler extends MatchingHandler { ); @Override - public boolean match(PsiElement node, PsiElement match, MatchContext context) { + public boolean match(PsiElement node, PsiElement match, @NotNull MatchContext context) { String text1 = node.getText(); text1 = getTextFromNode(node, text1); diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/ExpressionHandler.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/ExpressionHandler.java index e23b0fe0b4aa..8c2b02f3e6b3 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/ExpressionHandler.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/ExpressionHandler.java @@ -4,6 +4,7 @@ package com.intellij.structuralsearch.impl.matcher.handlers; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpressionStatement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; /** * Handler for expression search. The pattern for an expression includes an unnecessary {@code PsiExpressionStatement}, @@ -11,7 +12,7 @@ import com.intellij.structuralsearch.impl.matcher.MatchContext; */ public class ExpressionHandler extends MatchingHandler { @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { if (!super.match(patternNode,matchedNode, context)) { return false; } diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/StatementHandler.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/StatementHandler.java index 9ad5e4c688de..948676f49fc3 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/StatementHandler.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/handlers/StatementHandler.java @@ -3,6 +3,7 @@ package com.intellij.structuralsearch.impl.matcher.handlers; import com.intellij.psi.*; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; /** * Handler for statement search @@ -10,7 +11,7 @@ import com.intellij.structuralsearch.impl.matcher.MatchContext; public class StatementHandler extends MatchingHandler { @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { if (!(matchedNode instanceof PsiStatement) && !(matchedNode instanceof PsiComment)) { // typed statement matches statements (including block statements) and comments return false; diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/iterators/HierarchyNodeIterator.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/iterators/HierarchyNodeIterator.java index 7a4466821b8e..20b70e5333ba 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/iterators/HierarchyNodeIterator.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/iterators/HierarchyNodeIterator.java @@ -6,6 +6,7 @@ import com.intellij.psi.*; import com.intellij.psi.impl.PsiClassImplUtil; import com.intellij.structuralsearch.impl.matcher.MatchUtils; import com.intellij.util.SmartList; +import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.List; @@ -16,14 +17,14 @@ import java.util.Set; */ public class HierarchyNodeIterator extends NodeIterator { private int index; - private final List remaining; + private final List remaining = new SmartList<>(); private boolean objectTaken; private boolean firstElementTaken; private final boolean acceptClasses; private final boolean acceptInterfaces; private final boolean acceptFirstElement; - private void build(PsiElement current, Set visited) { + private void build(PsiElement current, @NotNull Set visited) { if (current == null) return; final String text = current instanceof PsiClass ? ((PsiClass)current).getName() : current.getText(); @@ -66,7 +67,7 @@ public class HierarchyNodeIterator extends NodeIterator { } } - private void processClasses(PsiReferenceList referenceList, Set visited) { + private void processClasses(PsiReferenceList referenceList, @NotNull Set visited) { if (referenceList == null) { return; } @@ -79,8 +80,7 @@ public class HierarchyNodeIterator extends NodeIterator { this(reference, acceptClasses, acceptInterfaces, true); } - public HierarchyNodeIterator(PsiElement reference, boolean acceptClasses, boolean acceptInterfaces, boolean acceptFirstElement) { - remaining = new SmartList<>(); + private HierarchyNodeIterator(PsiElement reference, boolean acceptClasses, boolean acceptInterfaces, boolean acceptFirstElement) { this.acceptClasses = acceptClasses; this.acceptInterfaces = acceptInterfaces; this.acceptFirstElement = acceptFirstElement; diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/ExprTypePredicate.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/ExprTypePredicate.java index 96c026b44864..d1abedaa32b8 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/ExprTypePredicate.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/ExprTypePredicate.java @@ -6,6 +6,8 @@ import com.intellij.psi.*; import com.intellij.structuralsearch.impl.matcher.MatchContext; import com.intellij.util.SmartList; import gnu.trove.THashSet; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; @@ -24,7 +26,7 @@ public class ExprTypePredicate extends MatchPredicate { private final boolean myCaseSensitive; private final List myTypes; - public ExprTypePredicate(String type, String baseName, boolean withinHierarchy, boolean caseSensitiveMatch, boolean target, boolean regex) { + public ExprTypePredicate(@NotNull String type, String baseName, boolean withinHierarchy, boolean caseSensitiveMatch, boolean target, boolean regex) { myDelegate = regex ? new RegExpPredicate(type, caseSensitiveMatch, baseName, false, target) : null; myWithinHierarchy = withinHierarchy; needsTypeParameters = type.indexOf('<') >= 0; @@ -35,7 +37,7 @@ public class ExprTypePredicate extends MatchPredicate { } @Override - public boolean match(PsiElement match, int start, int end, MatchContext context) { + public boolean match(@NotNull PsiElement match, int start, int end, @NotNull MatchContext context) { if (match instanceof PsiIdentifier) { // since we pickup tokens match = match.getParent(); @@ -51,7 +53,7 @@ public class ExprTypePredicate extends MatchPredicate { return type != null && doMatchWithTheType(type, context, match, null); } - protected PsiType evalType(PsiExpression match, MatchContext context) { + protected PsiType evalType(@NotNull PsiExpression match, @NotNull MatchContext context) { if (match instanceof PsiFunctionalExpression) { final PsiFunctionalExpression functionalExpression = (PsiFunctionalExpression)match; return functionalExpression.getFunctionalInterfaceType(); @@ -65,7 +67,7 @@ public class ExprTypePredicate extends MatchPredicate { return match.getType(); } - private boolean doMatchWithTheType(final PsiType type, MatchContext context, PsiElement matchedNode, Set visited) { + private boolean doMatchWithTheType(@NotNull PsiType type, @NotNull MatchContext context, @NotNull PsiElement matchedNode, @Nullable Set visited) { final List permutations = getTextPermutations(type); for (String permutation : permutations) { if (myDelegate == null ? doMatch(permutation) : myDelegate.doMatch(permutation, context, matchedNode)) { diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/FormalArgTypePredicate.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/FormalArgTypePredicate.java index 3fda996a7270..7c3a44d75d69 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/FormalArgTypePredicate.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/FormalArgTypePredicate.java @@ -5,10 +5,11 @@ import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiType; import com.intellij.structuralsearch.impl.matcher.MatchContext; import com.siyeh.ig.psiutils.ExpectedTypeUtils; +import org.jetbrains.annotations.NotNull; public class FormalArgTypePredicate extends ExprTypePredicate { - public FormalArgTypePredicate(String type, + public FormalArgTypePredicate(@NotNull String type, String baseName, boolean withinHierarchy, boolean caseSensitiveMatch, @@ -18,7 +19,7 @@ public class FormalArgTypePredicate extends ExprTypePredicate { } @Override - protected PsiType evalType(PsiExpression match, MatchContext context) { + protected PsiType evalType(@NotNull PsiExpression match, @NotNull MatchContext context) { return ExpectedTypeUtils.findExpectedType(match, true, true); } } diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ex/DynamicGroupTool.java b/platform/analysis-impl/src/com/intellij/codeInspection/ex/DynamicGroupTool.java index d0c88f0d6484..ffc9978f8012 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/ex/DynamicGroupTool.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/ex/DynamicGroupTool.java @@ -1,8 +1,11 @@ // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.ex; +import org.jetbrains.annotations.NotNull; + import java.util.List; public interface DynamicGroupTool { + @NotNull List getChildren(); } diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionProfileActionProvider.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionProfileActionProvider.java index ffba30dfbf37..b40dde99871f 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionProfileActionProvider.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionProfileActionProvider.java @@ -15,5 +15,5 @@ public abstract class InspectionProfileActionProvider { ExtensionPointName.create("com.intellij.inspectionProfileActionProvider"); @NotNull - public abstract List getActions(SingleInspectionProfilePanel panel); + public abstract List getActions(@NotNull SingleInspectionProfilePanel panel); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/DefaultMatchResultSink.java b/platform/structuralsearch/source/com/intellij/structuralsearch/DefaultMatchResultSink.java index d86b09ce2653..05e503452261 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/DefaultMatchResultSink.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/DefaultMatchResultSink.java @@ -17,23 +17,24 @@ package com.intellij.structuralsearch; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.psi.PsiFile; +import org.jetbrains.annotations.NotNull; /** * @author Bas Leijdekkers */ public class DefaultMatchResultSink implements MatchResultSink { @Override - public void newMatch(MatchResult result) { + public void newMatch(@NotNull MatchResult result) { } @Override - public void processFile(PsiFile element) { + public void processFile(@NotNull PsiFile element) { } @Override - public void setMatchingProcess(MatchingProcess matchingProcess) { + public void setMatchingProcess(@NotNull MatchingProcess matchingProcess) { } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java index 2147f010a8de..f87afc4ea7d4 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java @@ -9,6 +9,7 @@ import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import com.intellij.structuralsearch.plugin.replace.ReplacementInfo; +import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; @@ -25,7 +26,7 @@ public class DocumentBasedReplaceHandler extends StructuralReplaceHandler { } @Override - public void replace(ReplacementInfo info, ReplaceOptions options) { + public void replace(@NotNull ReplacementInfo info, @NotNull ReplaceOptions options) { final RangeMarker rangeMarker = myRangeMarkers.get(info); final Document document = rangeMarker.getDocument(); document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), info.getReplacement()); @@ -33,7 +34,7 @@ public class DocumentBasedReplaceHandler extends StructuralReplaceHandler { } @Override - public void prepare(ReplacementInfo info) { + public void prepare(@NotNull ReplacementInfo info) { final PsiElement firstElement = StructuralSearchUtil.getPresentableElement(info.getMatch(0)); if (firstElement == null) return; final Document document = PsiDocumentManager.getInstance(myProject).getDocument(firstElement.getContainingFile()); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/MalformedPatternException.java b/platform/structuralsearch/source/com/intellij/structuralsearch/MalformedPatternException.java index ec07cf027f41..f1e25e3181fb 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/MalformedPatternException.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/MalformedPatternException.java @@ -2,6 +2,7 @@ package com.intellij.structuralsearch; import com.intellij.psi.PsiErrorElement; +import org.jetbrains.annotations.NotNull; public class MalformedPatternException extends StructuralSearchException { @@ -11,12 +12,12 @@ public class MalformedPatternException extends StructuralSearchException { isErrorElement = false; } - public MalformedPatternException(String msg) { + public MalformedPatternException(@NotNull String msg) { super(msg); isErrorElement = false; } - public MalformedPatternException(PsiErrorElement errorElement) { + public MalformedPatternException(@NotNull PsiErrorElement errorElement) { super(errorElement.getErrorDescription()); isErrorElement = true; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchOptions.java b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchOptions.java index 96c791b9f8f5..15dd4a22c8ca 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchOptions.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchOptions.java @@ -68,11 +68,12 @@ public class MatchOptions implements JDOMExternalizable { myPatternContextId = options.myPatternContextId; } + @NotNull public MatchOptions copy() { return new MatchOptions(this); } - public void initScope(Project project) { + public void initScope(@NotNull Project project) { if (scope == null && scopeType != null && scopeDescriptor != null) { scope = Scopes.createScope(project, scopeDescriptor, scopeType); } @@ -149,7 +150,7 @@ public class MatchOptions implements JDOMExternalizable { return pattern; } - public void fillSearchCriteria(String criteria) { + public void fillSearchCriteria(@NotNull String criteria) { if (!variableConstraints.isEmpty()) variableConstraints.clear(); StringToConstraintsTransformer.transformCriteria(criteria, this); } @@ -255,7 +256,7 @@ public class MatchOptions implements JDOMExternalizable { } public int hashCode() { - int result = (looseMatching ? 1 : 0); + int result = looseMatching ? 1 : 0; result = 29 * result + (recursiveSearch ? 1 : 0); result = 29 * result + (caseSensitiveMatch ? 1 : 0); result = 29 * result + pattern.hashCode(); @@ -267,7 +268,7 @@ public class MatchOptions implements JDOMExternalizable { return result; } - public void setFileType(LanguageFileType fileType) { + public void setFileType(@NotNull LanguageFileType fileType) { myFileType = fileType; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResult.java b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResult.java index dbb979e46df6..f4157fe2fc56 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResult.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResult.java @@ -4,6 +4,7 @@ package com.intellij.structuralsearch; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.plugin.util.SmartPsiPointer; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import java.util.List; @@ -20,6 +21,7 @@ public abstract class MatchResult { public abstract String getName(); + @NotNull public abstract List getChildren(); public abstract boolean hasChildren(); public abstract int size(); @@ -27,6 +29,7 @@ public abstract class MatchResult { public abstract boolean isScopeMatch(); public abstract boolean isMultipleMatch(); + @NotNull public abstract MatchResult getRoot(); public abstract boolean isTarget(); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResultSink.java b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResultSink.java index 79eacd6b51b1..bc534fbe5977 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResultSink.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchResultSink.java @@ -3,6 +3,7 @@ package com.intellij.structuralsearch; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.psi.PsiFile; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** @@ -11,21 +12,20 @@ import org.jetbrains.annotations.Nullable; public interface MatchResultSink { /** * Notifies sink about new match - * @param result */ - void newMatch(MatchResult result); + void newMatch(@NotNull MatchResult result); /** * Notifies sink about starting the matching for given element * @param element the current file */ - void processFile(PsiFile element); + void processFile(@NotNull PsiFile element); /** * Sets the reference to the matching process * @param matchingProcess the matching process reference */ - void setMatchingProcess(MatchingProcess matchingProcess); + void setMatchingProcess(@NotNull MatchingProcess matchingProcess); /** * Notifies sink about end of matching. diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchVariableConstraint.java b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchVariableConstraint.java index e1993edf7c1d..00cd36d7f676 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/MatchVariableConstraint.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/MatchVariableConstraint.java @@ -91,11 +91,11 @@ public class MatchVariableConstraint extends NamedScriptableDefinition { public MatchVariableConstraint() {} - public MatchVariableConstraint(String name) { + public MatchVariableConstraint(@NotNull String name) { setName(name); } - MatchVariableConstraint(MatchVariableConstraint constraint) { + private MatchVariableConstraint(@NotNull MatchVariableConstraint constraint) { super(constraint); regExp = constraint.regExp; invertRegExp = constraint.invertRegExp; @@ -395,7 +395,7 @@ public class MatchVariableConstraint extends NamedScriptableDefinition { public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MatchVariableConstraint)) return false; - if (!(super.equals(o))) return false; + if (!super.equals(o)) return false; final MatchVariableConstraint other = (MatchVariableConstraint)o; @@ -425,8 +425,9 @@ public class MatchVariableConstraint extends NamedScriptableDefinition { if (!contextConstraint.equals(other.contextConstraint)) return false; if (additionalConstraints != null) { if (!additionalConstraints.equals(other.additionalConstraints)) return false; - } else if (other.additionalConstraints != null) { - return false; + } + else { + return other.additionalConstraints == null; } return true; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/Matcher.java b/platform/structuralsearch/source/com/intellij/structuralsearch/Matcher.java index ac18515c0408..8122f0cdee5e 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/Matcher.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/Matcher.java @@ -44,24 +44,25 @@ import static com.intellij.structuralsearch.impl.matcher.iterators.SingleNodeIte * This class makes program structure tree matching: */ public class Matcher { - static final Logger LOG = Logger.getInstance(Matcher.class); + private static final Logger LOG = Logger.getInstance(Matcher.class); @SuppressWarnings("SSBasedInspection") private static final ThreadLocal> ourRecursionGuard = ThreadLocal.withInitial(() -> new HashSet<>()); // project being worked on - final Project project; + private final Project project; // context of matching - final MatchContext matchContext; + @NotNull + private final MatchContext matchContext; private boolean isTesting; // visitor to delegate the real work private final GlobalMatchingVisitor visitor = new GlobalMatchingVisitor(); private final TaskScheduler scheduler = new TaskScheduler(); - int totalFilesToScan; - int scannedFilesCount; + private int totalFilesToScan; + private int scannedFilesCount; public Matcher(@NotNull Project project, @NotNull MatchOptions matchOptions) { this(project, matchOptions, PatternCompiler.compilePattern(project, matchOptions, false, true)); @@ -69,15 +70,14 @@ public class Matcher { public Matcher(@NotNull Project project, @NotNull MatchOptions matchOptions, @NotNull CompiledPattern compiledPattern) { this.project = project; - matchContext = new MatchContext(); - matchContext.setMatcher(visitor); + matchContext = new MatchContext(visitor); visitor.setMatchContext(matchContext); matchContext.setOptions(matchOptions); matchContext.setPattern(compiledPattern); } - public static Matcher buildMatcher(Project project, LanguageFileType fileType, String constraint) { + public static Matcher buildMatcher(@NotNull Project project, @NotNull LanguageFileType fileType, @NotNull String constraint) { if (StringUtil.isQuotedString(constraint)) { // keep old configurations working, also useful for testing final MatchOptions myMatchOptions = new MatchOptions(); @@ -110,7 +110,7 @@ public class Matcher { PatternCompiler.compilePattern(project, options, true, true); } - public boolean checkIfShouldAttemptToMatch(NodeIterator matchedNodes) { + public boolean checkIfShouldAttemptToMatch(@NotNull NodeIterator matchedNodes) { final CompiledPattern pattern = matchContext.getPattern(); final NodeIterator patternNodes = pattern.getNodes(); try { @@ -168,7 +168,7 @@ public class Matcher { return; } - matchContext.getSink().setMatchingProcess( scheduler ); + matchContext.getSink().setMatchingProcess(scheduler); scheduler.init(); if (isTesting) { @@ -239,7 +239,7 @@ public class Matcher { } } - public MatchContext getMatchContext() { + public @NotNull MatchContext getMatchContext() { return matchContext; } @@ -385,7 +385,7 @@ public class Matcher { * Initiates the matching process for given element * @param element the current search tree element */ - void match(@NotNull PsiElement element) { + private void match(@NotNull PsiElement element) { final MatchingStrategy strategy = matchContext.getPattern().getStrategy(); if (strategy.continueMatching(element)) { @@ -430,12 +430,13 @@ public class Matcher { } while (element.getClass() != targetNode.getClass()) { element = element.getParent(); - if (element == null) return Collections.emptyList(); + if (element == null) return Collections.emptyList(); } elementToStartMatching = element; } - } else { + } + else { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(element); if (profile == null) return Collections.emptyList(); targetNode = profile.extendMatchedByDownUp(targetNode); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/PatternContext.java b/platform/structuralsearch/source/com/intellij/structuralsearch/PatternContext.java index 0f8eafe0c1ef..4e4629a7d761 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/PatternContext.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/PatternContext.java @@ -7,14 +7,14 @@ import org.jetbrains.annotations.NotNull; * @author Bas Leijdekkers */ public final class PatternContext implements Comparable { - + @NotNull public final String myID; + @NotNull private final String myDisplayName; - public PatternContext(@NotNull String ID, String displayName) { + public PatternContext(@NotNull String ID, @NotNull String displayName) { myID = ID; myDisplayName = displayName; - } @Override @@ -41,7 +41,7 @@ public final class PatternContext implements Comparable { return myID; } - public String getDisplayName() { + public @NotNull String getDisplayName() { return myDisplayName; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/PredefinedConfigurationUtil.java b/platform/structuralsearch/source/com/intellij/structuralsearch/PredefinedConfigurationUtil.java index 061dd5f1e5a5..190d7dc61a06 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/PredefinedConfigurationUtil.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/PredefinedConfigurationUtil.java @@ -6,6 +6,8 @@ import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.structuralsearch.plugin.ui.Configuration; import com.intellij.structuralsearch.plugin.ui.SearchConfiguration; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public final class PredefinedConfigurationUtil { @@ -15,19 +17,22 @@ public final class PredefinedConfigurationUtil { * instead. */ @Deprecated - public static Configuration createSearchTemplateInfo(String name, @NonNls String criteria, String category) { + @NotNull + public static Configuration createSearchTemplateInfo(@NotNull String name, @NonNls @NotNull String criteria, @NotNull String category) { return createSearchTemplateInfo(name, criteria, category, StdFileTypes.JAVA); } - public static Configuration createSearchTemplateInfo(String name, @NonNls String criteria, String category, LanguageFileType fileType) { + @NotNull + public static Configuration createSearchTemplateInfo(@NotNull String name, @NonNls @NotNull String criteria, @NotNull String category, @NotNull LanguageFileType fileType) { return createSearchTemplateInfo(name, criteria, category, fileType, null); } - public static Configuration createSearchTemplateInfo(String name, - @NonNls String criteria, - String category, - LanguageFileType fileType, - PatternContext context) { + @NotNull + public static Configuration createSearchTemplateInfo(@NotNull String name, + @NonNls @NotNull String criteria, + @NotNull String category, + @NotNull LanguageFileType fileType, + @Nullable PatternContext context) { final SearchConfiguration config = new SearchConfiguration(name, category); config.setPredefined(true); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/ReplacementVariableDefinition.java b/platform/structuralsearch/source/com/intellij/structuralsearch/ReplacementVariableDefinition.java index cc7dc101641e..e1d25eb2d00c 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/ReplacementVariableDefinition.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/ReplacementVariableDefinition.java @@ -1,17 +1,19 @@ // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.structuralsearch; +import org.jetbrains.annotations.NotNull; + /** * @author Maxim.Mossienko */ public class ReplacementVariableDefinition extends NamedScriptableDefinition { public ReplacementVariableDefinition() {} - public ReplacementVariableDefinition(String name) { + public ReplacementVariableDefinition(@NotNull String name) { setName(name); } - public ReplacementVariableDefinition(ReplacementVariableDefinition definition) { + public ReplacementVariableDefinition(@NotNull ReplacementVariableDefinition definition) { super(definition); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralReplaceHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralReplaceHandler.java index 2a9bf219fe37..4547ff35d65a 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralReplaceHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralReplaceHandler.java @@ -3,14 +3,15 @@ package com.intellij.structuralsearch; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import com.intellij.structuralsearch.plugin.replace.ReplacementInfo; +import org.jetbrains.annotations.NotNull; /** * @author Eugene.Kudelevsky */ public abstract class StructuralReplaceHandler { - public abstract void replace(final ReplacementInfo info, ReplaceOptions options); + public abstract void replace(@NotNull ReplacementInfo info, @NotNull ReplaceOptions options); - public void prepare(ReplacementInfo info) {} + public void prepare(@NotNull ReplacementInfo info) {} - public void postProcess(PsiElement affectedElement, ReplaceOptions options) {} + public void postProcess(@NotNull PsiElement affectedElement, @NotNull ReplaceOptions options) {} } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchException.java b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchException.java index e9a8429d42ad..afdf6700b1f8 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchException.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchException.java @@ -1,17 +1,19 @@ // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.structuralsearch; +import org.jetbrains.annotations.NotNull; + /** * @author Bas Leijdekkers */ public class StructuralSearchException extends RuntimeException { public StructuralSearchException() {} - public StructuralSearchException(String message) { + public StructuralSearchException(@NotNull String message) { super(message); } - public StructuralSearchException(Throwable cause) { + public StructuralSearchException(@NotNull Throwable cause) { super(cause); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfile.java b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfile.java index 025ab2e1e5d0..9459c3b4d7c1 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfile.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfile.java @@ -46,10 +46,8 @@ public abstract class StructuralSearchProfile { * Creates the pattern PSI tree which is stored inside CompiledPattern. * Uses compiling visitor to visit the query PsiElements, sets the correct Filters and Handlers. * @see #createCompiledPattern() - * @param elements - * @param globalVisitor */ - public abstract void compile(PsiElement[] elements, @NotNull GlobalCompilingVisitor globalVisitor); + public abstract void compile(PsiElement @NotNull [] elements, @NotNull GlobalCompilingVisitor globalVisitor); /** * The MatchingVisitor knows how to match language specific constructs, when those constructs have already been found. @@ -70,25 +68,22 @@ public abstract class StructuralSearchProfile { /** * Filter to filter out uninteresting elements that should not be matched. Usually white space and error elements. - * @return */ @NotNull public abstract NodeFilter getLexicalNodesFilter(); /** * Creates language specific compiled pattern. - * @return */ @NotNull public abstract CompiledPattern createCompiledPattern(); @NotNull - public List getCustomPredicates(MatchVariableConstraint constraint, String name, MatchOptions options) { + public List getCustomPredicates(@NotNull MatchVariableConstraint constraint, @NotNull String name, @NotNull MatchOptions options) { return Collections.emptyList(); } /** - * @param language * @return true, if this structural search profile can match code of the specified language. False otherwise. */ public abstract boolean isMyLanguage(@NotNull Language language); @@ -96,32 +91,25 @@ public abstract class StructuralSearchProfile { /** * Converts query text into PSI tree. * @param text the text of the search query. - * @param context - * @param fileType - * @param language - * @param contextId - * @param project - * @param physical - * @return */ @NotNull - public PsiElement[] createPatternTree(@NotNull String text, - @NotNull PatternTreeContext context, - @NotNull LanguageFileType fileType, - @NotNull Language language, - @Nullable String contextId, - @NotNull Project project, - boolean physical) { + public PsiElement @NotNull [] createPatternTree(@NotNull String text, + @NotNull PatternTreeContext context, + @NotNull LanguageFileType fileType, + @NotNull Language language, + @Nullable String contextId, + @NotNull Project project, + boolean physical) { return doCreatePatternTree(text, context, fileType, language, project, physical, getContext(text, language, contextId)); } @NotNull - public PsiElement[] createPatternTree(@NotNull String text, - @NotNull PatternContextInfo contextInfo, - @NotNull LanguageFileType fileType, - @NotNull Language language, - @NotNull Project project, - boolean physical) { + public PsiElement @NotNull [] createPatternTree(@NotNull String text, + @NotNull PatternContextInfo contextInfo, + @NotNull LanguageFileType fileType, + @NotNull Language language, + @NotNull Project project, + boolean physical) { String contextConstraint = contextInfo.getContextConstraint(); if (StringUtil.isEmpty(contextConstraint)) { PatternContext patternContext = contextInfo.getPatternContext(); @@ -132,13 +120,13 @@ public abstract class StructuralSearchProfile { } @NotNull - private PsiElement[] doCreatePatternTree(@NotNull String text, - @NotNull PatternTreeContext context, - @NotNull LanguageFileType fileType, - @NotNull Language language, - @NotNull Project project, - boolean physical, - String strContext) { + private PsiElement @NotNull [] doCreatePatternTree(@NotNull String text, + @NotNull PatternTreeContext context, + @NotNull LanguageFileType fileType, + @NotNull Language language, + @NotNull Project project, + boolean physical, + @NotNull String strContext) { String placeholderName = getPlaceholderVarName(); final String patternInContext = (context == PatternTreeContext.File) ? text : strContext.replace(placeholderName, text); @@ -207,14 +195,15 @@ public abstract class StructuralSearchProfile { } @Nullable - public PsiCodeFragment createCodeFragment(Project project, String text, String contextId) { + public PsiCodeFragment createCodeFragment(@NotNull Project project, @NotNull String text, @Nullable String contextId) { return null; } /** * This method is called while holding a read action. */ - public String getCodeFragmentText(PsiFile fragment) { + @NotNull + public String getCodeFragmentText(@NotNull PsiFile fragment) { return fragment.getText(); } @@ -245,14 +234,14 @@ public abstract class StructuralSearchProfile { return false; } - public void checkSearchPattern(CompiledPattern pattern) {} + public void checkSearchPattern(@NotNull CompiledPattern pattern) {} - public void checkReplacementPattern(Project project, ReplaceOptions options) { + public void checkReplacementPattern(@NotNull Project project, @NotNull ReplaceOptions options) { final String fileType = StringUtil.toLowerCase(options.getMatchOptions().getFileType().getName()); throw new UnsupportedPatternException(SSRBundle.message("replacement.not.supported.for.filetype", fileType)); } - public boolean shouldShowProblem(PsiErrorElement error) { + public boolean shouldShowProblem(@NotNull PsiErrorElement error) { return false; } @@ -261,14 +250,15 @@ public abstract class StructuralSearchProfile { return false; } - public String getText(PsiElement match, int start, int end) { + @NotNull + public String getText(@NotNull PsiElement match, int start, int end) { final String matchText = match.getText(); if (start == 0 && end == -1) return matchText; return matchText.substring(start, end == -1 ? matchText.length() : end); } @NotNull - public String getTypedVarString(PsiElement element) { + public String getTypedVarString(@NotNull PsiElement element) { if (element instanceof PsiNamedElement) { final String name = ((PsiNamedElement)element).getName(); if (name != null) { @@ -278,23 +268,26 @@ public abstract class StructuralSearchProfile { return element.getText(); } - public String getMeaningfulText(PsiElement element) { + public String getMeaningfulText(@NotNull PsiElement element) { return getTypedVarString(element); } - public String getAlternativeText(PsiElement element, String previousText) { + public String getAlternativeText(@NotNull PsiElement element, @NotNull String previousText) { return null; } - public PsiElement updateCurrentNode(PsiElement node) { + @NotNull + public PsiElement updateCurrentNode(@NotNull PsiElement node) { return node; } - public PsiElement extendMatchedByDownUp(PsiElement node) { + @NotNull + public PsiElement extendMatchedByDownUp(@NotNull PsiElement node) { return node; } - public PsiElement extendMatchOnePsiFile(PsiElement file) { + @NotNull + public PsiElement extendMatchOnePsiFile(@NotNull PsiElement file) { return file; } @@ -302,13 +295,13 @@ public abstract class StructuralSearchProfile { return fileType; } - public Configuration[] getPredefinedTemplates() { + public Configuration @NotNull [] getPredefinedTemplates() { return Configuration.EMPTY_ARRAY; } - public void provideAdditionalReplaceOptions(@NotNull PsiElement node, ReplaceOptions options, ReplacementBuilder builder) {} + public void provideAdditionalReplaceOptions(@NotNull PsiElement node, @NotNull ReplaceOptions options, @NotNull ReplacementBuilder builder) {} - public void handleSubstitution(ParameterInfo info, MatchResult match, StringBuilder result, ReplacementInfo replacementInfo) { + public void handleSubstitution(@NotNull ParameterInfo info, @NotNull MatchResult match, @NotNull StringBuilder result, @NotNull ReplacementInfo replacementInfo) { if (info.getName().equals(match.getName())) { final String replacementString; boolean removeSemicolon = false; @@ -350,7 +343,7 @@ public abstract class StructuralSearchProfile { } } - public void handleNoSubstitution(ParameterInfo info, StringBuilder result) { + public void handleNoSubstitution(@NotNull ParameterInfo info, @NotNull StringBuilder result) { if (info.isHasCommaBefore()) { result.delete(info.getBeforeDelimiterPos(), info.getBeforeDelimiterPos() + 1); } @@ -369,12 +362,12 @@ public abstract class StructuralSearchProfile { return Collections.emptySet(); } - public boolean isDocCommentOwner(PsiElement match) { + public boolean isDocCommentOwner(@NotNull PsiElement match) { return false; } - @Contract("!null -> !null") - public PsiElement getPresentableElement(PsiElement element) { + @NotNull + public PsiElement getPresentableElement(@NotNull PsiElement element) { return isIdentifier(element) ? element.getParent() : element; } @@ -388,7 +381,7 @@ public abstract class StructuralSearchProfile { * @param target true, if the current variableNode is the target of the search * @return true, if the requested constraint is applicable and the corresponding UI should be shown when editing the variable; false otherwise */ - public boolean isApplicableConstraint(String constraintName, @Nullable PsiElement variableNode, boolean completePattern, boolean target) { + public boolean isApplicableConstraint(@NotNull String constraintName, @Nullable PsiElement variableNode, boolean completePattern, boolean target) { switch (constraintName) { case UIUtil.MINIMUM_ZERO: if (target) return false; @@ -400,8 +393,8 @@ public abstract class StructuralSearchProfile { return false; } - public final boolean isApplicableConstraint(String constraintName, - List nodes, + public final boolean isApplicableConstraint(@NotNull String constraintName, + @NotNull List nodes, boolean completePattern, boolean target) { if (nodes.isEmpty()) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfileBase.java b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfileBase.java index 58b1440cebc9..a36db2e3741d 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfileBase.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfileBase.java @@ -41,7 +41,7 @@ public abstract class StructuralSearchProfileBase extends StructuralSearchProfil private static final String DELIMITER_CHARS = ",;.[]{}():"; @Override - public void compile(PsiElement[] elements, @NotNull final GlobalCompilingVisitor globalVisitor) { + public void compile(PsiElement @NotNull [] elements, @NotNull final GlobalCompilingVisitor globalVisitor) { final PsiElement topElement = elements[0].getParent(); final PsiElement element = elements.length > 1 ? topElement : elements[0]; @@ -179,14 +179,14 @@ public abstract class StructuralSearchProfileBase extends StructuralSearchProfil protected abstract LanguageFileType getFileType(); @Override - public void checkReplacementPattern(Project project, ReplaceOptions options) {} + public void checkReplacementPattern(@NotNull Project project, @NotNull ReplaceOptions options) {} @Override public StructuralReplaceHandler getReplaceHandler(@NotNull Project project, @NotNull ReplaceOptions replaceOptions) { return new DocumentBasedReplaceHandler(project); } - static boolean canBePatternVariable(PsiElement element) { + private static boolean canBePatternVariable(@NotNull PsiElement element) { // can be leaf element! (ex. var a = 1 <-> var $a$ = 1) if (element instanceof LeafElement) { return true; @@ -213,7 +213,7 @@ public abstract class StructuralSearchProfileBase extends StructuralSearchProfil return false; } - static boolean canBePatternVariableValue(PsiElement element) { + private static boolean canBePatternVariableValue(@NotNull PsiElement element) { // can be leaf element! (ex. var a = 1 <-> var $a$ = 1) return !containsOnlyDelimiters(element.getText()); } @@ -251,7 +251,7 @@ public abstract class StructuralSearchProfileBase extends StructuralSearchProfil } } - private void doVisitElement(PsiElement element) { + private void doVisitElement(@NotNull PsiElement element) { final CompiledPattern pattern = myGlobalVisitor.getContext().getPattern(); if (myGlobalVisitor.getCodeBlockLevel() == 0) { @@ -262,12 +262,7 @@ public abstract class StructuralSearchProfileBase extends StructuralSearchProfil if (canBePatternVariable(element) && pattern.isRealTypedVar(element)) { myGlobalVisitor.handle(element); final MatchingHandler handler = pattern.getHandler(element); - handler.setFilter(new NodeFilter() { - @Override - public boolean accepts(PsiElement other) { - return canBePatternVariableValue(other); - } - }); + handler.setFilter(other -> canBePatternVariableValue(other)); super.visitElement(element); @@ -283,7 +278,7 @@ public abstract class StructuralSearchProfileBase extends StructuralSearchProfil // todo: support variables inside comments if (StringUtil.isJavaIdentifier(text)) { - myGlobalVisitor.processTokenizedName(text, true, GlobalCompilingVisitor.OccurenceKind.CODE); + myGlobalVisitor.processTokenizedName(text, GlobalCompilingVisitor.OccurenceKind.CODE); } } } @@ -456,13 +451,13 @@ public abstract class StructuralSearchProfileBase extends StructuralSearchProfil private static class MySubstitutionHandler extends SubstitutionHandler { final Set myExceptedNodes; - MySubstitutionHandler(String name, boolean target, int minOccurs, int maxOccurs, boolean greedy) { + MySubstitutionHandler(@NotNull String name, boolean target, int minOccurs, int maxOccurs, boolean greedy) { super(name, target, minOccurs, maxOccurs, greedy); myExceptedNodes = new HashSet<>(); } @Override - public boolean matchSequentially(NodeIterator patternNodes, NodeIterator matchNodes, MatchContext context) { + public boolean matchSequentially(@NotNull NodeIterator patternNodes, @NotNull NodeIterator matchNodes, @NotNull MatchContext context) { if (doMatchSequentially(patternNodes, matchNodes, context)) { return true; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchUtil.java b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchUtil.java index 36cbc474251a..6ca5e4961d71 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchUtil.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchUtil.java @@ -26,12 +26,12 @@ import java.util.stream.Collectors; public final class StructuralSearchUtil { private static final String REG_EXP_META_CHARS = ".$|()[]{}^?*+\\"; private static final Pattern ACCENTS = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); - private static LanguageFileType ourDefaultFileType = null; + private static LanguageFileType ourDefaultFileType; - private static boolean ourUseUniversalMatchingAlgorithm = false; + private static boolean ourUseUniversalMatchingAlgorithm; private static final Map cache = new HashMap<>(); - private static List ourPredefinedConfigurations = null; + private static List ourPredefinedConfigurations; static { StructuralSearchProfile.EP_NAME.addChangeListener(() -> { ourPredefinedConfigurations = null; @@ -53,7 +53,7 @@ public final class StructuralSearchUtil { } @Nullable - public static StructuralSearchProfile getProfileByFileType(LanguageFileType fileType) { + public static StructuralSearchProfile getProfileByFileType(@NotNull LanguageFileType fileType) { return getProfileByLanguage(fileType.getLanguage()); } @@ -81,7 +81,7 @@ public final class StructuralSearchUtil { } public static PsiElement getParentIfIdentifier(PsiElement element) { - return !isIdentifier(element) ? element : element.getParent(); + return isIdentifier(element) ? element.getParent() : element; } @Contract("!null -> !null") @@ -146,7 +146,8 @@ public final class StructuralSearchUtil { return REG_EXP_META_CHARS.indexOf(ch) >= 0; } - public static String shieldRegExpMetaChars(String word) { + @NotNull + public static String shieldRegExpMetaChars(@NotNull String word) { return shieldRegExpMetaChars(word, new StringBuilder(word.length())).toString(); } @@ -193,7 +194,7 @@ public final class StructuralSearchUtil { return ourPredefinedConfigurations; } - public static boolean isDocCommentOwner(PsiElement match) { + public static boolean isDocCommentOwner(@NotNull PsiElement match) { final StructuralSearchProfile profile = getProfileByPsiElement(match); return profile != null && profile.isDocCommentOwner(match); } @@ -203,11 +204,12 @@ public final class StructuralSearchUtil { return profile != null ? profile.getMeaningfulText(matchedNode) : matchedNode.getText(); } - public static String getAlternativeText(PsiElement matchedNode, String previousText) { + public static String getAlternativeText(@NotNull PsiElement matchedNode, @NotNull String previousText) { final StructuralSearchProfile profile = getProfileByPsiElement(matchedNode); return profile != null ? profile.getAlternativeText(matchedNode, previousText) : null; } + @NotNull public static String normalizeWhiteSpace(@NotNull String text) { text = text.trim(); final StringBuilder result = new StringBuilder(); @@ -228,10 +230,12 @@ public final class StructuralSearchUtil { return result.toString(); } + @NotNull public static String stripAccents(@NotNull String input) { return ACCENTS.matcher(Normalizer.normalize(input, Normalizer.Form.NFD)).replaceAll(""); } + @NotNull public static String normalize(@NotNull String text) { return stripAccents(normalizeWhiteSpace(text)); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/XmlStructuralSearchProfile.java b/platform/structuralsearch/source/com/intellij/structuralsearch/XmlStructuralSearchProfile.java index 7ed95e167b47..265de5308a99 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/XmlStructuralSearchProfile.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/XmlStructuralSearchProfile.java @@ -38,7 +38,7 @@ import static com.intellij.structuralsearch.PredefinedConfigurationUtil.createSe public class XmlStructuralSearchProfile extends StructuralSearchProfile { @Override - public void compile(PsiElement[] elements, @NotNull GlobalCompilingVisitor globalVisitor) { + public void compile(PsiElement @NotNull [] elements, @NotNull GlobalCompilingVisitor globalVisitor) { new XmlCompilingVisitor(globalVisitor).compile(elements); } @@ -55,7 +55,7 @@ public class XmlStructuralSearchProfile extends StructuralSearchProfile { @NotNull @Override - public String getTypedVarString(PsiElement element) { + public String getTypedVarString(@NotNull PsiElement element) { return element instanceof XmlText ? element.getText().trim() : super.getTypedVarString(element); } @@ -102,7 +102,7 @@ public class XmlStructuralSearchProfile extends StructuralSearchProfile { } @Override - public PsiElement extendMatchedByDownUp(PsiElement node) { + public @NotNull PsiElement extendMatchedByDownUp(@NotNull PsiElement node) { if (XmlUtil.isXmlToken(node, XmlTokenType.XML_DATA_CHARACTERS)) { final PsiElement parent = node.getParent(); if (parent.getTextRange().equals(node.getTextRange())) { @@ -130,7 +130,7 @@ public class XmlStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void checkSearchPattern(CompiledPattern pattern) { + public void checkSearchPattern(@NotNull CompiledPattern pattern) { final ValidatingVisitor visitor = new ValidatingVisitor(); final NodeIterator nodes = pattern.getNodes(); while (nodes.hasNext()) { @@ -159,7 +159,7 @@ public class XmlStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void checkReplacementPattern(Project project, ReplaceOptions options) { + public void checkReplacementPattern(@NotNull Project project, @NotNull ReplaceOptions options) { } @Override @@ -178,7 +178,7 @@ public class XmlStructuralSearchProfile extends StructuralSearchProfile { } @Override - public void replace(ReplacementInfo info, ReplaceOptions options) { + public void replace(@NotNull ReplacementInfo info, @NotNull ReplaceOptions options) { final PsiElement elementToReplace = StructuralSearchUtil.getPresentableElement(info.getMatch(0)); assert elementToReplace != null; final String replacementToMake = info.getReplacement(); @@ -240,7 +240,7 @@ public class XmlStructuralSearchProfile extends StructuralSearchProfile { } @Override - public Configuration[] getPredefinedTemplates() { + public Configuration @NotNull [] getPredefinedTemplates() { return XmlPredefinedConfigurations.createPredefinedTemplates(); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/CompiledPattern.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/CompiledPattern.java index 6fc4f959f312..e1386e8ca91a 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/CompiledPattern.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/CompiledPattern.java @@ -42,7 +42,7 @@ public abstract class CompiledPattern { public abstract String @NotNull [] getTypedVarPrefixes(); public abstract boolean isTypedVar(@NotNull String str); - public void setTargetNode(PsiElement element) { + public void setTargetNode(@NotNull PsiElement element) { targetNode = element; } @@ -113,11 +113,11 @@ public abstract class CompiledPattern { return handler; } - public MatchingHandler getHandler(String name) { + public MatchingHandler getHandler(@NotNull String name) { return handlers.get(name); } - public void setHandler(PsiElement node, MatchingHandler handler) { + public void setHandler(@NotNull PsiElement node, @NotNull MatchingHandler handler) { last = null; handlers.put(node, handler); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/GlobalMatchingVisitor.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/GlobalMatchingVisitor.java index d5b05ec33a49..455dcfeecb4b 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/GlobalMatchingVisitor.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/GlobalMatchingVisitor.java @@ -64,13 +64,14 @@ public class GlobalMatchingVisitor extends AbstractMatchingVisitor { return this.myResult = result; } + @NotNull public MatchContext getMatchContext() { return matchContext; } @Override protected boolean doMatchInAnyOrder(@NotNull NodeIterator elements, @NotNull NodeIterator elements2) { - return matchContext.getPattern().getHandler(elements.current()).matchInAnyOrder( + return MatchingHandler.matchInAnyOrder( elements, elements2, matchContext @@ -217,7 +218,7 @@ public class GlobalMatchingVisitor extends AbstractMatchingVisitor { } } - public void setMatchContext(MatchContext matchContext) { + public void setMatchContext(@NotNull MatchContext matchContext) { this.matchContext = matchContext; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchContext.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchContext.java index 43763c6d9ef2..9c5102b1cb05 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchContext.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchContext.java @@ -17,6 +17,10 @@ import java.util.List; * Global context of matching process */ public class MatchContext { + public MatchContext(@NotNull GlobalMatchingVisitor visitor) { + matcher = visitor; + } + private final Stack myMatchedElementsListenerStack = new Stack<>(2); private MatchResultSink sink; @@ -24,7 +28,8 @@ public class MatchContext { private MatchResultImpl result; private CompiledPattern pattern; private MatchOptions options; - private GlobalMatchingVisitor matcher; + @NotNull + private final GlobalMatchingVisitor matcher; private boolean shouldRecursivelyMatch = true; private final Stack> mySavedMatchedNodes = new Stack<>(); @@ -53,14 +58,10 @@ public class MatchContext { @FunctionalInterface public interface MatchedElementsListener { - void matchedElements(@NotNull Collection matchedElements); + void matchedElements(@NotNull Collection matchedElements); } - public void setMatcher(GlobalMatchingVisitor matcher) { - this.matcher = matcher; - } - - public GlobalMatchingVisitor getMatcher() { + public @NotNull GlobalMatchingVisitor getMatcher() { return matcher; } @@ -68,7 +69,7 @@ public class MatchContext { return options; } - public void setOptions(MatchOptions options) { + public void setOptions(@NotNull MatchOptions options) { this.options = options; } @@ -87,6 +88,7 @@ public class MatchContext { } } + @NotNull public MatchResultImpl getResult() { if (result==null) result = new MatchResultImpl(); return result; @@ -116,7 +118,7 @@ public class MatchContext { return pattern; } - public void setPattern(CompiledPattern pattern) { + public void setPattern(@NotNull CompiledPattern pattern) { this.pattern = pattern; } @@ -124,7 +126,7 @@ public class MatchContext { return sink; } - public void setSink(MatchResultSink sink) { + public void setSink(@NotNull MatchResultSink sink) { this.sink = sink; } @@ -140,7 +142,7 @@ public class MatchContext { this.shouldRecursivelyMatch = shouldRecursivelyMatch; } - public void pushMatchedElementsListener(MatchedElementsListener matchedElementsListener) { + public void pushMatchedElementsListener(@NotNull MatchedElementsListener matchedElementsListener) { myMatchedElementsListenerStack.push(matchedElementsListener); } @@ -148,7 +150,7 @@ public class MatchContext { myMatchedElementsListenerStack.pop(); } - public void notifyMatchedElements(Collection matchedElements) { + public void notifyMatchedElements(@NotNull Collection matchedElements) { if (!myMatchedElementsListenerStack.isEmpty()) { myMatchedElementsListenerStack.peek().matchedElements(matchedElements); } @@ -167,7 +169,7 @@ public class MatchContext { getSink().newMatch(result); } - private boolean doDispatch(final MatchResult result) { + private boolean doDispatch(@NotNull MatchResult result) { boolean ret = false; for (MatchResult r : result.getChildren()) { @@ -182,7 +184,7 @@ public class MatchContext { return ret; } - private static void processNoSubstitutionMatch(List matchedNodes, MatchResultImpl result) { + private static void processNoSubstitutionMatch(@NotNull List matchedNodes, @NotNull MatchResultImpl result) { final boolean complexMatch = matchedNodes.size() > 1; final PsiElement match = matchedNodes.get(0); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchResultImpl.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchResultImpl.java index 9904dec4ca0a..df0812d8c52d 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchResultImpl.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchResultImpl.java @@ -5,6 +5,8 @@ import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.MatchResult; import com.intellij.structuralsearch.plugin.util.SmartPsiPointer; import com.intellij.util.SmartList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; @@ -20,16 +22,16 @@ public final class MatchResultImpl extends MatchResult { private boolean myScopeMatch; private boolean myMultipleMatch; - private MatchResultImpl parent = null; + private MatchResultImpl parent; MatchResultImpl() { } - public MatchResultImpl(String name, String image, SmartPsiPointer ref, boolean target) { - this(name,image,ref,0,-1,target); + public MatchResultImpl(@NotNull String name, @Nullable String image, @NotNull SmartPsiPointer ref, boolean target) { + this(name, image, ref, 0, -1, target); } - public MatchResultImpl(String name, String image, SmartPsiPointer ref, int start, int end, boolean target) { + public MatchResultImpl(@NotNull String name, @Nullable String image, @NotNull SmartPsiPointer ref, int start, int end, boolean target) { matchRef = ref; this.name = name; matchImage = image; @@ -56,7 +58,7 @@ public final class MatchResultImpl extends MatchResult { return matchRef.getElement(); } - public void setMatchRef(SmartPsiPointer matchStart) { + public void setMatchRef(@NotNull SmartPsiPointer matchStart) { matchRef = matchStart; } @@ -65,12 +67,12 @@ public final class MatchResultImpl extends MatchResult { return name; } - public void setName(String name) { + public void setName(@NotNull String name) { this.name = name; } @Override - public List getChildren() { + public @NotNull List getChildren() { return Collections.unmodifiableList(myChildren); } @@ -90,21 +92,6 @@ public final class MatchResultImpl extends MatchResult { return myMultipleMatch; } - public void clear() { - if (matchRef != null) { - matchRef.clear(); - matchRef = null; - } - - for (final MatchResult match : myChildren) { - ((MatchResultImpl)match).clear(); - } - myChildren.clear(); - - name = null; - matchImage = null; - } - @Override public boolean hasChildren() { return !myChildren.isEmpty(); @@ -114,6 +101,7 @@ public final class MatchResultImpl extends MatchResult { myChildren.clear(); } + @NotNull public MatchResult removeLastChild() { return myChildren.remove(myChildren.size() - 1); } @@ -126,7 +114,7 @@ public final class MatchResultImpl extends MatchResult { myMultipleMatch = multipleMatch; } - public MatchResultImpl findChild(String name) { + public MatchResultImpl findChild(@NotNull String name) { // @todo this could be performance bottleneck, replace with hash lookup! for (final MatchResult match : myChildren) { final MatchResultImpl res = (MatchResultImpl)match; @@ -138,7 +126,7 @@ public final class MatchResultImpl extends MatchResult { return null; } - public static MatchResultImpl findChildDeep(MatchResult match , String name) { + public static MatchResultImpl findChildDeep(@NotNull MatchResult match, @NotNull String name) { for (MatchResult child : match.getChildren()) { if (name.equals(child.getName())) { return (MatchResultImpl)child; @@ -151,7 +139,7 @@ public final class MatchResultImpl extends MatchResult { return null; } - public MatchResult removeChild(String typedVar) { + public MatchResult removeChild(@NotNull String typedVar) { // @todo this could be performance bottleneck, replace with hash lookup! for (int i = 0, size = myChildren.size(); i < size; i++) { final MatchResult child = myChildren.get(i); @@ -164,7 +152,7 @@ public final class MatchResultImpl extends MatchResult { return null; } - public void addChild(MatchResult result) { + public void addChild(@NotNull MatchResult result) { if (result instanceof MatchResultImpl) { ((MatchResultImpl)result).parent = this; } @@ -172,7 +160,7 @@ public final class MatchResultImpl extends MatchResult { } @Override - public MatchResult getRoot() { + public @NotNull MatchResult getRoot() { if (parent == null) return this; MatchResultImpl root = parent; while (root.parent != null) { @@ -181,7 +169,7 @@ public final class MatchResultImpl extends MatchResult { return root; } - public void setMatchImage(String matchImage) { + public void setMatchImage(@NotNull String matchImage) { this.matchImage = matchImage; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImplUtil.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImplUtil.java index b7883c5029fe..dc546336d1e4 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImplUtil.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImplUtil.java @@ -8,21 +8,25 @@ import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.PatternContextInfo; import com.intellij.structuralsearch.StructuralSearchProfile; import com.intellij.structuralsearch.StructuralSearchUtil; +import org.jetbrains.annotations.NotNull; /** * @author Maxim.Mossienko */ public final class MatcherImplUtil { - public static PsiElement[] createTreeFromText(String text, PatternTreeContext context, LanguageFileType fileType, Project project) { - return createTreeFromText(text, new PatternContextInfo(context), fileType, null, project, false); + public static PsiElement @NotNull [] createTreeFromText(@NotNull String text, + @NotNull PatternTreeContext context, + @NotNull LanguageFileType fileType, + @NotNull Project project) { + return createTreeFromText(text, new PatternContextInfo(context), fileType, fileType.getLanguage(), project, false); } - public static PsiElement[] createSourceTreeFromText(String text, - PatternTreeContext context, - LanguageFileType fileType, - Project project, - boolean physical) { + public static PsiElement @NotNull [] createSourceTreeFromText(@NotNull String text, + @NotNull PatternTreeContext context, + @NotNull LanguageFileType fileType, + @NotNull Project project, + boolean physical) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(fileType.getLanguage()); if (profile != null) { return profile.createPatternTree(text, context, fileType, fileType.getLanguage(), null, project, physical); @@ -30,15 +34,12 @@ public final class MatcherImplUtil { return PsiElement.EMPTY_ARRAY; } - public static PsiElement[] createTreeFromText(String text, - PatternContextInfo contextInfo, - LanguageFileType fileType, - Language language, - Project project, - boolean physical) { - if (language == null) { - language = fileType.getLanguage(); - } + public static PsiElement @NotNull [] createTreeFromText(@NotNull String text, + @NotNull PatternContextInfo contextInfo, + @NotNull LanguageFileType fileType, + @NotNull Language language, + @NotNull Project project, + boolean physical) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language); if (profile != null) { return profile.createPatternTree(text, contextInfo, fileType, language, project, physical); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/XmlMatchingVisitor.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/XmlMatchingVisitor.java index 03abfab1c67e..b5c5e33a0440 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/XmlMatchingVisitor.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/XmlMatchingVisitor.java @@ -12,6 +12,7 @@ import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler; import com.intellij.structuralsearch.impl.matcher.iterators.ListNodeIterator; import com.intellij.structuralsearch.impl.matcher.iterators.SsrFilteringNodeIterator; import com.intellij.xml.util.XmlUtil; +import org.jetbrains.annotations.NotNull; /** * @author Eugene.Kudelevsky @@ -19,7 +20,7 @@ import com.intellij.xml.util.XmlUtil; public class XmlMatchingVisitor extends XmlElementVisitor { private final GlobalMatchingVisitor myMatchingVisitor; - public XmlMatchingVisitor(GlobalMatchingVisitor matchingVisitor) { + public XmlMatchingVisitor(@NotNull GlobalMatchingVisitor matchingVisitor) { myMatchingVisitor = matchingVisitor; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/CompileContext.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/CompileContext.java index 3935b7bb56e8..a267196e6c71 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/CompileContext.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/CompileContext.java @@ -5,6 +5,7 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.structuralsearch.MatchOptions; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; +import org.jetbrains.annotations.NotNull; /** * @author maxim @@ -16,7 +17,7 @@ public class CompileContext { private final MatchOptions myOptions; private final Project myProject; - public CompileContext(CompiledPattern pattern, MatchOptions options, Project project) { + public CompileContext(@NotNull CompiledPattern pattern, @NotNull MatchOptions options, @NotNull Project project) { myPattern = pattern; myOptions = options; myProject = project; @@ -30,18 +31,22 @@ public class CompileContext { mySearchHelper.clear(); } + @NotNull public OptimizingSearchHelper getSearchHelper() { return mySearchHelper; } + @NotNull public CompiledPattern getPattern() { return myPattern; } + @NotNull public MatchOptions getOptions() { return myOptions; } + @NotNull public Project getProject() { return myProject; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/DeleteNodesAction.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/DeleteNodesAction.java index 5810279e5281..cb9a051b20d3 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/DeleteNodesAction.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/DeleteNodesAction.java @@ -1,6 +1,7 @@ package com.intellij.structuralsearch.impl.matcher.compiler; import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; import java.util.List; @@ -8,11 +9,11 @@ class DeleteNodesAction implements Runnable { private final List elements; - DeleteNodesAction(List _elements) { + DeleteNodesAction(@NotNull List _elements) { elements = _elements; } - private static void delete(PsiElement first, PsiElement last) { + private static void delete(@NotNull PsiElement first, PsiElement last) { if (last == first) { first.delete(); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/FindInFilesOptimizingSearchHelper.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/FindInFilesOptimizingSearchHelper.java index bbbbbbd3f8d6..a5925fe7f363 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/FindInFilesOptimizingSearchHelper.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/FindInFilesOptimizingSearchHelper.java @@ -18,21 +18,21 @@ import static com.intellij.psi.search.UsageSearchContext.*; * @author Maxim.Mossienko */ class FindInFilesOptimizingSearchHelper extends OptimizingSearchHelperBase { - private THashSet filesToScan; - private THashSet filesToScan2; + private Set filesToScan; + private Set filesToScan2; private final Project myProject; private final SearchScope myScope; private final boolean myCaseSensitive; - private boolean myTransactionStarted = false; + private boolean myTransactionStarted; - FindInFilesOptimizingSearchHelper(SearchScope scope, boolean caseSensitive, Project project) { + FindInFilesOptimizingSearchHelper(SearchScope scope, boolean caseSensitive, @NotNull Project project) { myScope = scope; myCaseSensitive = caseSensitive; myProject = project; - if (scope instanceof GlobalSearchScope && filesToScan == null) { + if (scope instanceof GlobalSearchScope) { filesToScan = new THashSet<>(); filesToScan2 = new THashSet<>(); } @@ -90,7 +90,7 @@ class FindInFilesOptimizingSearchHelper extends OptimizingSearchHelperBase { if (!myTransactionStarted) return; myTransactionStarted = false; super.endTransaction(); - final THashSet map = filesToScan; + Set map = filesToScan; if (!map.isEmpty()) map.clear(); filesToScan = filesToScan2; filesToScan2 = map; @@ -106,7 +106,7 @@ class FindInFilesOptimizingSearchHelper extends OptimizingSearchHelperBase { return filesToScan; } - private void process(VirtualFile[] files) { + private void process(VirtualFile @NotNull [] files) { if (scanRequest == 0) { Collections.addAll(filesToScan2, files); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/GlobalCompilingVisitor.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/GlobalCompilingVisitor.java index cdd6395c2750..d42d550baf4c 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/GlobalCompilingVisitor.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/GlobalCompilingVisitor.java @@ -16,6 +16,7 @@ import com.intellij.structuralsearch.impl.matcher.predicates.RegExpPredicate; import com.intellij.util.SmartList; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -34,11 +35,12 @@ public class GlobalCompilingVisitor { private final List myLexicalNodes = new SmartList<>(); private int myCodeBlockLevel; + @NotNull public static NodeFilter getFilter() { return ourFilter; } - public void setHandler(PsiElement element, MatchingHandler handler) { + public void setHandler(@NotNull PsiElement element, @NotNull MatchingHandler handler) { MatchingHandler realHandler = context.getPattern().getHandlerSimple(element); if (realHandler instanceof SubstitutionHandler) { @@ -50,7 +52,7 @@ public class GlobalCompilingVisitor { } } - public final void handle(PsiElement element) { + public final void handle(@NotNull PsiElement element) { if ((!ourFilter.accepts(element) || StructuralSearchUtil.isIdentifier(element)) && context.getPattern().isRealTypedVar(element) && @@ -83,7 +85,7 @@ public class GlobalCompilingVisitor { this.myCodeBlockLevel = codeBlockLevel; } - public static void setFilter(MatchingHandler handler, NodeFilter filter) { + public static void setFilter(@NotNull MatchingHandler handler, @NotNull NodeFilter filter) { if (handler.getFilter() != null && handler.getFilter().getClass() != filter.getClass()) { // for constructor we will have the same handler for class and method and tokens itself handler.setFilter(new CompositeNodeFilter(filter, handler.getFilter())); @@ -93,19 +95,20 @@ public class GlobalCompilingVisitor { } } - public void setFilterSimple(PsiElement element, NodeFilter filter) { + public void setFilterSimple(@NotNull PsiElement element, @NotNull NodeFilter filter) { context.getPattern().getHandler(element).setFilter(filter); } + @NotNull public List getLexicalNodes() { return myLexicalNodes; } - public void addLexicalNode(PsiElement node) { + public void addLexicalNode(@NotNull PsiElement node) { myLexicalNodes.add(node); } - void compile(PsiElement[] elements, CompileContext context) { + void compile(PsiElement @NotNull [] elements, @NotNull CompileContext context) { if (elements.length == 0) { throw new MalformedPatternException(); } @@ -119,17 +122,17 @@ public class GlobalCompilingVisitor { assert context.getPattern().getStrategy() != null; } - public boolean hasFragments(String pattern) { + public boolean hasFragments(@NotNull String pattern) { return ourSubstitutionPattern.matcher(pattern).find(); } @Nullable - public MatchingHandler processPatternStringWithFragments(String pattern, OccurenceKind kind) { + public MatchingHandler processPatternStringWithFragments(@NotNull String pattern, @NotNull OccurenceKind kind) { return processPatternStringWithFragments(pattern, kind, ourSubstitutionPattern); } @Nullable - public MatchingHandler processPatternStringWithFragments(String pattern, OccurenceKind kind, Pattern substitutionPattern) { + public MatchingHandler processPatternStringWithFragments(@NotNull String pattern, @NotNull OccurenceKind kind, @NotNull Pattern substitutionPattern) { String content; if (kind == OccurenceKind.LITERAL) { @@ -157,7 +160,7 @@ public class GlobalCompilingVisitor { hasLiteralContent = true; buf.append(StructuralSearchUtil.makeExtremeSpacesOptional(StructuralSearchUtil.shieldRegExpMetaChars(word))); - processTokenizedName(word, false, kind); + processTokenizedName(word, kind); } handler = (SubstitutionHandler)getContext().getPattern().getHandler(matcher.group(1)); @@ -174,7 +177,7 @@ public class GlobalCompilingVisitor { } if (isSuitablePredicate(predicate, handler)) { - processTokenizedName(predicate.getRegExp(), false, kind); + processTokenizedName(predicate.getRegExp(), kind); } start = matcher.end(); @@ -186,7 +189,7 @@ public class GlobalCompilingVisitor { hasLiteralContent = true; buf.append(StructuralSearchUtil.makeExtremeSpacesOptional(StructuralSearchUtil.shieldRegExpMetaChars(word))); - processTokenizedName(word, false, kind); + processTokenizedName(word, kind); } if (hasLiteralContent) { @@ -206,14 +209,14 @@ public class GlobalCompilingVisitor { } @Contract("null,_ -> false") - public static boolean isSuitablePredicate(RegExpPredicate predicate, SubstitutionHandler handler) { + public static boolean isSuitablePredicate(RegExpPredicate predicate, @NotNull SubstitutionHandler handler) { return predicate != null && handler.getMinOccurs() != 0 && predicate.couldBeOptimized(); } - public static void addFilesToSearchForGivenWord(String word, + public static void addFilesToSearchForGivenWord(@NotNull String word, boolean endTransaction, - GlobalCompilingVisitor.OccurenceKind kind, - CompileContext compileContext) { + @NotNull GlobalCompilingVisitor.OccurenceKind kind, + @NotNull CompileContext compileContext) { if (!compileContext.getSearchHelper().doOptimizing()) { return; } @@ -240,7 +243,7 @@ public class GlobalCompilingVisitor { } } - public void processTokenizedName(String name, boolean skipComments, GlobalCompilingVisitor.OccurenceKind kind) { + public void processTokenizedName(@NotNull String name, @NotNull GlobalCompilingVisitor.OccurenceKind kind) { if (kind == OccurenceKind.LITERAL) name = StringUtil.unescapeStringCharacters(name); for (String word : StringUtil.getWordsInStringLongestFirst(name)) { addFilesToSearchForGivenWord(word, true, kind, getContext()); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelper.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelper.java index 292b78ba7f73..7167c3db6dfa 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelper.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelper.java @@ -13,13 +13,13 @@ public interface OptimizingSearchHelper { boolean doOptimizing(); void clear(); - void addWordToSearchInCode(String word); + void addWordToSearchInCode(@NotNull String word); - void addWordToSearchInText(String word); + void addWordToSearchInText(@NotNull String word); - void addWordToSearchInComments(String word); + void addWordToSearchInComments(@NotNull String word); - void addWordToSearchInLiterals(String word); + void addWordToSearchInLiterals(@NotNull String word); void endTransaction(); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelperBase.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelperBase.java index 65792b42081b..f8b469160f3d 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelperBase.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/OptimizingSearchHelperBase.java @@ -4,24 +4,18 @@ package com.intellij.structuralsearch.impl.matcher.compiler; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; +import java.util.Set; + /** * @author Maxim.Mossienko */ abstract class OptimizingSearchHelperBase implements OptimizingSearchHelper { - private final THashSet scanned; - private final THashSet scannedText; - private final THashSet scannedComments; - private final THashSet scannedLiterals; + private final Set scanned = new THashSet<>(); + private final Set scannedText = new THashSet<>(); + private final Set scannedComments = new THashSet<>(); + private final Set scannedLiterals = new THashSet<>(); protected int scanRequest; - OptimizingSearchHelperBase() { - scanRequest = 0; - scanned = new THashSet<>(); - scannedText = new THashSet<>(); - scannedComments = new THashSet<>(); - scannedLiterals = new THashSet<>(); - } - @Override public void clear() { scanned.clear(); @@ -31,29 +25,29 @@ abstract class OptimizingSearchHelperBase implements OptimizingSearchHelper { } @Override - public void addWordToSearchInCode(String word) { - if (word != null && doOptimizing() && scanned.add(word)) { + public void addWordToSearchInCode(@NotNull String word) { + if (doOptimizing() && scanned.add(word)) { doAddSearchWordInCode(word); } } @Override - public void addWordToSearchInText(String word) { - if (word != null && doOptimizing() && scannedText.add(word)) { + public void addWordToSearchInText(@NotNull String word) { + if (doOptimizing() && scannedText.add(word)) { doAddSearchWordInText(word); } } @Override - public void addWordToSearchInComments(String word) { - if (word != null && doOptimizing() && scannedComments.add(word)) { + public void addWordToSearchInComments(@NotNull String word) { + if (doOptimizing() && scannedComments.add(word)) { doAddSearchWordInComments(word); } } @Override - public void addWordToSearchInLiterals(String word) { - if (word != null && doOptimizing() && scannedLiterals.add(word)) { + public void addWordToSearchInLiterals(@NotNull String word) { + if (doOptimizing() && scannedLiterals.add(word)) { doAddSearchWordInLiterals(word); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java index ab3f896025cf..fbb81acab34a 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java @@ -56,7 +56,7 @@ public final class PatternCompiler { } @Nullable - private static CompiledPattern doCompilePattern(Project project, MatchOptions options, + private static CompiledPattern doCompilePattern(@NotNull Project project, @NotNull MatchOptions options, boolean checkForErrors, boolean optimizeScope) throws MalformedPatternException, NoMatchFoundException { @@ -84,7 +84,8 @@ public final class PatternCompiler { optimizeScope(options, checkForErrors, context, result); } return result; - } finally { + } + finally { context.clear(); } } @@ -176,10 +177,10 @@ public final class PatternCompiler { } @NotNull - private static List compileByAllPrefixes(Project project, - MatchOptions options, - CompiledPattern pattern, - CompileContext context, + private static List compileByAllPrefixes(@NotNull Project project, + @NotNull MatchOptions options, + @NotNull CompiledPattern pattern, + @NotNull CompileContext context, String @NotNull [] applicablePrefixes, boolean checkForErrors) throws MalformedPatternException { if (applicablePrefixes.length == 0) { @@ -396,11 +397,12 @@ public final class PatternCompiler { } } - private static List doCompile(Project project, - MatchOptions options, - CompiledPattern result, - PrefixProvider prefixProvider, - CompileContext context, + @NotNull + private static List doCompile(@NotNull Project project, + @NotNull MatchOptions options, + @NotNull CompiledPattern result, + @NotNull PrefixProvider prefixProvider, + @NotNull CompileContext context, boolean checkForErrors) throws MalformedPatternException { result.clearHandlers(); @@ -524,7 +526,8 @@ public final class PatternCompiler { addExtensionPredicates(options, constraint, handler); addScriptConstraint(project, Configuration.CONTEXT_VAR_NAME, constraint, handler, variableNames, options, checkForErrors); - } catch (MalformedPatternException e) { + } + catch (MalformedPatternException e) { if (checkForErrors) throw e; } } @@ -564,7 +567,7 @@ public final class PatternCompiler { return elements; } - private static void addExtensionPredicates(MatchOptions options, MatchVariableConstraint constraint, SubstitutionHandler handler) { + private static void addExtensionPredicates(@NotNull MatchOptions options, @NotNull MatchVariableConstraint constraint, @NotNull SubstitutionHandler handler) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(options.getFileType()); assert profile != null; for (MatchPredicate matchPredicate : profile.getCustomPredicates(constraint, handler.getName(), options)) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/StringToConstraintsTransformer.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/StringToConstraintsTransformer.java index c02f64ec374b..7acc795ab2d1 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/StringToConstraintsTransformer.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/StringToConstraintsTransformer.java @@ -29,10 +29,11 @@ public final class StringToConstraintsTransformer { @NonNls private static final String WITHIN = "within"; @NonNls private static final String CONTEXT = "context"; - private static final Set knownOptions = ContainerUtil.set(REF, REGEX, REGEXW, EXPRTYPE, FORMAL, SCRIPT, CONTAINS, WITHIN, CONTEXT); + private static final Set knownOptions = + ContainerUtil.set(REF, REGEX, REGEXW, EXPRTYPE, FORMAL, SCRIPT, CONTAINS, WITHIN, CONTEXT); @SuppressWarnings("AssignmentToForLoopParameter") - public static void transformCriteria(@NotNull String criteria, MatchOptions options) { + public static void transformCriteria(@NotNull String criteria, @NotNull MatchOptions options) { final StringBuilder pattern = new StringBuilder(); int anonymousTypedVarsCount = 0; boolean targetFound = false; @@ -40,7 +41,7 @@ public final class StringToConstraintsTransformer { final MatchVariableConstraint context = options.addNewVariableConstraint(Configuration.CONTEXT_VAR_NAME); final int length = criteria.length(); - for(int index = 0; index < length; ++index) { + for (int index = 0; index < length; ++index) { char ch = criteria.charAt(index); if (index == 0 && ch == '[') { @@ -51,7 +52,7 @@ public final class StringToConstraintsTransformer { if (ch == '\\' && index + 1 < length) { ch = criteria.charAt(++index); } - else if (ch=='\'') { + else if (ch == '\'') { final int newIndex = handleCharacterLiteral(criteria, index, pattern); if (newIndex != index) { index = newIndex; @@ -65,14 +66,15 @@ public final class StringToConstraintsTransformer { boolean target = true; final String typedVar; - if (criteria.charAt(index)=='_') { + if (criteria.charAt(index) == '_') { target = false; - if(endIndex == index + 1) { + if (endIndex == index + 1) { // anonymous var, make it unique for the case of constraints anonymousTypedVarsCount++; typedVar = "_" + anonymousTypedVarsCount; - } else { + } + else { typedVar = criteria.substring(index + 1, endIndex); } } @@ -100,14 +102,17 @@ public final class StringToConstraintsTransformer { if (ch == '+') { maxOccurs = Integer.MAX_VALUE; ++index; - } else if (ch == '?') { + } + else if (ch == '?') { minOccurs = 0; ++index; - } else if (ch == '*') { + } + else if (ch == '*') { minOccurs = 0; maxOccurs = Integer.MAX_VALUE; ++index; - } else if (ch == '{') { + } + else if (ch == '{') { ++index; minOccurs = -1; maxOccurs = -1; @@ -118,7 +123,7 @@ public final class StringToConstraintsTransformer { ++index; } - if (ch==',') { + if (ch == ',') { ++index; while (index < length && (ch = criteria.charAt(index)) >= '0' && ch <= '9') { @@ -127,25 +132,36 @@ public final class StringToConstraintsTransformer { if (maxOccurs < 0) throw new MalformedPatternException(SSRBundle.message("error.overflow")); ++index; } - } else { + } + else { maxOccurs = -2; } if (ch != '}') { if (minOccurs < 0 && maxOccurs < 0) throw new MalformedPatternException(SSRBundle.message("error.expected.digit")); - if (maxOccurs < 0) throw new MalformedPatternException(SSRBundle.message("error.expected.brace1")); - else throw new MalformedPatternException(SSRBundle.message("error.expected.brace2")); + if (maxOccurs < 0) { + throw new MalformedPatternException(SSRBundle.message("error.expected.brace1")); + } + else { + throw new MalformedPatternException(SSRBundle.message("error.expected.brace2")); + } + } + if (minOccurs < 0 && maxOccurs < 0) { + throw new MalformedPatternException(SSRBundle.message("error.empty.quantifier")); + } + else if (minOccurs == -1) { + minOccurs = 0; + } + else if (maxOccurs == -1) { + maxOccurs = Integer.MAX_VALUE; } - if (minOccurs < 0 && maxOccurs < 0) throw new MalformedPatternException(SSRBundle.message("error.empty.quantifier")); - else if (minOccurs == -1) minOccurs = 0; - else if (maxOccurs == -1) maxOccurs = Integer.MAX_VALUE; else if (maxOccurs == -2) maxOccurs = minOccurs; ++index; } if (index < length) { ch = criteria.charAt(index); - if (ch=='?') { + if (ch == '?') { greedy = false; ++index; } @@ -175,8 +191,9 @@ public final class StringToConstraintsTransformer { pattern.append(ch); } else { - if (!constraintCreated) + if (!constraintCreated) { throw new MalformedPatternException(SSRBundle.message("error.condition.only.on.first.variable.reference")); + } index = handleTypedVarCondition(index, criteria, constraint); } } @@ -197,21 +214,27 @@ public final class StringToConstraintsTransformer { options.setSearchPattern(pattern.toString()); } - public static int handleCharacterLiteral(String criteria, int index, StringBuilder pattern) { + public static int handleCharacterLiteral(@NotNull String criteria, int index, @NotNull StringBuilder pattern) { final int length = criteria.length(); if (index + 1 < length && criteria.charAt(index + 1) == '\'') { // ignore next ' pattern.append('\''); return index + 1; - } else if (index + 2 < length && criteria.charAt(index + 2) == '\'') { + } + else if (index + 2 < length && criteria.charAt(index + 2) == '\'') { // eat simple character pattern.append(criteria, index, index + 3); return index + 2; - } else if (index + 3 < length && criteria.charAt(index + 1) == '\\' && criteria.charAt(index + 3) == '\'') { + } + else if (index + 3 < length && criteria.charAt(index + 1) == '\\' && criteria.charAt(index + 3) == '\'') { // eat simple escape character pattern.append(criteria, index, index + 4); return index + 3; - } else if (index + 7 < length && criteria.charAt(index + 1) == '\\' && criteria.charAt(index + 2) == 'u' && criteria.charAt(index + 7) == '\'') { + } + else if (index + 7 < length && + criteria.charAt(index + 1) == '\\' && + criteria.charAt(index + 2) == 'u' && + criteria.charAt(index + 7) == '\'') { // eat unicode escape character pattern.append(criteria, index, index + 8); return index + 7; @@ -219,7 +242,7 @@ public final class StringToConstraintsTransformer { return index; } - private static int handleTypedVarCondition(int index, String criteria, MatchVariableConstraint constraint) { + private static int handleTypedVarCondition(int index, @NotNull String criteria, @NotNull MatchVariableConstraint constraint) { final int length = criteria.length(); char ch = criteria.charAt(index); @@ -231,7 +254,7 @@ public final class StringToConstraintsTransformer { } if (ch == '+' || ch == '*') { // this is type axis navigation relation - switch(ch) { + switch (ch) { case '+': constraint.setStrictlyWithinHierarchy(true); break; @@ -252,7 +275,9 @@ public final class StringToConstraintsTransformer { while (++endIndex < length) { if (criteria.charAt(endIndex - 1) != '\\') { ch = criteria.charAt(endIndex); - if (ch == '"') quoted = !quoted; + if (ch == '"') { + quoted = !quoted; + } else if (ch == ']' && !quoted) break; } } @@ -267,7 +292,7 @@ public final class StringToConstraintsTransformer { } } - private static int handleRegExp(int index, String criteria, MatchVariableConstraint constraint) { + private static int handleRegExp(int index, @NotNull String criteria, @NotNull MatchVariableConstraint constraint) { final int length = criteria.length(); int endIndex = index; while (endIndex < length && !Character.isWhitespace(criteria.charAt(endIndex))) { @@ -275,8 +300,12 @@ public final class StringToConstraintsTransformer { } if (endIndex == index) { - if (criteria.charAt(index - 1) == ':') throw new MalformedPatternException(SSRBundle.message("error.expected.condition", ":")); - else return endIndex; + if (criteria.charAt(index - 1) == ':') { + throw new MalformedPatternException(SSRBundle.message("error.expected.condition", ":")); + } + else { + return endIndex; + } } final String regexp = criteria.substring(index, endIndex); @@ -292,7 +321,7 @@ public final class StringToConstraintsTransformer { } @SuppressWarnings("AssignmentToForLoopParameter") - private static void parseCondition(MatchVariableConstraint constraint, String condition) { + private static void parseCondition(@NotNull MatchVariableConstraint constraint, @NotNull String condition) { final int length = condition.length(); final StringBuilder text = new StringBuilder(); boolean invert = false; @@ -319,7 +348,9 @@ public final class StringToConstraintsTransformer { while (++i < length) { c = condition.charAt(i); if (condition.charAt(i - 1) != '\\') { - if (c == '"') quoted = !quoted; + if (c == '"') { + quoted = !quoted; + } else if (c == ')' && !quoted) { int j = 1; while (j <= spaces && condition.charAt(i - j) == ' ') j++; @@ -333,8 +364,10 @@ public final class StringToConstraintsTransformer { } if (text.length() == 0) throw new MalformedPatternException(SSRBundle.message("error.argument.expected", option)); if (quoted) throw new MalformedPatternException(SSRBundle.message("error.expected.value", "\"")); - if (!closed) throw new MalformedPatternException(SSRBundle.message("error.expected.value", - StringUtil.repeatSymbol(' ', spaces) + ")")); + if (!closed) { + throw new MalformedPatternException(SSRBundle.message("error.expected.value", + StringUtil.repeatSymbol(' ', spaces) + ")")); + } handleOption(constraint, option, text.toString(), invert); text.setLength(0); invert = false; @@ -345,8 +378,9 @@ public final class StringToConstraintsTransformer { handleOption(constraint, text.toString(), "", invert); optionExpected = false; } - if (++i == length || condition.charAt(i) != '&' || optionExpected) + if (++i == length || condition.charAt(i) != '&' || optionExpected) { throw new MalformedPatternException(SSRBundle.message("error.unexpected.value", "&")); + } text.setLength(0); invert = false; optionExpected = true; @@ -365,7 +399,9 @@ public final class StringToConstraintsTransformer { if (text.length() != 0) { handleOption(constraint, text.toString(), "", invert); } - else if (invert) throw new MalformedPatternException(SSRBundle.message("error.expected.condition", "!")); + else if (invert) { + throw new MalformedPatternException(SSRBundle.message("error.expected.condition", "!")); + } else if (optionExpected) throw new MalformedPatternException(SSRBundle.message("error.expected.condition", length == 0 ? "[" : "&&")); } @@ -415,15 +451,17 @@ public final class StringToConstraintsTransformer { constraint.setInvertContainsConstraint(invert); } else if (option.equals(WITHIN)) { - if (!Configuration.CONTEXT_VAR_NAME.equals(constraint.getName())) + if (!Configuration.CONTEXT_VAR_NAME.equals(constraint.getName())) { throw new MalformedPatternException(SSRBundle.message("error.only.applicable.to.complete.match", option)); + } constraint.setWithinConstraint(argument); constraint.setInvertWithinConstraint(invert); } else if (option.equals(CONTEXT)) { if (invert) throw new MalformedPatternException(SSRBundle.message("error.cannot.invert", option)); - if (!Configuration.CONTEXT_VAR_NAME.equals(constraint.getName())) + if (!Configuration.CONTEXT_VAR_NAME.equals(constraint.getName())) { throw new MalformedPatternException(SSRBundle.message("error.only.applicable.to.complete.match", option)); + } constraint.setContextConstraint(argument); } else if (option.startsWith("_")) { @@ -444,7 +482,8 @@ public final class StringToConstraintsTransformer { } } - private static String unescape(String s) { + @NotNull + private static String unescape(@NotNull String s) { final StringBuilder result = new StringBuilder(); boolean escaped = false; for (int i = 0, length = s.length(); i < length; i++) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/TestModeOptimizingSearchHelper.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/TestModeOptimizingSearchHelper.java index 5bc09ac31638..eb3e663f2340 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/TestModeOptimizingSearchHelper.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/TestModeOptimizingSearchHelper.java @@ -14,7 +14,7 @@ import java.util.Set; */ class TestModeOptimizingSearchHelper extends OptimizingSearchHelperBase { private final StringBuilder builder = new StringBuilder(); - private boolean myTransactionStarted = false; + private boolean myTransactionStarted; private final List myWords = new SmartList<>(); @@ -23,7 +23,7 @@ class TestModeOptimizingSearchHelper extends OptimizingSearchHelperBase { return true; } - private void append(final String word, final String prefix) { + private void append(@NotNull String word, @NotNull String prefix) { myWords.add(prefix + word); myTransactionStarted = true; } @@ -77,6 +77,7 @@ class TestModeOptimizingSearchHelper extends OptimizingSearchHelperBase { return Collections.emptySet(); } + @NotNull public String getSearchPlan() { assert !myTransactionStarted; final String plan = builder.toString(); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/WordOptimizer.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/WordOptimizer.java index de82e1594353..a8681f525da6 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/WordOptimizer.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/WordOptimizer.java @@ -6,6 +6,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler; import com.intellij.structuralsearch.impl.matcher.predicates.RegExpPredicate; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; @@ -69,7 +70,8 @@ public interface WordOptimizer { * @param className the name of the class to search for subclasses of * @param includeSelf include the class itself in the search */ - default List getDescendantsOf(String className, boolean includeSelf, Project project) { + @NotNull + default List getDescendantsOf(@NotNull String className, boolean includeSelf, @NotNull Project project) { return Collections.emptyList(); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/XmlCompilingVisitor.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/XmlCompilingVisitor.java index 762d91dcf8b3..ed9e2cdec2ed 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/XmlCompilingVisitor.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/XmlCompilingVisitor.java @@ -20,14 +20,15 @@ import static com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilin * @author Eugene.Kudelevsky */ public class XmlCompilingVisitor extends XmlRecursiveElementVisitor { - final GlobalCompilingVisitor myCompilingVisitor; + @NotNull + private final GlobalCompilingVisitor myCompilingVisitor; private final XmlWordOptimizer myOptimizer = new XmlWordOptimizer(); - public XmlCompilingVisitor(GlobalCompilingVisitor compilingVisitor) { + public XmlCompilingVisitor(@NotNull GlobalCompilingVisitor compilingVisitor) { this.myCompilingVisitor = compilingVisitor; } - public void compile(PsiElement[] topLevelElements) { + public void compile(PsiElement @NotNull [] topLevelElements) { final CompileContext context = myCompilingVisitor.getContext(); final CompiledPattern pattern = context.getPattern(); final MatchOptions options = context.getOptions(); @@ -39,12 +40,11 @@ public class XmlCompilingVisitor extends XmlRecursiveElementVisitor { } } - public void optimize(PsiElement element) { + public void optimize(@NotNull PsiElement element) { element.accept(myOptimizer); } private class XmlWordOptimizer extends XmlRecursiveElementWalkingVisitor implements WordOptimizer { - @Override public void visitXmlTag(XmlTag tag) { if (!handleWord(tag.getName(), CODE, myCompilingVisitor.getContext())) return; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/CompositeNodeFilter.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/CompositeNodeFilter.java index 2c7bc70ab0a1..c03cf22bc9e8 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/CompositeNodeFilter.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/CompositeNodeFilter.java @@ -2,19 +2,20 @@ package com.intellij.structuralsearch.impl.matcher.filters; import com.intellij.dupLocator.util.NodeFilter; import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; public class CompositeNodeFilter implements NodeFilter { private final NodeFilter first; private final NodeFilter second; + public CompositeNodeFilter(@NotNull NodeFilter _first, @NotNull NodeFilter _second) { + first = _first; + second = _second; + } + @Override public boolean accepts(PsiElement element) { return first.accepts(element) || second.accepts(element); } - - public CompositeNodeFilter(NodeFilter _first, NodeFilter _second) { - first = _first; - second = _second; - } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/DefaultFilter.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/DefaultFilter.java index 1059dfbd4dd3..da7c0f77355f 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/DefaultFilter.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/DefaultFilter.java @@ -3,12 +3,14 @@ package com.intellij.structuralsearch.impl.matcher.filters; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.LeafElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * Default searching filter */ public final class DefaultFilter { - public static boolean accepts(PsiElement patternNode, PsiElement matchNode) { + public static boolean accepts(@NotNull PsiElement patternNode, @Nullable PsiElement matchNode) { if (patternNode instanceof LeafElement && matchNode instanceof LeafElement) { return ((LeafElement)patternNode).getElementType() == ((LeafElement)matchNode).getElementType(); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/LexicalNodesFilter.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/LexicalNodesFilter.java index f92086162955..99f7601c5c54 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/LexicalNodesFilter.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/filters/LexicalNodesFilter.java @@ -11,7 +11,7 @@ import com.intellij.structuralsearch.StructuralSearchUtil; */ public final class LexicalNodesFilter implements NodeFilter { - LexicalNodesFilter() {} + private LexicalNodesFilter() {} public static NodeFilter getInstance() { return NodeFilterHolder.INSTANCE; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LightTopLevelMatchingHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LightTopLevelMatchingHandler.java index f02c1175e802..00d592b428e9 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LightTopLevelMatchingHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LightTopLevelMatchingHandler.java @@ -14,22 +14,22 @@ public final class LightTopLevelMatchingHandler extends MatchingHandler implemen } @Override - public boolean match(final PsiElement patternNode, final PsiElement matchedNode, final MatchContext matchContext) { + public boolean match(final PsiElement patternNode, final PsiElement matchedNode, final @NotNull MatchContext matchContext) { return myDelegate.match(patternNode, matchedNode, matchContext); } @Override - public boolean canMatch(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean canMatch(@NotNull PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { return myDelegate.canMatch(patternNode, matchedNode, context); } @Override - public boolean matchSequentially(final NodeIterator patternNodes, final NodeIterator matchNodes, final MatchContext context) { + public boolean matchSequentially(final @NotNull NodeIterator patternNodes, final @NotNull NodeIterator matchNodes, final @NotNull MatchContext context) { return myDelegate.matchSequentially(patternNodes, matchNodes, context); } @Override - public boolean isMatchSequentiallySucceeded(final NodeIterator matchNodes) { + public boolean isMatchSequentiallySucceeded(final @NotNull NodeIterator matchNodes) { return true; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LiteralWithSubstitutionHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LiteralWithSubstitutionHandler.java index 17a374f70c8c..eca8165c978b 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LiteralWithSubstitutionHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/LiteralWithSubstitutionHandler.java @@ -3,6 +3,7 @@ package com.intellij.structuralsearch.impl.matcher.handlers; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.regex.Matcher; @@ -21,11 +22,11 @@ public class LiteralWithSubstitutionHandler extends MatchingHandler { } @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { return match(matchedNode, matchedNode.getText(), 0, context); } - public boolean match(PsiElement matchedNode, String text, int textOffset, MatchContext context) { + public boolean match(@NotNull PsiElement matchedNode, @NotNull String text, int textOffset, @NotNull MatchContext context) { if (myMatcher == null) { myMatcher = Pattern.compile(myRegexp, (myCaseSensitive ? 0 : Pattern.CASE_INSENSITIVE) | Pattern.DOTALL).matcher(text); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/MatchingHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/MatchingHandler.java index 4e4f2a013ae2..c6c815dc198a 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/MatchingHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/MatchingHandler.java @@ -13,6 +13,7 @@ import com.intellij.structuralsearch.impl.matcher.MatchResultImpl; import com.intellij.structuralsearch.impl.matcher.filters.DefaultFilter; import com.intellij.structuralsearch.impl.matcher.strategies.MatchingStrategy; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.HashSet; import java.util.Set; @@ -28,9 +29,8 @@ public abstract class MatchingHandler { /** * Node filters determine which kind of PsiElements can match the pattern element. * Filters are applied to MatchingHandlers in the CompilingVisitor. - * @param filter */ - public void setFilter(NodeFilter filter) { + public void setFilter(@Nullable NodeFilter filter) { this.filter = filter; } @@ -40,15 +40,15 @@ public abstract class MatchingHandler { * @param context of the matching * @return true if matching was successful and false otherwise */ - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { return (patternNode == null) ? matchedNode == null : canMatch(patternNode, matchedNode, context); } - public boolean canMatch(final PsiElement patternNode, final PsiElement matchedNode, MatchContext context) { + public boolean canMatch(@NotNull PsiElement patternNode, final PsiElement matchedNode, @NotNull MatchContext context) { return (filter != null) ? filter.accepts(matchedNode) : DefaultFilter.accepts(patternNode, matchedNode); } - public boolean matchSequentially(NodeIterator patternNodes, NodeIterator matchNodes, MatchContext context) { + public boolean matchSequentially(@NotNull NodeIterator patternNodes, @NotNull NodeIterator matchNodes, @NotNull MatchContext context) { final MatchingStrategy strategy = context.getPattern().getStrategy(); final PsiElement currentPatternNode = patternNodes.current(); final PsiElement currentMatchNode = matchNodes.current(); @@ -89,18 +89,18 @@ public abstract class MatchingHandler { return false; } - private static void skipComments(NodeIterator matchNodes, PsiElement patternNode) { + private static void skipComments(@NotNull NodeIterator matchNodes, PsiElement patternNode) { if (patternNode instanceof PsiComment) return; while (matchNodes.current() instanceof PsiComment) matchNodes.advance(); } - private static void skipIfNecessary(NodeIterator nodes, PsiElement elementToMatchWith, MatchingStrategy strategy) { + private static void skipIfNecessary(@NotNull NodeIterator nodes, PsiElement elementToMatchWith, @NotNull MatchingStrategy strategy) { while (nodes.hasNext() && strategy.shouldSkip(nodes.current(), elementToMatchWith)) { nodes.advance(); } } - protected boolean isMatchSequentiallySucceeded(final NodeIterator matchNodes) { + protected boolean isMatchSequentiallySucceeded(@NotNull NodeIterator matchNodes) { skipComments(matchNodes, null); return !matchNodes.hasNext(); } @@ -112,7 +112,8 @@ public abstract class MatchingHandler { super(true); } - @Override public void visitElement(@NotNull PsiElement element) { + @Override + public void visitElement(@NotNull PsiElement element) { // We do not reset certain handlers because they are also bound to higher level nodes // e.g. Identifier handler in name is also bound to PsiMethod if (pattern.isToResetHandler(element)) { @@ -124,7 +125,7 @@ public abstract class MatchingHandler { super.visitElement(element); } - synchronized void clearState(CompiledPattern _pattern, PsiElement el) { + synchronized void clearState(@NotNull CompiledPattern _pattern, @NotNull PsiElement el) { pattern = _pattern; el.acceptChildren(this); pattern = null; @@ -133,7 +134,7 @@ public abstract class MatchingHandler { protected static ClearStateVisitor clearingVisitor = new ClearStateVisitor(); - public boolean matchInAnyOrder(NodeIterator patternNodes, NodeIterator matchedNodes, final MatchContext context) { + public static boolean matchInAnyOrder(@NotNull NodeIterator patternNodes, @NotNull NodeIterator matchedNodes, @NotNull MatchContext context) { final MatchResultImpl saveResult = context.hasResult() ? context.getResult() : null; context.setResult(null); @@ -207,7 +208,7 @@ public abstract class MatchingHandler { } } - protected static boolean validateSatisfactionOfHandlers(NodeIterator patternNodes, MatchContext context) { + protected static boolean validateSatisfactionOfHandlers(@NotNull NodeIterator patternNodes, @NotNull MatchContext context) { for (; patternNodes.hasNext(); patternNodes.advance()) { if (!context.getPattern().getHandler(patternNodes.current()).validate(context, 0)) { return false; @@ -216,7 +217,7 @@ public abstract class MatchingHandler { return true; } - boolean validate(MatchContext context, int matchedOccurs) { + boolean validate(@NotNull MatchContext context, int matchedOccurs) { return matchedOccurs == 1; } @@ -224,7 +225,7 @@ public abstract class MatchingHandler { return filter; } - public boolean shouldAdvanceThePatternFor(PsiElement patternElement, PsiElement matchedElement) { + public boolean shouldAdvanceThePatternFor(@NotNull PsiElement patternElement, @NotNull PsiElement matchedElement) { return true; } @@ -240,7 +241,7 @@ public abstract class MatchingHandler { return pinnedElement; } - public void setPinnedElement(final PsiElement pinnedElement) { + public void setPinnedElement(@NotNull PsiElement pinnedElement) { this.pinnedElement = pinnedElement; } } \ No newline at end of file diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SimpleHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SimpleHandler.java index f4fdb712815e..308b28e6b5d3 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SimpleHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SimpleHandler.java @@ -3,6 +3,7 @@ package com.intellij.structuralsearch.impl.matcher.handlers; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; /** * Handles simplest type of the match: one node from the pattern to one node of the code. @@ -15,7 +16,7 @@ public final class SimpleHandler extends MatchingHandler { * @return true if matching was successful and false otherwise */ @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { if (!super.match(patternNode, matchedNode, context)) return false; return context.getMatcher().match(patternNode, matchedNode); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SkippingHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SkippingHandler.java index 1a5e7f1d0c8e..713ee0a7d8ac 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SkippingHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SkippingHandler.java @@ -24,7 +24,7 @@ public class SkippingHandler extends MatchingHandler implements DelegatingHandle } @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, final MatchContext matchContext) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, final @NotNull MatchContext matchContext) { if (patternNode == null || matchedNode == null || matchedNode.getClass() == patternNode.getClass()) { return myDelegate.match(patternNode, matchedNode, matchContext); } @@ -43,7 +43,7 @@ public class SkippingHandler extends MatchingHandler implements DelegatingHandle } @Override - public boolean canMatch(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean canMatch(@NotNull PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { final PsiElement newPatternNode = skipNodeIfNecessary(patternNode); if (newPatternNode != patternNode) { return context.getPattern().getHandler(newPatternNode).canMatch(newPatternNode, matchedNode, context); @@ -52,12 +52,12 @@ public class SkippingHandler extends MatchingHandler implements DelegatingHandle } @Override - public boolean matchSequentially(final NodeIterator patternNodes, final NodeIterator matchNodes, final MatchContext context) { + public boolean matchSequentially(final @NotNull NodeIterator patternNodes, final @NotNull NodeIterator matchNodes, final @NotNull MatchContext context) { return myDelegate.matchSequentially(patternNodes, matchNodes, context); } @Override - protected boolean isMatchSequentiallySucceeded(final NodeIterator matchNodes) { + protected boolean isMatchSequentiallySucceeded(final @NotNull NodeIterator matchNodes) { return myDelegate.isMatchSequentiallySucceeded(matchNodes); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SubstitutionHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SubstitutionHandler.java index e343b83a9c2c..c70a072fa710 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SubstitutionHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SubstitutionHandler.java @@ -27,6 +27,7 @@ import java.util.List; * Matching handler that manages substitutions matching */ public class SubstitutionHandler extends MatchingHandler { + @NotNull private final String name; private final int maxOccurs; private final int minOccurs; @@ -40,25 +41,22 @@ public class SubstitutionHandler extends MatchingHandler { private int matchedOccurs; private int totalMatchedOccurs = -1; private MatchResultImpl myNestedResult; - private boolean myRepeatedVar = false; + private boolean myRepeatedVar; - private static final NodeFilter VARS_DELIM_FILTER = new NodeFilter() { - @Override - public boolean accepts(PsiElement element) { - if (element == null) { - return false; - } - - final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(element); - if (profile == null) { - return false; - } - - return profile.canBeVarDelimiter(element); + private static final NodeFilter VARS_DELIM_FILTER = element -> { + if (element == null) { + return false; } + + final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(element); + if (profile == null) { + return false; + } + + return profile.canBeVarDelimiter(element); }; - public SubstitutionHandler(String name, boolean target, int minOccurs, int maxOccurs, boolean greedy) { + public SubstitutionHandler(@NotNull String name, boolean target, int minOccurs, int maxOccurs, boolean greedy) { if (minOccurs < 0) throw new IllegalArgumentException("minOccurs must be greater or equal to 0"); if (minOccurs > maxOccurs) throw new IllegalArgumentException("maxOccurs must be greater equal to minOccurs"); this.name = name; @@ -117,30 +115,25 @@ public class SubstitutionHandler extends MatchingHandler { return null; } - private boolean validateOneMatch(PsiElement match, int start, int end, MatchResult result, MatchContext matchContext) { + private boolean validateOneMatch(@NotNull PsiElement match, int start, int end, @NotNull MatchResult result, @NotNull MatchContext matchContext) { if (!myRepeatedVar) { return true; } - if (match != null) { - if (start == 0 && end == -1 && result.getStart() == 0 && result.getEnd() == -1) { - return matchContext.getMatcher().match(match, result.getMatch()); - } - else { - final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(match); - assert profile != null; - return profile.getText(match, start, end).equals(result.getMatchImage()); - } + if (start == 0 && end == -1 && result.getStart() == 0 && result.getEnd() == -1) { + return matchContext.getMatcher().match(match, result.getMatch()); } else { - return result.getMatchImage() == null; + final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(match); + assert profile != null; + return profile.getText(match, start, end).equals(result.getMatchImage()); } } - public boolean validate(PsiElement match, MatchContext context) { + public boolean validate(PsiElement match, @NotNull MatchContext context) { return validate(match, 0, -1, context); } - public boolean validate(PsiElement match, int start, int end, MatchContext context) { + public boolean validate(PsiElement match, int start, int end, @NotNull MatchContext context) { if (match == null || predicate != null && !predicate.match(match, start, end, context)) { return false; } @@ -158,7 +151,8 @@ public class SubstitutionHandler extends MatchingHandler { if (minOccurs == 1 && maxOccurs == 1) { // check if they are the same return validateOneMatch(match, start, end, result,context); - } else if (maxOccurs > 1 && totalMatchedOccurs != -1) { + } + if (maxOccurs > 1 && totalMatchedOccurs != -1) { if (result.isMultipleMatch()) { final List children = result.getChildren(); final int size = children.size(); @@ -178,7 +172,7 @@ public class SubstitutionHandler extends MatchingHandler { } @Override - public boolean match(PsiElement node, PsiElement match, MatchContext context) { + public boolean match(PsiElement node, PsiElement match, @NotNull MatchContext context) { if (!super.match(node, match, context)) return false; return matchHandler == null ? @@ -186,11 +180,11 @@ public class SubstitutionHandler extends MatchingHandler { matchHandler.match(node, match, context); } - public void addResult(@NotNull PsiElement match, MatchContext context) { + public void addResult(@NotNull PsiElement match, @NotNull MatchContext context) { addResult(match, 0, -1, context); } - public void addResult(@NotNull PsiElement match, int start, int end, MatchContext context) { + public void addResult(@NotNull PsiElement match, int start, int end, @NotNull MatchContext context) { if (totalMatchedOccurs == -1) { final MatchResultImpl matchResult = context.getResult(); final MatchResultImpl substitution = matchResult.findChild(name); @@ -231,11 +225,11 @@ public class SubstitutionHandler extends MatchingHandler { } } - public boolean handle(PsiElement match, MatchContext context) { + public boolean handle(PsiElement match, @NotNull MatchContext context) { return handle(match, 0, -1, context); } - public boolean handle(PsiElement match, int start, int end, MatchContext context) { + public boolean handle(PsiElement match, int start, int end, @NotNull MatchContext context) { if (!validate(match, start, end, context)) { myNestedResult = null; @@ -247,11 +241,14 @@ public class SubstitutionHandler extends MatchingHandler { return false; } - if (!Configuration.CONTEXT_VAR_NAME.equals(name)) addResult(match, start, end, context); + if (!Configuration.CONTEXT_VAR_NAME.equals(name)) { + addResult(match, start, end, context); + } return true; } + @NotNull private MatchResultImpl createMatch(@NotNull PsiElement match, int start, int end) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(match); assert profile != null; @@ -268,12 +265,12 @@ public class SubstitutionHandler extends MatchingHandler { ) : myNestedResult; if (myNestedResult != null) { - myNestedResult.setName( name ); - myNestedResult.setMatchImage( image ); - myNestedResult.setMatchRef( ref ); - myNestedResult.setStart( start ); - myNestedResult.setEnd( end ); - myNestedResult.setTarget( target ); + myNestedResult.setName(name); + myNestedResult.setMatchImage(image); + myNestedResult.setMatchRef(ref); + myNestedResult.setStart(start); + myNestedResult.setEnd(end); + myNestedResult.setTarget(target); myNestedResult = null; } @@ -281,7 +278,7 @@ public class SubstitutionHandler extends MatchingHandler { } @Override - boolean validate(MatchContext context, int matchedOccurs) { + boolean validate(@NotNull MatchContext context, int matchedOccurs) { if (minOccurs > matchedOccurs) return false; if (maxOccurs < matchedOccurs) return false; return true; @@ -295,7 +292,7 @@ public class SubstitutionHandler extends MatchingHandler { return maxOccurs; } - private void removeLastResults(int numberOfResults, MatchContext context) { + private void removeLastResults(int numberOfResults, @NotNull MatchContext context) { if (numberOfResults == 0) return; final MatchResultImpl substitution = context.getResult().findChild(name); @@ -318,11 +315,11 @@ public class SubstitutionHandler extends MatchingHandler { } @Override - public boolean matchSequentially(NodeIterator patternNodes, NodeIterator matchNodes, MatchContext context) { + public boolean matchSequentially(@NotNull NodeIterator patternNodes, @NotNull NodeIterator matchNodes, @NotNull MatchContext context) { return doMatchSequentially(patternNodes, matchNodes, context); } - protected boolean doMatchSequentiallyBySimpleHandler(NodeIterator patternNodes, NodeIterator matchNodes, MatchContext context) { + protected boolean doMatchSequentiallyBySimpleHandler(NodeIterator patternNodes, NodeIterator matchNodes, @NotNull MatchContext context) { final boolean oldValue = context.shouldRecursivelyMatch(); context.setShouldRecursivelyMatch(false); final boolean result = super.matchSequentially(patternNodes, matchNodes, context); @@ -330,7 +327,9 @@ public class SubstitutionHandler extends MatchingHandler { return result; } - protected boolean doMatchSequentially(NodeIterator patternNodes, NodeIterator matchNodes, MatchContext context) { + protected boolean doMatchSequentially(@NotNull NodeIterator patternNodes, + @NotNull NodeIterator matchNodes, + @NotNull MatchContext context) { final int previousMatchedOccurs = matchedOccurs; final FilteringNodeIterator fNodes = new FilteringNodeIterator(matchNodes, VARS_DELIM_FILTER); @@ -345,9 +344,10 @@ public class SubstitutionHandler extends MatchingHandler { while (fNodes.hasNext() && matchedOccurs < minOccurs) { if (handler.match(currentPatternNode, matchNodes.current(), context)) { ++matchedOccurs; - } else if (handler instanceof TopLevelMatchingHandler && matchedOccurs == 0 || - currentPatternNode instanceof PsiComment || - !(matchNodes.current() instanceof PsiComment)) { + } + else if (handler instanceof TopLevelMatchingHandler && matchedOccurs == 0 || + currentPatternNode instanceof PsiComment || + !(matchNodes.current() instanceof PsiComment)) { break; } fNodes.advance(); @@ -361,15 +361,16 @@ public class SubstitutionHandler extends MatchingHandler { return false; } - if (greedy) { + if (greedy) { // go greedily to maxOccurs while (fNodes.hasNext() && matchedOccurs < maxOccurs) { if (handler.match(currentPatternNode, matchNodes.current(), context)) { ++matchedOccurs; - } else if (handler instanceof TopLevelMatchingHandler && matchedOccurs == 0 || - currentPatternNode instanceof PsiComment || - !(matchNodes.current() instanceof PsiComment)) { + } + else if (handler instanceof TopLevelMatchingHandler && matchedOccurs == 0 || + currentPatternNode instanceof PsiComment || + !(matchNodes.current() instanceof PsiComment)) { break; } fNodes.advance(); @@ -404,7 +405,8 @@ public class SubstitutionHandler extends MatchingHandler { removeLastResults(matchedOccurs, context); } patternNodes.rewind(); - } else { + } + else { // match found if (handler.isMatchSequentiallySucceeded(matchNodes)) { return checkSameOccurrencesConstraint(context); @@ -412,7 +414,8 @@ public class SubstitutionHandler extends MatchingHandler { removeLastResults(matchedOccurs, context); } return false; - } else { + } + else { patternNodes.advance(); if (flag) { @@ -437,7 +440,8 @@ public class SubstitutionHandler extends MatchingHandler { if (handler.match(patternNodes.current(), matchNodes.current(), context)) { matchedOccurs++; - } else { + } + else { patternNodes.rewind(); removeLastResults(matchedOccurs, context); return false; @@ -449,16 +453,18 @@ public class SubstitutionHandler extends MatchingHandler { patternNodes.rewind(); removeLastResults(matchedOccurs, context); return false; - } else { + } + else { return checkSameOccurrencesConstraint(context); } } - } finally { + } + finally { matchedOccurs = previousMatchedOccurs; } } - private boolean checkSameOccurrencesConstraint(MatchContext context) { + private boolean checkSameOccurrencesConstraint(@NotNull MatchContext context) { if (totalMatchedOccurs == -1) { totalMatchedOccurs = matchedOccurs; return true; @@ -474,7 +480,7 @@ public class SubstitutionHandler extends MatchingHandler { this.target = target; } - public void setMatchHandler(MatchingHandler matchHandler) { + public void setMatchHandler(@NotNull MatchingHandler matchHandler) { this.matchHandler = matchHandler; } @@ -482,7 +488,7 @@ public class SubstitutionHandler extends MatchingHandler { return target; } - public String getName() { + public @NotNull String getName() { return name; } @@ -493,7 +499,7 @@ public class SubstitutionHandler extends MatchingHandler { } @Override - public boolean shouldAdvanceThePatternFor(PsiElement patternElement, PsiElement matchedElement) { + public boolean shouldAdvanceThePatternFor(@NotNull PsiElement patternElement, @NotNull PsiElement matchedElement) { if(maxOccurs > 1) return false; return super.shouldAdvanceThePatternFor(patternElement,matchedElement); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SymbolHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SymbolHandler.java index 1532a531193a..287a9bace295 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SymbolHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SymbolHandler.java @@ -3,6 +3,7 @@ package com.intellij.structuralsearch.impl.matcher.handlers; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; /** * Search handler for symbol search @@ -15,7 +16,7 @@ public class SymbolHandler extends MatchingHandler { } @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { return handler.handle(matchedNode, context); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TopLevelMatchingHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TopLevelMatchingHandler.java index 133b43c4f5ac..1d8ffec95eb9 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TopLevelMatchingHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TopLevelMatchingHandler.java @@ -19,7 +19,7 @@ public final class TopLevelMatchingHandler extends MatchingHandler implements De } @Override - public boolean match(final PsiElement patternNode, final PsiElement matchedNode, final MatchContext matchContext) { + public boolean match(final PsiElement patternNode, final PsiElement matchedNode, final @NotNull MatchContext matchContext) { final boolean matched = delegate.match(patternNode, matchedNode, matchContext); if (matched) { @@ -48,17 +48,17 @@ public final class TopLevelMatchingHandler extends MatchingHandler implements De } @Override - public boolean canMatch(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean canMatch(@NotNull PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { return delegate.canMatch(patternNode, matchedNode, context); } @Override - public boolean matchSequentially(final NodeIterator patternNodes, final NodeIterator matchNodes, final MatchContext context) { + public boolean matchSequentially(final @NotNull NodeIterator patternNodes, final @NotNull NodeIterator matchNodes, final @NotNull MatchContext context) { return delegate.matchSequentially(patternNodes, matchNodes, context); } @Override - public boolean isMatchSequentiallySucceeded(final NodeIterator matchNodes) { + public boolean isMatchSequentiallySucceeded(final @NotNull NodeIterator matchNodes) { return true; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TypedSymbolHandler.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TypedSymbolHandler.java index f93d08463031..5f8a181bc6ac 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TypedSymbolHandler.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/TypedSymbolHandler.java @@ -2,13 +2,14 @@ package com.intellij.structuralsearch.impl.matcher.handlers; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; /** * Search handler for typed symbol ('T) */ public class TypedSymbolHandler extends MatchingHandler { @Override - public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) { + public boolean match(PsiElement patternNode, PsiElement matchedNode, @NotNull MatchContext context) { if (!super.match(patternNode,matchedNode,context)) { return false; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/AndPredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/AndPredicate.java index dc25194190e4..ccca38b9e55f 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/AndPredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/AndPredicate.java @@ -17,18 +17,19 @@ package com.intellij.structuralsearch.impl.matcher.predicates; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; public final class AndPredicate extends MatchPredicate { private final MatchPredicate first; private final MatchPredicate second; - public AndPredicate(MatchPredicate first, MatchPredicate second) { + public AndPredicate(@NotNull MatchPredicate first, @NotNull MatchPredicate second) { this.first = first; this.second = second; } @Override - public boolean match(PsiElement matchedNode, int start, int end, MatchContext context) { + public boolean match(@NotNull PsiElement matchedNode, int start, int end, @NotNull MatchContext context) { return first.match(matchedNode, start, end, context) && second.match(matchedNode, start, end, context); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ContainsPredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ContainsPredicate.java index 673511140e0c..a176572b94ef 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ContainsPredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ContainsPredicate.java @@ -2,6 +2,7 @@ package com.intellij.structuralsearch.impl.matcher.predicates; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; /** * @author Maxim.Mossienko @@ -12,7 +13,7 @@ public class ContainsPredicate extends MatchPredicate { } @Override - public boolean match(PsiElement match, int start, int end, MatchContext context) { + public boolean match(@NotNull PsiElement match, int start, int end, @NotNull MatchContext context) { return false; } } \ No newline at end of file diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/MatchPredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/MatchPredicate.java index 299df21f5f66..3ee917b49b3c 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/MatchPredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/MatchPredicate.java @@ -17,6 +17,7 @@ package com.intellij.structuralsearch.impl.matcher.predicates; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; public abstract class MatchPredicate { /** @@ -25,9 +26,9 @@ public abstract class MatchPredicate { * @param context of the matching * @return true if matching was successful, false otherwise */ - public abstract boolean match(PsiElement matchedNode, int start, int end, MatchContext context); + public abstract boolean match(@NotNull PsiElement matchedNode, int start, int end, @NotNull MatchContext context); - public final boolean match(PsiElement matchedNode, MatchContext context) { + public final boolean match(@NotNull PsiElement matchedNode, @NotNull MatchContext context) { return match(matchedNode, 0, -1, context); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/NotPredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/NotPredicate.java index b81655803077..8fd165b45f05 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/NotPredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/NotPredicate.java @@ -17,6 +17,7 @@ package com.intellij.structuralsearch.impl.matcher.predicates; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; /** * Negates predicate @@ -24,12 +25,12 @@ import com.intellij.structuralsearch.impl.matcher.MatchContext; public final class NotPredicate extends MatchPredicate { private final MatchPredicate myPredicate; - public NotPredicate(final MatchPredicate predicate) { + public NotPredicate(@NotNull MatchPredicate predicate) { myPredicate = predicate; } @Override - public boolean match(PsiElement matchedNode, int start, int end, MatchContext context) { + public boolean match(@NotNull PsiElement matchedNode, int start, int end, @NotNull MatchContext context) { return !myPredicate.match(matchedNode, start, end, context); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ReferencePredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ReferencePredicate.java index 734b03eac9d2..c039110472fd 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ReferencePredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ReferencePredicate.java @@ -9,6 +9,7 @@ import com.intellij.psi.PsiReferenceService; import com.intellij.structuralsearch.Matcher; import com.intellij.structuralsearch.StructuralSearchUtil; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Objects; @@ -20,12 +21,12 @@ public final class ReferencePredicate extends MatchPredicate { private final Matcher matcher; - public ReferencePredicate(String constraint, LanguageFileType fileType, Project project) { + public ReferencePredicate(@NotNull String constraint, @NotNull LanguageFileType fileType, @NotNull Project project) { matcher = Matcher.buildMatcher(project, fileType, constraint); } @Override - public boolean match(PsiElement matchedNode, int start, int end, MatchContext context) { + public boolean match(@NotNull PsiElement matchedNode, int start, int end, @NotNull MatchContext context) { matchedNode = StructuralSearchUtil.getParentIfIdentifier(matchedNode); final List references = PsiReferenceService.getService().getReferences(matchedNode, PsiReferenceService.Hints.NO_HINTS); return references.stream().map(PsiReference::resolve).filter(Objects::nonNull).anyMatch(t -> matcher.matchNode(t)); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/RegExpPredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/RegExpPredicate.java index fc4033e57aae..e886bd3e2122 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/RegExpPredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/RegExpPredicate.java @@ -1,7 +1,7 @@ // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.structuralsearch.impl.matcher.predicates; -import com.intellij.psi.*; +import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.MalformedPatternException; import com.intellij.structuralsearch.SSRBundle; import com.intellij.structuralsearch.StructuralSearchUtil; @@ -9,6 +9,7 @@ import com.intellij.structuralsearch.impl.matcher.MatchContext; import com.intellij.structuralsearch.impl.matcher.MatchResultImpl; import com.intellij.structuralsearch.plugin.util.SmartPsiPointer; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -19,6 +20,7 @@ public final class RegExpPredicate extends MatchPredicate { private final String baseHandlerName; private boolean simpleString; private final boolean couldBeOptimized; + @NotNull private final String regexp; private final boolean caseSensitive; private boolean multiline; @@ -30,7 +32,7 @@ public final class RegExpPredicate extends MatchPredicate { String getText(PsiElement element); } - public RegExpPredicate(String regexp, boolean caseSensitive, String _baseHandlerName, boolean _wholeWords, boolean _target) { + public RegExpPredicate(@NotNull String regexp, boolean caseSensitive, String _baseHandlerName, boolean _wholeWords, boolean _target) { couldBeOptimized = !StructuralSearchUtil.containsRegExpMetaChar(regexp); if (!_wholeWords) { simpleString = couldBeOptimized; @@ -54,8 +56,9 @@ public final class RegExpPredicate extends MatchPredicate { realRegexp = ".*?\\b(?:" + realRegexp + ")\\b.*?"; } - pattern = Pattern.compile(realRegexp, (caseSensitive ? 0: Pattern.CASE_INSENSITIVE) | (multiline ? Pattern.DOTALL:0)); - } catch(PatternSyntaxException ex) { + pattern = Pattern.compile(realRegexp, (caseSensitive ? 0 : Pattern.CASE_INSENSITIVE) | (multiline ? Pattern.DOTALL : 0)); + } + catch (PatternSyntaxException ex) { throw new MalformedPatternException(SSRBundle.message("error.incorrect.regexp.constraint", regexp, baseHandlerName)); } } @@ -64,6 +67,7 @@ public final class RegExpPredicate extends MatchPredicate { return couldBeOptimized; } + @NotNull public String getRegExp() { return regexp; } @@ -75,9 +79,7 @@ public final class RegExpPredicate extends MatchPredicate { * @return true if matching was successful and false otherwise */ @Override - public boolean match(PsiElement matchedNode, int start, int end, MatchContext context) { - if (matchedNode==null) return false; - + public boolean match(@NotNull PsiElement matchedNode, int start, int end, @NotNull MatchContext context) { final String text = myNodeTextGenerator != null ? myNodeTextGenerator.getText(matchedNode) : StructuralSearchUtil.getMeaningfulText(matchedNode); @@ -94,11 +96,11 @@ public final class RegExpPredicate extends MatchPredicate { return result; } - public boolean doMatch(String text, MatchContext context, PsiElement matchedElement) { + public boolean doMatch(@NotNull String text, @NotNull MatchContext context, @NotNull PsiElement matchedElement) { return doMatch(text, 0, -1 ,context, matchedElement); } - boolean doMatch(String text, int from, int end, MatchContext context,PsiElement matchedElement) { + private boolean doMatch(@NotNull String text, int from, int end, @NotNull MatchContext context, @NotNull PsiElement matchedElement) { if (from > 0 || end != -1) { text = text.substring(from, (end == -1 || end >= text.length()) ? text.length() : end); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptPredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptPredicate.java index cdedb60290af..c45a9aea752d 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptPredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptPredicate.java @@ -5,6 +5,7 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.MatchOptions; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; import java.util.Set; @@ -19,9 +20,7 @@ public class ScriptPredicate extends MatchPredicate { } @Override - public boolean match(PsiElement match, int start, int end, MatchContext context) { - if (match == null) return false; - + public boolean match(@NotNull PsiElement match, int start, int end, @NotNull MatchContext context) { return Boolean.TRUE.equals(scriptSupport.evaluate(context.hasResult() ? context.getResult() : null, match)); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptSupport.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptSupport.java index 37f4f49d3efd..53711aa7564f 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptSupport.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptSupport.java @@ -91,7 +91,7 @@ public class ScriptSupport { public Object evaluate(MatchResult result, PsiElement context) { try { - final HashMap variableMap = new HashMap<>(); + Map variableMap = new HashMap<>(); myVariableNames.forEach(n -> variableMap.put(n, null)); variableMap.put(ScriptLog.SCRIPT_LOG_VAR_NAME, myScriptLog); if (result != null) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/WithinPredicate.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/WithinPredicate.java index c47ebf74c285..05fbc6c4bc09 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/WithinPredicate.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/WithinPredicate.java @@ -8,6 +8,7 @@ import com.intellij.psi.util.PsiTreeUtil; import com.intellij.structuralsearch.MatchResult; import com.intellij.structuralsearch.Matcher; import com.intellij.structuralsearch.impl.matcher.MatchContext; +import org.jetbrains.annotations.NotNull; import java.util.List; @@ -18,12 +19,12 @@ public class WithinPredicate extends MatchPredicate { private final Matcher matcher; - public WithinPredicate(String within, LanguageFileType fileType, Project project) { + public WithinPredicate(@NotNull String within, @NotNull LanguageFileType fileType, @NotNull Project project) { matcher = Matcher.buildMatcher(project, fileType, within); } @Override - public boolean match(PsiElement matchedNode, int start, int end, MatchContext context) { + public boolean match(@NotNull PsiElement matchedNode, int start, int end, @NotNull MatchContext context) { final List results = matcher.matchByDownUp(matchedNode); for (MatchResult result : results) { if (PsiTreeUtil.isAncestor(result.getMatch(), matchedNode, false)) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/InspectionProfileUtil.java b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/InspectionProfileUtil.java index 98992b3d3a30..ac55f847328b 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/InspectionProfileUtil.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/InspectionProfileUtil.java @@ -8,6 +8,7 @@ import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.openapi.project.Project; import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel; import com.intellij.util.ui.UIUtil; +import org.jetbrains.annotations.NotNull; import java.awt.*; @@ -18,19 +19,20 @@ public final class InspectionProfileUtil { private InspectionProfileUtil() {} - public static SSBasedInspection getStructuralSearchInspection(InspectionProfile profile) { + @NotNull + public static SSBasedInspection getStructuralSearchInspection(@NotNull InspectionProfile profile) { final InspectionToolWrapper wrapper = profile.getInspectionTool(SSBasedInspection.SHORT_NAME, (Project)null); assert wrapper != null; return (SSBasedInspection)wrapper.getTool(); } - public static InspectionProfileModifiableModel getInspectionProfile(Component c) { + public static InspectionProfileModifiableModel getInspectionProfile(@NotNull Component c) { final SingleInspectionProfilePanel panel = UIUtil.uiParents(c, true).filter(SingleInspectionProfilePanel.class).first(); if (panel == null) return null; return panel.getProfile(); } - public static void fireProfileChanged(InspectionProfileImpl profile) { + public static void fireProfileChanged(@NotNull InspectionProfileImpl profile) { profile.getProfileManager().fireProfileChanged(profile); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspection.java b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspection.java index af3cd3d67aae..140b8e1d2df7 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspection.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspection.java @@ -39,12 +39,12 @@ import java.util.*; import java.util.stream.Collectors; public class SSBasedInspection extends LocalInspectionTool implements DynamicGroupTool { - static final Object LOCK = new Object(); // hack to avoid race conditions in SSR + private static final Object LOCK = ObjectUtils.sentinel("SSRLock"); // hack to avoid race conditions in SSR @NonNls public static final String SHORT_NAME = "SSBasedInspection"; private final List myConfigurations = ContainerUtil.createLockFreeCopyOnWriteList(); - final Set myProblemsReported = new HashSet<>(1); - private InspectionProfileImpl mySessionProfile = null; + private final Set myProblemsReported = new HashSet<>(1); + private InspectionProfileImpl mySessionProfile; @Override public void writeSettings(@NotNull Element node) throws WriteExternalException { @@ -154,7 +154,7 @@ public class SSBasedInspection extends LocalInspectionTool implements DynamicGro }; } - public static void register(Configuration configuration) { + public static void register(@NotNull Configuration configuration) { if (configuration.getOrder() != 0) { // not a main configuration containing meta data return; @@ -175,7 +175,7 @@ public class SSBasedInspection extends LocalInspectionTool implements DynamicGro } } - private static boolean isMetaDataChanged(Configuration configuration, HighlightDisplayKey key) { + private static boolean isMetaDataChanged(@NotNull Configuration configuration, @NotNull HighlightDisplayKey key) { if (StringUtil.isEmpty(configuration.getSuppressId())) { if (!SHORT_NAME.equals(key.getID())) return true; } @@ -184,14 +184,14 @@ public class SSBasedInspection extends LocalInspectionTool implements DynamicGro } @Override - public List getChildren() { + public @NotNull List getChildren() { return getConfigurations().stream() .filter(configuration -> configuration.getOrder() == 0) .map(configuration -> new StructuralSearchInspectionToolWrapper(getConfigurationsWithUuid(configuration.getUuid()))) .collect(Collectors.toList()); } - static LocalQuickFix createQuickFix(final Project project, final MatchResult matchResult, final Configuration configuration) { + private static LocalQuickFix createQuickFix(@NotNull Project project, @NotNull MatchResult matchResult, @NotNull Configuration configuration) { if (!(configuration instanceof ReplaceConfiguration)) return null; final ReplaceConfiguration replaceConfiguration = (ReplaceConfiguration)configuration; final Replacer replacer = new Replacer(project, replaceConfiguration.getReplaceOptions()); @@ -221,7 +221,8 @@ public class SSBasedInspection extends LocalInspectionTool implements DynamicGro }; } - private Configuration getMainConfiguration(Configuration configuration) { + @NotNull + private Configuration getMainConfiguration(@NotNull Configuration configuration) { if (configuration.getOrder() == 0) { return configuration; } @@ -229,10 +230,12 @@ public class SSBasedInspection extends LocalInspectionTool implements DynamicGro return myConfigurations.stream().filter(c -> c.getOrder() == 0 && uuid.equals(c.getUuid())).findFirst().orElse(configuration); } + @NotNull public List getConfigurations() { return Collections.unmodifiableList(myConfigurations); } + @NotNull public List getConfigurationsWithUuid(@NotNull UUID uuid) { final List configurations = ContainerUtil.filter(myConfigurations, c -> uuid.equals(c.getUuid())); configurations.sort(Comparator.comparingInt(Configuration::getOrder)); @@ -267,13 +270,13 @@ public class SSBasedInspection extends LocalInspectionTool implements DynamicGro private final Configuration myConfiguration; private PairProcessor myProcessor; - InspectionResultSink(PairProcessor processor, Configuration configuration) { + InspectionResultSink(@NotNull PairProcessor processor, @NotNull Configuration configuration) { myProcessor = processor; myConfiguration = configuration; } @Override - public void newMatch(MatchResult result) { + public void newMatch(@NotNull MatchResult result) { myProcessor.process(result, myConfiguration); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspectionCompiledPatternsCache.java b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspectionCompiledPatternsCache.java index 68dc68022013..ef4eea1c3410 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspectionCompiledPatternsCache.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/SSBasedInspectionCompiledPatternsCache.java @@ -25,7 +25,6 @@ import java.util.Map; * @author Eugene.Kudelevsky */ final class SSBasedInspectionCompiledPatternsCache { - private static final Logger LOG = Logger.getInstance(SSBasedInspectionCompiledPatternsCache.class); private static final Key> COMPILED_OPTIONS_KEY = Key.create("SSR_INSPECTION_COMPILED_OPTIONS_KEY"); private final Project myProject; @@ -43,13 +42,15 @@ final class SSBasedInspectionCompiledPatternsCache { } @NotNull - Map getCompiledOptions(@NotNull List configurations) { + Map getCompiledOptions(@NotNull List configurations) { final Map cache = getCompiledOptions(configurations, myProject.getUserData(COMPILED_OPTIONS_KEY)); myProject.putUserData(COMPILED_OPTIONS_KEY, cache); return cache; } - Map getCompiledOptions(@NotNull List configurations, @Nullable Map cache) { + @NotNull + private Map getCompiledOptions(@NotNull List configurations, + @Nullable Map cache) { if (areConfigurationsInCache(configurations, cache)) { return cache; } @@ -79,7 +80,7 @@ final class SSBasedInspectionCompiledPatternsCache { } @Contract("_, null -> false") - private static boolean areConfigurationsInCache(List configurations, @Nullable Map cache) { + private static boolean areConfigurationsInCache(@NotNull List configurations, @Nullable Map cache) { return cache != null && configurations.size() == cache.size() && configurations.stream().allMatch(key -> cache.containsKey(key)); } } \ No newline at end of file diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchFakeInspection.java b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchFakeInspection.java index b9bd6bf53360..62669ddb8930 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchFakeInspection.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchFakeInspection.java @@ -115,10 +115,10 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { } @Override - public @Nullable JComponent createOptionsPanel() { + public @NotNull JComponent createOptionsPanel() { final MyListModel model = new MyListModel(); final JButton button = new JButton(SSRBundle.message("edit.metadata.button")); - button.addActionListener(e -> performEditMetaData(button)); + button.addActionListener(__ -> performEditMetaData(button)); final JList list = new JBList<>(model); list.setCellRenderer(new ConfigurationCellRenderer()); @@ -148,7 +148,7 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { return panel; } - private void performEditMetaData(Component context) { + private void performEditMetaData(@NotNull Component context) { final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(context)); final InspectionProfileModifiableModel profile = InspectionProfileUtil.getInspectionProfile(context); if (profile == null) { @@ -170,7 +170,7 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { InspectionProfileUtil.fireProfileChanged(profile); } - private void performMove(JList list, boolean up) { + private void performMove(@NotNull JList list, boolean up) { final MyListModel model = (MyListModel)list.getModel(); final List values = list.getSelectedValuesList(); final Comparator c = Comparator.comparingInt(Configuration::getOrder); @@ -195,7 +195,8 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { profile.setModified(true); } - private static Configuration moveMetaData(Configuration source, Configuration target) { + @NotNull + private static Configuration moveMetaData(@NotNull Configuration source, @NotNull Configuration target) { if (source == target) return source; target.setDescription(source.getDescription()); target.setSuppressId(source.getSuppressId()); @@ -206,7 +207,7 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { return target; } - private void performAdd(JList list, AnActionButton b) { + private void performAdd(@NotNull JList list, @NotNull AnActionButton b) { final AnAction[] children = new AnAction[]{new AddTemplateAction(list, false), new AddTemplateAction(list, true)}; final RelativePoint point = b.getPreferredPopupPoint(); if (point == null) return; @@ -215,7 +216,7 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true).show(point); } - private void performRemove(JList list) { + private void performRemove(@NotNull JList list) { boolean metaData = false; for (Configuration configuration : list.getSelectedValuesList()) { if (configuration.getOrder() == 0) { @@ -250,7 +251,7 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { profile.setModified(true); } - private void performEdit(JList list) { + private void performEdit(@NotNull JList list) { final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(list)); if (project == null) return; final int index = list.getSelectedIndex(); @@ -278,11 +279,11 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { } private final class AddTemplateAction extends DumbAwareAction { - + @NotNull private final JList myList; private final boolean myReplace; - private AddTemplateAction(JList list, boolean replace) { + private AddTemplateAction(@NotNull JList list, boolean replace) { super(replace ? SSRBundle.message("SSRInspection.add.replace.template.button") : SSRBundle.message("SSRInspection.add.search.template.button")); @@ -326,7 +327,6 @@ public class StructuralSearchFakeInspection extends LocalInspectionTool { } private class MyListModel extends AbstractListModel { - @Override public int getSize() { return myConfigurations.size(); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchProfileActionProvider.java b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchProfileActionProvider.java index 5659aa8a8ea2..34314b5c16cf 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchProfileActionProvider.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/StructuralSearchProfileActionProvider.java @@ -48,7 +48,7 @@ public class StructuralSearchProfileActionProvider extends InspectionProfileActi @NotNull @Override - public List getActions(SingleInspectionProfilePanel panel) { + public List getActions(@NotNull SingleInspectionProfilePanel panel) { final InspectionProfileModifiableModel profile = panel.getProfile(); if (profile.getToolsOrNull(SSBasedInspection.SHORT_NAME, null) != null && !profile.isToolEnabled(HighlightDisplayKey.find(SSBasedInspection.SHORT_NAME))) { @@ -76,10 +76,9 @@ public class StructuralSearchProfileActionProvider extends InspectionProfileActi } private static final class RemoveInspectionAction extends DumbAwareAction { - private final SingleInspectionProfilePanel myPanel; - private RemoveInspectionAction(SingleInspectionProfilePanel panel) { + private RemoveInspectionAction(@NotNull SingleInspectionProfilePanel panel) { super(SSRBundle.message("remove.inspection.button"), null, AllIcons.General.Remove); myPanel = panel; registerCustomShortcutSet(CommonShortcuts.getDelete(), myPanel); @@ -104,11 +103,10 @@ public class StructuralSearchProfileActionProvider extends InspectionProfileActi } private static final class AddInspectionAction extends DumbAwareAction { - private final SingleInspectionProfilePanel myPanel; private final boolean myReplace; - private AddInspectionAction(SingleInspectionProfilePanel panel, boolean replace) { + private AddInspectionAction(@NotNull SingleInspectionProfilePanel panel, boolean replace) { super(replace ? SSRBundle.message("SSRInspection.add.replace.template.button") : SSRBundle.message("SSRInspection.add.search.template.button")); @@ -138,9 +136,9 @@ public class StructuralSearchProfileActionProvider extends InspectionProfileActi createNewInspection(configuration, project, InspectionProfileManager.getInstance(project).getCurrentProfile()); } - static boolean createNewInspection(@NotNull Configuration configuration, - @NotNull Project project, - @NotNull InspectionProfileImpl profile) { + private static boolean createNewInspection(@NotNull Configuration configuration, + @NotNull Project project, + @NotNull InspectionProfileImpl profile) { final SSBasedInspection inspection = InspectionProfileUtil.getStructuralSearchInspection(profile); if (!ApplicationManager.getApplication().isUnitTestMode()) { configuration.setOrder(0); // reset @@ -159,7 +157,9 @@ public class StructuralSearchProfileActionProvider extends InspectionProfileActi return true; } - private static void addInspectionToProfile(@NotNull Project project, InspectionProfileImpl profile, Configuration configuration) { + private static void addInspectionToProfile(@NotNull Project project, + @NotNull InspectionProfileImpl profile, + @NotNull Configuration configuration) { final String shortName = configuration.getUuid().toString(); final InspectionToolWrapper toolWrapper = profile.getInspectionTool(shortName, project); if (toolWrapper != null) { @@ -187,7 +187,7 @@ public class StructuralSearchProfileActionProvider extends InspectionProfileActi private final EditorTextField myDescriptionTextArea; private final JTextField mySuppressIdTextField; - InspectionDataDialog(Project project, SSBasedInspection inspection, Configuration configuration, boolean newInspection) { + InspectionDataDialog(Project project, @NotNull SSBasedInspection inspection, @NotNull Configuration configuration, boolean newInspection) { super(null); myInspection = inspection; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/StructuralSearchAction.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/StructuralSearchAction.java index 8c526c72f7f9..daa7ee3b3257 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/StructuralSearchAction.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/StructuralSearchAction.java @@ -22,7 +22,7 @@ public class StructuralSearchAction extends DumbAwareAction { triggerAction(null, new SearchContext(event.getDataContext()), false); } - public static void triggerAction(Configuration config, SearchContext searchContext, boolean replace) { + public static void triggerAction(Configuration config, @NotNull SearchContext searchContext, boolean replace) { final Project project = searchContext.getProject(); PsiDocumentManager.getInstance(project).commitAllDocuments(); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplaceOptions.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplaceOptions.java index 35d714876a41..95a8d9a7d651 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplaceOptions.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplaceOptions.java @@ -22,6 +22,7 @@ public class ReplaceOptions implements JDOMExternalizable { private boolean toShortenFQN; private boolean myToReformatAccordingToStyle; private boolean myToUseStaticImport; + @NotNull private final MatchOptions matchOptions; @NonNls private static final String REFORMAT_ATTR_NAME = "reformatAccordingToStyle"; @@ -35,14 +36,14 @@ public class ReplaceOptions implements JDOMExternalizable { this(new MatchOptions()); } - public ReplaceOptions(MatchOptions matchOptions) { + public ReplaceOptions(@NotNull MatchOptions matchOptions) { variableDefs = new LinkedHashMap<>(); this.matchOptions = matchOptions; replacement = ""; myToUseStaticImport = false; } - ReplaceOptions(ReplaceOptions options) { + private ReplaceOptions(@NotNull ReplaceOptions options) { variableDefs = new LinkedHashMap<>(options.variableDefs.size()); options.variableDefs.forEach((key, value) -> variableDefs.put(key, value.copy())); // deep copy replacement = options.replacement; @@ -52,10 +53,12 @@ public class ReplaceOptions implements JDOMExternalizable { matchOptions = options.matchOptions.copy(); // deep copy } + @NotNull public ReplaceOptions copy() { return new ReplaceOptions(this); } + @NotNull public String getReplacement() { return replacement; } @@ -76,7 +79,7 @@ public class ReplaceOptions implements JDOMExternalizable { return myToReformatAccordingToStyle; } - public MatchOptions getMatchOptions() { + public @NotNull MatchOptions getMatchOptions() { return matchOptions; } @@ -92,6 +95,7 @@ public class ReplaceOptions implements JDOMExternalizable { myToUseStaticImport = useStaticImport; } + @NotNull private Set getUsedVariableNames() { return TemplateImplUtil.parseVariableNames(replacement); } @@ -179,20 +183,22 @@ public class ReplaceOptions implements JDOMExternalizable { return result; } - public ReplacementVariableDefinition getVariableDefinition(String name) { + public ReplacementVariableDefinition getVariableDefinition(@NotNull String name) { return variableDefs != null ? variableDefs.get(name): null; } - public void addVariableDefinition(ReplacementVariableDefinition definition) { + public void addVariableDefinition(@NotNull ReplacementVariableDefinition definition) { variableDefs.put(definition.getName(), definition); } - public ReplacementVariableDefinition addNewVariableDefinition(String name) { + @NotNull + public ReplacementVariableDefinition addNewVariableDefinition(@NotNull String name) { final ReplacementVariableDefinition definition = new ReplacementVariableDefinition(name); variableDefs.put(name, definition); return definition; } + @NotNull public Collection getVariableDefinitions() { return variableDefs.values(); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplacementInfo.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplacementInfo.java index c318b2f17851..26775504607d 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplacementInfo.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ReplacementInfo.java @@ -3,6 +3,7 @@ package com.intellij.structuralsearch.plugin.replace; import com.intellij.psi.PsiElement; import com.intellij.structuralsearch.MatchResult; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface ReplacementInfo { @@ -13,11 +14,12 @@ public interface ReplacementInfo { int getMatchesCount(); - MatchResult getNamedMatchResult(String name); + MatchResult getNamedMatchResult(@NotNull String name); + @NotNull MatchResult getMatchResult(); - String getVariableName(PsiElement element); + String getVariableName(@NotNull PsiElement element); - String getSearchPatternName(String sourceName); + String getSearchPatternName(@NotNull String sourceName); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ParameterInfo.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ParameterInfo.java index 0ae9744f57bb..caff7544af29 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ParameterInfo.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ParameterInfo.java @@ -3,8 +3,10 @@ package com.intellij.structuralsearch.plugin.replace.impl; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; public final class ParameterInfo extends UserDataHolderBase { + @NotNull private final String name; private final int startIndex; private final boolean replacementVariable; @@ -16,13 +18,13 @@ public final class ParameterInfo extends UserDataHolderBase { private boolean hasCommaAfter; private PsiElement myElement; - public ParameterInfo(String name, int startIndex, boolean replacementVariable) { + public ParameterInfo(@NotNull String name, int startIndex, boolean replacementVariable) { this.name = name; this.startIndex = startIndex; this.replacementVariable = replacementVariable; } - public String getName() { + public @NotNull String getName() { return name; } @@ -86,7 +88,7 @@ public final class ParameterInfo extends UserDataHolderBase { return myElement; } - public void setElement(PsiElement element) { + public void setElement(@NotNull PsiElement element) { myElement = element; } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementBuilder.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementBuilder.java index 99486f471703..7c78e840854c 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementBuilder.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementBuilder.java @@ -27,13 +27,14 @@ import java.util.*; * @author maxim */ public final class ReplacementBuilder { + @NotNull private final String replacement; private final MultiMap parameterizations = MultiMap.createLinked(); private final Map replacementVarsMap = new HashMap<>(); private final ReplaceOptions options; private final Project myProject; - ReplacementBuilder(Project project, ReplaceOptions options) { + ReplacementBuilder(@NotNull Project project, @NotNull ReplaceOptions options) { myProject = project; this.options = options; @@ -121,7 +122,8 @@ public final class ReplacementBuilder { } } - String process(MatchResult match, ReplacementInfo replacementInfo, LanguageFileType type) { + @NotNull + String process(@NotNull MatchResult match, @NotNull ReplacementInfo replacementInfo, @NotNull LanguageFileType type) { if (parameterizations.isEmpty()) { return replacement; } @@ -156,7 +158,7 @@ public final class ReplacementBuilder { } @Nullable - private Object generateReplacement(ParameterInfo info, MatchResult match) { + private Object generateReplacement(@NotNull ParameterInfo info, @NotNull MatchResult match) { ScriptSupport scriptSupport = replacementVarsMap.get(info.getName()); if (scriptSupport == null) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementInfoImpl.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementInfoImpl.java index b1c7cf9220ad..989976014ea6 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementInfoImpl.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementInfoImpl.java @@ -10,6 +10,7 @@ import com.intellij.structuralsearch.MatchResult; import com.intellij.structuralsearch.StructuralSearchUtil; import com.intellij.structuralsearch.plugin.replace.ReplacementInfo; import com.intellij.util.SmartList; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; @@ -18,6 +19,7 @@ import java.util.List; import java.util.Map; class ReplacementInfoImpl implements ReplacementInfo { + @NotNull private final MatchResult matchResult; private final List> matchesPtrList = new SmartList<>(); private final Map variableMap = new HashMap<>(); @@ -26,12 +28,12 @@ class ReplacementInfoImpl implements ReplacementInfo { private String replacement; - ReplacementInfoImpl(MatchResult matchResult, Project project) { + ReplacementInfoImpl(@NotNull MatchResult matchResult, @NotNull Project project) { this.matchResult = matchResult; init(project); } - private void init(Project project) { + private void init(@NotNull Project project) { fillPointerList(project); fillVariableMap(matchResult.getRoot()); for(Map.Entry entry : variableMap.entrySet()) { @@ -44,7 +46,7 @@ class ReplacementInfoImpl implements ReplacementInfo { return replacement; } - public void setReplacement(String replacement) { + public void setReplacement(@NotNull String replacement) { this.replacement = replacement; } @@ -60,26 +62,26 @@ class ReplacementInfoImpl implements ReplacementInfo { } @Override - public MatchResult getNamedMatchResult(String name) { + public MatchResult getNamedMatchResult(@NotNull String name) { return variableMap.get(name); } @Override - public MatchResult getMatchResult() { + public @NotNull MatchResult getMatchResult() { return matchResult; } @Override - public String getVariableName(PsiElement element) { + public String getVariableName(@NotNull PsiElement element) { return elementToVariableNameMap.get(element); } @Override - public String getSearchPatternName(String sourceName) { + public String getSearchPatternName(@NotNull String sourceName) { return sourceNameToSearchPatternNameMap.get(sourceName); } - private void fillPointerList(Project project) { + private void fillPointerList(@NotNull Project project) { final SmartPointerManager manager = SmartPointerManager.getInstance(project); if (MatchResult.MULTI_LINE_MATCH.equals(matchResult.getName())) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java index 415106c0e5cb..29df2b5d3afb 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java @@ -26,6 +26,7 @@ import com.intellij.structuralsearch.plugin.replace.ReplacementInfo; import com.intellij.structuralsearch.plugin.util.CollectingMatchResultSink; import com.intellij.util.IncorrectOperationException; import com.intellij.util.SmartList; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -35,12 +36,13 @@ import java.util.List; */ public class Replacer { private final Project project; + @NotNull private final ReplaceOptions options; private final StructuralReplaceHandler replaceHandler; private final ReplacementBuilder replacementBuilder; - private PsiElement lastAffectedElement = null; + private PsiElement lastAffectedElement; - public Replacer(Project project, ReplaceOptions options) { + public Replacer(@NotNull Project project, @NotNull ReplaceOptions options) { this.project = project; this.options = options; final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(options.getMatchOptions().getFileType()); @@ -68,11 +70,11 @@ public class Replacer { public static String testReplace(String in, String what, String by, ReplaceOptions options, Project project, boolean sourceIsFile) { final LanguageFileType type = options.getMatchOptions().getFileType(); - return testReplace(in, what, by, options, project, sourceIsFile, false, type, null); + return testReplace(in, what, by, options, project, sourceIsFile, false, type, type.getLanguage()); } public static String testReplace(String in, String what, String by, ReplaceOptions replaceOptions, Project project, boolean sourceIsFile, - boolean createPhysicalFile, LanguageFileType sourceFileType, Language sourceDialect) { + boolean createPhysicalFile, @NotNull LanguageFileType sourceFileType, @NotNull Language sourceDialect) { replaceOptions.setReplacement(by); final MatchOptions matchOptions = replaceOptions.getMatchOptions(); @@ -84,12 +86,15 @@ public class Replacer { final Replacer replacer = new Replacer(project, replaceOptions); final Matcher matcher = new Matcher(project, matchOptions); try { - final PsiElement firstElement, lastElement, parent; + final PsiElement firstElement; + final PsiElement lastElement; + final PsiElement parent; if (matchOptions.getScope() == null) { final PsiElement[] elements = MatcherImplUtil.createTreeFromText( in, new PatternContextInfo(sourceIsFile ? PatternTreeContext.File : PatternTreeContext.Block), - sourceFileType, sourceDialect, + sourceFileType, + sourceDialect, project, createPhysicalFile ); @@ -188,13 +193,13 @@ public class Replacer { ); } - public void replace(ReplacementInfo info) { + public void replace(@NotNull ReplacementInfo info) { replaceHandler.prepare(info); reformatAndPostProcess(doReplace(info)); } @Nullable - private PsiElement doReplace(ReplacementInfo info) { + private PsiElement doReplace(@NotNull ReplacementInfo info) { final PsiElement element = info.getMatch(0); if (element==null || !element.isWritable() || !element.isValid()) return null; @@ -258,7 +263,7 @@ public class Replacer { } } - public static void checkReplacementPattern(Project project, ReplaceOptions options) { + public static void checkReplacementPattern(@NotNull Project project, @NotNull ReplaceOptions options) { try { final String search = options.getMatchOptions().getSearchPattern(); final String replacement = options.getReplacement(); @@ -309,7 +314,8 @@ public class Replacer { } } - public ReplacementInfo buildReplacement(MatchResult result) { + @NotNull + public ReplacementInfo buildReplacement(@NotNull MatchResult result) { final ReplacementInfoImpl replacementInfo = new ReplacementInfoImpl(result, project); replacementInfo.setReplacement(replacementBuilder.process(result, replacementInfo, options.getMatchOptions().getFileType())); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacerUtil.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacerUtil.java index 50a69b7cbe9a..f5f6fce9751c 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacerUtil.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacerUtil.java @@ -6,6 +6,7 @@ import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.structuralsearch.StructuralSearchProfile; +import org.jetbrains.annotations.NotNull; /** * @author Eugene.Kudelevsky @@ -14,10 +15,10 @@ public final class ReplacerUtil { private ReplacerUtil() { } - public static PsiElement copySpacesAndCommentsBefore(PsiElement elementToReplace, - PsiElement[] patternElements, - String replacementToMake, - PsiElement elementParent) { + public static PsiElement copySpacesAndCommentsBefore(@NotNull PsiElement elementToReplace, + PsiElement @NotNull [] patternElements, + @NotNull String replacementToMake, + @NotNull PsiElement elementParent) { int i = 0; while (true) { // if it goes out of bounds then deep error happens if (!(patternElements[i] instanceof PsiComment || patternElements[i] instanceof PsiWhiteSpace)) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java index 6f90f5b336fa..7efaaa805a4a 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java @@ -7,17 +7,18 @@ import com.intellij.structuralsearch.plugin.ui.SearchCommand; import com.intellij.structuralsearch.plugin.ui.SearchContext; import com.intellij.structuralsearch.plugin.ui.UsageViewContext; import com.intellij.usages.Usage; +import org.jetbrains.annotations.NotNull; public class ReplaceCommand extends SearchCommand { private ReplaceUsageViewContext myReplaceUsageViewContext; - public ReplaceCommand(Configuration configuration, SearchContext searchContext) { + public ReplaceCommand(@NotNull Configuration configuration, @NotNull SearchContext searchContext) { super(configuration, searchContext); } @Override - protected UsageViewContext createUsageViewContext() { + protected @NotNull UsageViewContext createUsageViewContext() { final Runnable searchStarter = () -> new ReplaceCommand(myConfiguration, mySearchContext).startSearching(); myReplaceUsageViewContext = new ReplaceUsageViewContext(mySearchContext, myConfiguration, searchStarter); return myReplaceUsageViewContext; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceConfiguration.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceConfiguration.java index f12b7c6aab59..c81a38892407 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceConfiguration.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceConfiguration.java @@ -7,12 +7,13 @@ import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import com.intellij.structuralsearch.plugin.ui.Configuration; import com.intellij.util.ObjectUtils; import org.jdom.Element; +import org.jetbrains.annotations.NotNull; /** * @author Maxim.Mossienko */ public class ReplaceConfiguration extends Configuration { - + @NotNull private final ReplaceOptions myReplaceOptions; public static final String REPLACEMENT_VARIABLE_SUFFIX = "$replacement"; @@ -20,35 +21,35 @@ public class ReplaceConfiguration extends Configuration { myReplaceOptions = new ReplaceOptions(); } - public ReplaceConfiguration(Configuration configuration) { + public ReplaceConfiguration(@NotNull Configuration configuration) { super(configuration); myReplaceOptions = configuration instanceof ReplaceConfiguration ? ((ReplaceConfiguration)configuration).myReplaceOptions.copy() : new ReplaceOptions(configuration.getMatchOptions().copy()); } - public ReplaceConfiguration(String name, String category) { + public ReplaceConfiguration(@NotNull String name, @NotNull String category) { super(name, category); myReplaceOptions = new ReplaceOptions(); } @Override - public ReplaceConfiguration copy() { + public @NotNull ReplaceConfiguration copy() { return new ReplaceConfiguration(this); } @Override - public ReplaceOptions getReplaceOptions() { + public @NotNull ReplaceOptions getReplaceOptions() { return myReplaceOptions; } @Override - public MatchOptions getMatchOptions() { + public @NotNull MatchOptions getMatchOptions() { return myReplaceOptions.getMatchOptions(); } @Override - public NamedScriptableDefinition findVariable(String name) { + public NamedScriptableDefinition findVariable(@NotNull String name) { return ObjectUtils.chooseNotNull(myReplaceOptions.getVariableDefinition(name), getMatchOptions().getVariableConstraint(name)); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java index 98c6e051635a..a14c063887a6 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java @@ -25,18 +25,18 @@ import java.util.*; import java.util.stream.Collectors; class ReplaceUsageViewContext extends UsageViewContext { - private final HashMap usage2ReplacementInfo = new HashMap<>(); + private final Map usage2ReplacementInfo = new HashMap<>(); private final Replacer replacer = new Replacer(mySearchContext.getProject(), myConfiguration.getReplaceOptions()); - ReplaceUsageViewContext(SearchContext context, Configuration configuration, Runnable searchStarter) { + ReplaceUsageViewContext(@NotNull SearchContext context, @NotNull Configuration configuration, @NotNull Runnable searchStarter) { super(configuration, context, searchStarter); } - public void addReplaceUsage(Usage usage, MatchResult result) { + public void addReplaceUsage(@NotNull Usage usage, @NotNull MatchResult result) { usage2ReplacementInfo.put(usage, replacer.buildReplacement(result)); } - private static boolean isValid(UsageInfo2UsageAdapter info) { + private static boolean isValid(@NotNull UsageInfo2UsageAdapter info) { final PsiElement element = info.getUsageInfo().getElement(); return element != null && element.isValid(); } @@ -69,7 +69,7 @@ class ReplaceUsageViewContext extends UsageViewContext { myUsageView.addButtonToLowerPane(previewReplacement, SSRBundle.message("preview.replacement.button")); } - private void replace(@NotNull Collection usages) { + private void replace(@NotNull Collection usages) { final Set excluded = myUsageView.getExcludedUsages(); usages = usages.stream().filter(u -> !excluded.contains(u)).filter(u -> isValid((UsageInfo2UsageAdapter)u)).collect(Collectors.toList()); @@ -88,7 +88,7 @@ class ReplaceUsageViewContext extends UsageViewContext { } } - private void removeUsagesAndSelectNext(Collection usages, Collection excluded) { + private void removeUsagesAndSelectNext(@NotNull Collection usages, @NotNull Collection excluded) { final List sortedUsages = myUsageView.getSortedUsages(); if (sortedUsages.size() == usages.size()) { myUsageView.close(); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/Configuration.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/Configuration.java index b1fd92e6667d..e802a7af3e5a 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/Configuration.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/Configuration.java @@ -40,7 +40,7 @@ public abstract class Configuration implements JDOMExternalizable, Comparable { private static final int MAX_RECENT_SIZE = 30; - @NonNls static final String SEARCH_TAG_NAME = "searchConfiguration"; - @NonNls static final String REPLACE_TAG_NAME = "replaceConfiguration"; + @NonNls private static final String SEARCH_TAG_NAME = "searchConfiguration"; + @NonNls private static final String REPLACE_TAG_NAME = "replaceConfiguration"; @NonNls private static final String SAVE_HISTORY_ATTR_NAME = "history"; private final List configurations = new SmartList<>(); @@ -65,9 +65,8 @@ public class ConfigurationManager implements PersistentStateComponent { } /** * Stores configurations at the application level. Before the configurations where stored in the workspace file. - * @param configurations */ - private void migrate(List configurations) { + private void migrate(@NotNull List configurations) { if (configurations.isEmpty()) { return; } @@ -132,7 +131,8 @@ public class ConfigurationManager implements PersistentStateComponent { } } - static Element saveConfiguration(@NotNull Element element, @NotNull Configuration config) { + @NotNull + private static Element saveConfiguration(@NotNull Element element, @NotNull Configuration config) { final Element infoElement = new Element(config instanceof SearchConfiguration ? SEARCH_TAG_NAME : REPLACE_TAG_NAME); element.addContent(infoElement); config.writeExternal(infoElement); @@ -159,7 +159,7 @@ public class ConfigurationManager implements PersistentStateComponent { } } - static Configuration readConfiguration(@NotNull Element element) { + private static Configuration readConfiguration(@NotNull Element element) { final String name = element.getName(); final Configuration config; if (name.equals(SEARCH_TAG_NAME)) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java index 2d1972282674..8faf12df5200 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java @@ -19,16 +19,18 @@ import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; public class SearchCommand { + @NotNull protected final SearchContext mySearchContext; + @NotNull protected final Configuration myConfiguration; - private MatchingProcess process; private FindUsagesProcessPresentation myProcessPresentation; - public SearchCommand(Configuration configuration, SearchContext searchContext) { + public SearchCommand(@NotNull Configuration configuration, @NotNull SearchContext searchContext) { myConfiguration = configuration; mySearchContext = searchContext; } + @NotNull protected UsageViewContext createUsageViewContext() { final Runnable searchStarter = () -> new SearchCommand(myConfiguration, mySearchContext).startSearching(); return new UsageViewContext(myConfiguration, mySearchContext, searchStarter); @@ -49,12 +51,7 @@ public class SearchCommand { ((FindManagerImpl)FindManager.getInstance(mySearchContext.getProject())).getFindUsagesManager().addToHistory(target); UsageViewManager.getInstance(mySearchContext.getProject()).searchAndShowUsages( new UsageTarget[]{target}, - () -> new UsageSearcher() { - @Override - public void generate(@NotNull final Processor processor) { - findUsages(processor); - } - }, + () -> processor -> findUsages(processor), myProcessPresentation, presentation, new UsageViewManager.UsageViewStateListener() { @@ -70,7 +67,7 @@ public class SearchCommand { ); } - public void findUsages(final Processor processor) { + public void findUsages(@NotNull Processor processor) { final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); progress.setIndeterminate(false); @@ -78,13 +75,12 @@ public class SearchCommand { int count; @Override - public void setMatchingProcess(MatchingProcess _process) { - process = _process; + public void setMatchingProcess(@NotNull MatchingProcess _process) { findStarted(); } @Override - public void processFile(PsiFile element) { + public void processFile(@NotNull PsiFile element) { final VirtualFile virtualFile = element.getVirtualFile(); if (virtualFile != null) progress.setText(SSRBundle.message("looking.in.progress.message", virtualFile.getPresentableName())); @@ -103,7 +99,7 @@ public class SearchCommand { } @Override - public void newMatch(MatchResult result) { + public void newMatch(@NotNull MatchResult result) { UsageInfo info; if (MatchResult.MULTI_LINE_MATCH.equals(result.getName())) { diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchConfiguration.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchConfiguration.java index c69910875769..0eddbfc820bf 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchConfiguration.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchConfiguration.java @@ -3,7 +3,9 @@ package com.intellij.structuralsearch.plugin.ui; import com.intellij.structuralsearch.MatchOptions; import com.intellij.structuralsearch.NamedScriptableDefinition; +import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import org.jdom.Element; +import org.jetbrains.annotations.NotNull; /** * Configuration of the search @@ -16,28 +18,33 @@ public class SearchConfiguration extends Configuration { matchOptions = new MatchOptions(); } - SearchConfiguration(Configuration configuration) { + SearchConfiguration(@NotNull Configuration configuration) { super(configuration); matchOptions = configuration.getMatchOptions().copy(); } - public SearchConfiguration(String name, String category) { + public SearchConfiguration(@NotNull String name, @NotNull String category) { super(name, category); matchOptions = new MatchOptions(); } @Override - public SearchConfiguration copy() { + public @NotNull ReplaceOptions getReplaceOptions() { + throw new IllegalStateException(); + } + + @Override + public @NotNull SearchConfiguration copy() { return new SearchConfiguration(this); } @Override - public MatchOptions getMatchOptions() { + public @NotNull MatchOptions getMatchOptions() { return matchOptions; } @Override - public NamedScriptableDefinition findVariable(String name) { + public NamedScriptableDefinition findVariable(@NotNull String name) { return matchOptions.getVariableConstraint(name); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchDialog.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchDialog.java index c4d65cc69957..9c56dd7ea591 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchDialog.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchDialog.java @@ -73,15 +73,16 @@ import com.intellij.structuralsearch.plugin.replace.ui.ReplaceCommand; import com.intellij.structuralsearch.plugin.replace.ui.ReplaceConfiguration; import com.intellij.structuralsearch.plugin.ui.filters.FilterPanel; import com.intellij.structuralsearch.plugin.util.CollectingMatchResultSink; -import com.intellij.ui.*; +import com.intellij.ui.ComponentUtil; +import com.intellij.ui.EditorTextField; +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.OnePixelSplitter; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Alarm; -import com.intellij.util.IconUtil; import com.intellij.util.SmartList; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.textCompletion.TextCompletionUtil; -import com.intellij.util.ui.JBRectangle; import com.intellij.util.ui.TextTransferable; import org.jdom.JDOMException; import org.jetbrains.annotations.Nls; @@ -93,8 +94,10 @@ import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.datatransfer.DataFlavor; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import java.util.*; +import java.util.Objects; import static com.intellij.openapi.util.text.StringUtil.isEmpty; import static com.intellij.openapi.util.text.StringUtil.trimEnd; @@ -122,18 +125,19 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis private static final Key STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION = Key.create("STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION"); public static final Key TEST_STRUCTURAL_SEARCH_DIALOG = Key.create("TEST_STRUCTURAL_SEARCH_DIALOG"); + @NotNull private final SearchContext mySearchContext; - Editor myEditor; - boolean myReplace; - Configuration myConfiguration; - @NonNls LanguageFileType myFileType = StructuralSearchUtil.getDefaultFileType(); - Language myDialect = null; - PatternContext myPatternContext = null; - final List myRangeHighlighters = new SmartList<>(); + private Editor myEditor; + private boolean myReplace; + @NotNull + private Configuration myConfiguration; + @NotNull + @NonNls private LanguageFileType myFileType = StructuralSearchUtil.getDefaultFileType(); + private Language myDialect; + private PatternContext myPatternContext; + private final List myRangeHighlighters = new SmartList<>(); private final DocumentListener myRestartHighlightingListener = new DocumentListener() { - final Runnable runnable = () -> ReadAction.nonBlocking(() -> { - addMatchHighlights(); - }) + final Runnable runnable = () -> ReadAction.nonBlocking(() -> addMatchHighlights()) .withDocumentsCommitted(getProject()) .expireWith(getDisposable()) .coalesceBy(this) @@ -155,20 +159,20 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis private boolean myFilterIsShowing; // components - final FileTypeChooser myFileTypeChooser = new FileTypeChooser(); - ActionToolbarImpl myOptionsToolbar; - EditorTextField mySearchCriteriaEdit; - EditorTextField myReplaceCriteriaEdit; - OnePixelSplitter mySearchEditorPanel; + private final FileTypeChooser myFileTypeChooser = new FileTypeChooser(); + private ActionToolbarImpl myOptionsToolbar; + private EditorTextField mySearchCriteriaEdit; + private EditorTextField myReplaceCriteriaEdit; + private OnePixelSplitter mySearchEditorPanel; - FilterPanel myFilterPanel; + private FilterPanel myFilterPanel; private LinkComboBox myTargetComboBox; private ScopePanel myScopePanel; private JCheckBox myOpenInNewTab; - JComponent myReplacePanel; + private JComponent myReplacePanel; - public StructuralSearchDialog(SearchContext searchContext, boolean replace) { + public StructuralSearchDialog(@NotNull SearchContext searchContext, boolean replace) { this(searchContext, replace, false); } @@ -264,7 +268,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis initiateValidation(); } - void initiateValidation() { + private void initiateValidation() { if (myAlarm.isDisposed()) return; myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { @@ -313,13 +317,12 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis }, ModalityState.stateForComponent(myFilterPanel.getComponent())); } + @NotNull private Configuration createConfiguration(Configuration template) { if (myReplace) { return (template == null) ? new ReplaceConfiguration(getUserDefined(), getUserDefined()) : new ReplaceConfiguration(template); } - else { - return (template == null) ? new SearchConfiguration(getUserDefined(), getUserDefined()) : new SearchConfiguration(template); - } + return (template == null) ? new SearchConfiguration(getUserDefined(), getUserDefined()) : new SearchConfiguration(template); } private void setTextFromContext() { @@ -345,7 +348,8 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis final Configuration previousConfiguration = getProject().getUserData(STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION); if (previousConfiguration != null) { loadConfiguration(previousConfiguration); - } else { + } + else { final Configuration configuration = ConfigurationManager.getInstance(getProject()).getMostRecentConfiguration(); if (configuration != null) { loadConfiguration(configuration); @@ -380,7 +384,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis @NotNull @Nls @NlsContexts.DialogTitle - String getDefaultTitle() { + private String getDefaultTitle() { return myReplace ? SSRBundle.message("structural.replace.title") : SSRBundle.message("structural.search.title"); } @@ -752,7 +756,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis return panel; } - Project getProject() { + private Project getProject() { return mySearchContext.getProject(); } @@ -898,7 +902,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis } } - void removeMatchHighlights() { + private void removeMatchHighlights() { if (myEditConfigOnly) { return; } @@ -921,7 +925,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis }); } - void addMatchHighlights() { + private void addMatchHighlights() { if (myEditConfigOnly) { return; } @@ -950,7 +954,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis } } - private void addMatchHighlights(@NotNull List matchResults, + private void addMatchHighlights(@NotNull List matchResults, @NotNull Editor editor, @NotNull PsiFile file, @Nullable String statusBarText) { @@ -992,8 +996,8 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis }); } - Balloon myBalloon = null; - void reportMessage(@Nullable String message, boolean error, @NotNull JComponent component) { + private Balloon myBalloon; + private void reportMessage(@Nullable String message, boolean error, @NotNull JComponent component) { ApplicationManager.getApplication().invokeLater(() -> { if (myBalloon != null) myBalloon.hide(); component.putClientProperty("JComponent.outline", (!error || message == null) ? null : "error"); @@ -1015,7 +1019,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis }, ModalityState.stateForComponent(component)); } - void securityCheck() { + private void securityCheck() { final MatchOptions matchOptions = myConfiguration.getMatchOptions(); int scripts = 0; for (String name : matchOptions.getVariableConstraintNames()) { @@ -1023,10 +1027,8 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis if (constraint.getScriptCodeConstraint().length() > 2) scripts++; } final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions(); - if (replaceOptions != null) { - for (ReplacementVariableDefinition variableDefinition : replaceOptions.getVariableDefinitions()) { - if (variableDefinition.getScriptCodeConstraint().length() > 2) scripts++; - } + for (ReplacementVariableDefinition variableDefinition : replaceOptions.getVariableDefinitions()) { + if (variableDefinition.getScriptCodeConstraint().length() > 2) scripts++; } if (scripts > 0) { UIUtil.SSR_NOTIFICATION_GROUP.createNotification(NotificationType.WARNING) @@ -1042,7 +1044,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis myConfiguration.setCurrentVariableName(variableName); } - void setFilterPanelVisible(boolean visible) { + private void setFilterPanelVisible(boolean visible) { if (visible) { if (myFilterPanel.getVariable() == null) { myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(Configuration.CONTEXT_VAR_NAME, myConfiguration)); @@ -1059,7 +1061,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis } } - boolean isFilterPanelVisible() { + private boolean isFilterPanelVisible() { return mySearchEditorPanel.getSecondComponent() != null; } @@ -1089,7 +1091,7 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis * @param text the text to try and load a configuration from * @return {@code true}, if some configuration was found, even if it was broken or corrupted {@code false} otherwise. */ - boolean loadConfiguration(String text) { + private boolean loadConfiguration(String text) { if (text == null) { return false; } @@ -1172,15 +1174,12 @@ public class StructuralSearchDialog extends DialogWrapper implements DocumentLis matchOptions.setPatternContext(myPatternContext); matchOptions.setSearchPattern(getPattern(mySearchCriteriaEdit)); - final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions(); - - if (myReplace) { - replaceOptions.setReplacement(getPattern(myReplaceCriteriaEdit)); - matchOptions.setRecursiveSearch(false); - } final PropertiesComponent properties = PropertiesComponent.getInstance(); if (myReplace) { + final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions(); + replaceOptions.setReplacement(getPattern(myReplaceCriteriaEdit)); + matchOptions.setRecursiveSearch(false); properties.setValue(SHORTEN_FQN_STATE, replaceOptions.isToShortenFQN()); properties.setValue(USE_STATIC_IMPORT_STATE, replaceOptions.isToUseStaticImport()); properties.setValue(REFORMAT_STATE, replaceOptions.isToReformatAccordingToStyle()); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchTemplatesCompletionContributor.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchTemplatesCompletionContributor.java index 7e187b4f83ed..be14b9bae317 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchTemplatesCompletionContributor.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchTemplatesCompletionContributor.java @@ -15,7 +15,7 @@ import com.intellij.structuralsearch.MatchOptions; import com.intellij.ui.TextFieldWithAutoCompletionListProvider; import org.jetbrains.annotations.NotNull; -import java.util.LinkedHashSet; +import java.util.Set; public class StructuralSearchTemplatesCompletionContributor extends CompletionContributor { @Override @@ -34,7 +34,7 @@ public class StructuralSearchTemplatesCompletionContributor extends CompletionCo final CharSequence text = document.getCharsSequence(); if (StringUtil.startsWithChar(shortPrefix, '$')) { shortPrefix = shortPrefix.substring(1); - final LinkedHashSet variableNames = TemplateImplUtil.parseVariableNames(text); + Set variableNames = TemplateImplUtil.parseVariableNames(text); for (String name : variableNames) { if (name.startsWith(shortPrefix) && !name.equals(shortPrefix)) { result.addElement(LookupElementBuilder.create('$' + name + '$') @@ -75,7 +75,7 @@ public class StructuralSearchTemplatesCompletionContributor extends CompletionCo .withPresentableText(configurationName); if (dialog != null) element = element.withInsertHandler((InsertionContext context, LookupElement item) -> context.setLaterRunnable( - () -> { dialog.loadConfiguration((Configuration)item.getObject()); } + () -> dialog.loadConfiguration((Configuration)item.getObject()) )); insensitive.addElement(element); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchUsageTarget.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchUsageTarget.java index bae15ae8d188..e4c59d519eb3 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchUsageTarget.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchUsageTarget.java @@ -23,7 +23,7 @@ class StructuralSearchUsageTarget implements ConfigurableUsageTarget, ItemPresen private final Runnable mySearchStarter; private final SearchContext mySearchContext; - StructuralSearchUsageTarget(Configuration configuration, SearchContext searchContext, Runnable searchStarter) { + StructuralSearchUsageTarget(@NotNull Configuration configuration, @NotNull SearchContext searchContext, @NotNull Runnable searchStarter) { myConfiguration = configuration; mySearchStarter = searchStarter; mySearchContext = searchContext; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java index 8f281715df0d..ddcbc8ea6834 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java @@ -114,18 +114,18 @@ public final class UIUtil { () -> document.replaceString(0, document.getTextLength(), value)); } - public static void setContent(@NotNull EditorTextField editor, String text) { - final String value = text != null ? text : ""; + public static void setContent(@NotNull EditorTextField editor, @NotNull String text) { final Document document = editor.getDocument(); WriteCommandAction.runWriteCommandAction(editor.getProject(), SSRBundle.message("modify.editor.content.command.name"), SS_GROUP, - () -> document.replaceString(0, document.getTextLength(), value)); + () -> document.replaceString(0, document.getTextLength(), text)); } - public static void invokeAction(Configuration config, SearchContext context) { + public static void invokeAction(@NotNull Configuration config, @NotNull SearchContext context) { StructuralSearchAction.triggerAction(config, context, !(config instanceof SearchConfiguration)); } - public static MatchVariableConstraint getOrAddVariableConstraint(String varName, Configuration configuration) { + @NotNull + public static MatchVariableConstraint getOrAddVariableConstraint(@NotNull String varName, @NotNull Configuration configuration) { final MatchOptions options = configuration.getMatchOptions(); final MatchVariableConstraint varInfo = options.getVariableConstraint(varName); @@ -135,7 +135,8 @@ public final class UIUtil { return configuration.getMatchOptions().addNewVariableConstraint(varName); } - public static ReplacementVariableDefinition getOrAddReplacementVariable(String varName, Configuration configuration) { + @NotNull + public static ReplacementVariableDefinition getOrAddReplacementVariable(@NotNull String varName, @NotNull Configuration configuration) { final ReplaceOptions replaceOptions = configuration.getReplaceOptions(); ReplacementVariableDefinition definition = replaceOptions.getVariableDefinition(varName); @@ -145,7 +146,7 @@ public final class UIUtil { return replaceOptions.addNewVariableDefinition(varName); } - public static boolean isTarget(String varName, MatchOptions matchOptions) { + public static boolean isTarget(@NotNull String varName, @NotNull MatchOptions matchOptions) { if (Configuration.CONTEXT_VAR_NAME.equals(varName)) { // Complete Match is default target for (String name : matchOptions.getVariableConstraintNames()) { @@ -165,14 +166,14 @@ public final class UIUtil { } @NotNull - public static JComponent createCompleteMatchInfo(final Supplier configurationProducer) { + public static JComponent createCompleteMatchInfo(@NotNull Supplier configurationProducer) { return installCompleteMatchInfo(new JLabel(AllIcons.Actions.ListFiles), configurationProducer, null); } @NotNull - public static JComponent installCompleteMatchInfo(JLabel completeMatchInfo, - Supplier configurationProducer, - Consumer linkConsumer) { + public static JComponent installCompleteMatchInfo(@NotNull JLabel completeMatchInfo, + @NotNull Supplier configurationProducer, + @Nullable Consumer linkConsumer) { completeMatchInfo.putClientProperty(IdeTooltip.TOOLTIP_DISMISS_DELAY_KEY, 20000); completeMatchInfo.addMouseListener(new MouseAdapter() { @Override @@ -219,27 +220,30 @@ public final class UIUtil { return completeMatchInfo; } - public static EditorTextField createTextComponent(String text, Project project) { + @NotNull + public static EditorTextField createTextComponent(@NotNull String text, @NotNull Project project) { return createEditorComponent(text, "1.txt", project); } - public static EditorTextField createRegexComponent(String text, Project project) { + @NotNull + public static EditorTextField createRegexComponent(@NotNull String text, @NotNull Project project) { return createEditorComponent(text, "1.regexp", project); } - public static EditorTextField createScriptComponent(String text, Project project) { + @NotNull + public static EditorTextField createScriptComponent(@NotNull String text, @NotNull Project project) { return createEditorComponent(text, "1.groovy", project); } @NotNull - public static EditorTextField createEditorComponent(String text, String fileName, Project project) { + public static EditorTextField createEditorComponent(@NotNull String text, @NotNull String fileName, @NotNull Project project) { final FileType fileType = getFileType(fileName); final Document document = createDocument(fileType, text, project); return new EditorTextField(document, project, fileType); } @NotNull - public static Document createDocument(FileType fileType, String text, Project project) { + public static Document createDocument(@NotNull FileType fileType, @NotNull String text, @NotNull Project project) { final PsiFile file = PsiFileFactory.getInstance(project).createFileFromText("Dummy." + fileType.getDefaultExtension(), fileType, text, -1, true); final Document document = PsiDocumentManager.getInstance(project).getDocument(file); @@ -247,12 +251,14 @@ public final class UIUtil { return document; } - private static FileType getFileType(final String fileName) { + @NotNull + private static FileType getFileType(@NotNull String fileName) { FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName); if (fileType == FileTypes.UNKNOWN) fileType = FileTypes.PLAIN_TEXT; return fileType; } + @NotNull public static LanguageFileType detectFileType(@NotNull SearchContext searchContext) { final PsiFile file = searchContext.getFile(); PsiElement context = null; @@ -275,8 +281,11 @@ public final class UIUtil { final Language language = context.getLanguage(); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language); if (profile != null) { - final LanguageFileType fileType = profile.detectFileType(context); - return fileType != null ? fileType : language.getAssociatedFileType(); + LanguageFileType fileType = profile.detectFileType(context); + if (fileType == null) { + fileType = language.getAssociatedFileType(); + } + if (fileType != null) return fileType; } } return StructuralSearchUtil.getDefaultFileType(); @@ -329,7 +338,7 @@ public final class UIUtil { : factory.createFileFromText(name, dialect, text, true, true); } - public static TemplateContextType getTemplateContextType(StructuralSearchProfile profile) { + public static TemplateContextType getTemplateContextType(@NotNull StructuralSearchProfile profile) { final Class clazz = profile.getTemplateContextTypeClass(); return ContainerUtil.findInstance(TemplateContextType.EP_NAME.getExtensions(), clazz); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UsageViewContext.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UsageViewContext.java index 25f6c552d1ef..a276479e594c 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UsageViewContext.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UsageViewContext.java @@ -18,18 +18,21 @@ import java.awt.event.ActionEvent; public class UsageViewContext { + @NotNull protected final SearchContext mySearchContext; + @NotNull protected final Configuration myConfiguration; + @NotNull private final ConfigurableUsageTarget myTarget; protected UsageView myUsageView; - protected UsageViewContext(Configuration configuration, SearchContext searchContext, Runnable searchStarter) { + protected UsageViewContext(@NotNull Configuration configuration, @NotNull SearchContext searchContext, @NotNull Runnable searchStarter) { myConfiguration = configuration; mySearchContext = searchContext; myTarget = new StructuralSearchUsageTarget(configuration, searchContext, searchStarter); } - public void setUsageView(final UsageView usageView) { + public void setUsageView(@NotNull UsageView usageView) { myUsageView = usageView; final MessageBusConnection connection = mySearchContext.getProject().getMessageBus().connect(usageView); connection.subscribe(DynamicPluginListener.TOPIC, new DynamicPluginListener() { @@ -40,7 +43,7 @@ public class UsageViewContext { }); } - public ConfigurableUsageTarget getTarget() { + public @NotNull ConfigurableUsageTarget getTarget() { return myTarget; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/CollectingMatchResultSink.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/CollectingMatchResultSink.java index 450ecdced42a..ab810d0e3612 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/CollectingMatchResultSink.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/CollectingMatchResultSink.java @@ -12,7 +12,7 @@ public class CollectingMatchResultSink extends DefaultMatchResultSink { private final List matches = new SmartList<>(); @Override - public void newMatch(MatchResult result) { + public void newMatch(@NotNull MatchResult result) { matches.add(result); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/DuplicateFilteringResultSink.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/DuplicateFilteringResultSink.java index 648de0674207..0acd5448704a 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/DuplicateFilteringResultSink.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/DuplicateFilteringResultSink.java @@ -6,6 +6,7 @@ import com.intellij.structuralsearch.MatchResult; import com.intellij.structuralsearch.MatchResultSink; import com.intellij.structuralsearch.MatchingProcess; import gnu.trove.THashSet; +import org.jetbrains.annotations.NotNull; import java.util.Set; @@ -14,14 +15,14 @@ import java.util.Set; */ public class DuplicateFilteringResultSink implements MatchResultSink { private final MatchResultSink delegate; - final Set duplicates = new THashSet<>(); + private final Set duplicates = new THashSet<>(); - public DuplicateFilteringResultSink(MatchResultSink delegate) { + public DuplicateFilteringResultSink(@NotNull MatchResultSink delegate) { this.delegate = delegate; } @Override - public void newMatch(MatchResult result) { + public void newMatch(@NotNull MatchResult result) { if (!duplicates.add(result.getMatchRef())) { return; } @@ -29,12 +30,12 @@ public class DuplicateFilteringResultSink implements MatchResultSink { } @Override - public void processFile(PsiFile element) { + public void processFile(@NotNull PsiFile element) { delegate.processFile(element); } @Override - public void setMatchingProcess(MatchingProcess matchingProcess) { + public void setMatchingProcess(@NotNull MatchingProcess matchingProcess) { delegate.setMatchingProcess(matchingProcess); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/SmartPsiPointer.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/SmartPsiPointer.java index c69f6eb45f21..cd9aeb812c61 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/SmartPsiPointer.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/util/SmartPsiPointer.java @@ -1,23 +1,24 @@ package com.intellij.structuralsearch.plugin.util; -import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; +import org.jetbrains.annotations.NotNull; /** * Reference to element have been matched */ public class SmartPsiPointer { - private SmartPsiElementPointer pointer; + @NotNull + private final SmartPsiElementPointer pointer; - public SmartPsiPointer(PsiElement element) { - pointer = element != null ? SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element):null; + public SmartPsiPointer(@NotNull PsiElement element) { + pointer = SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element); } public VirtualFile getFile() { - return pointer != null ? pointer.getVirtualFile():null; + return pointer.getVirtualFile(); } public int getOffset() { @@ -31,16 +32,7 @@ public class SmartPsiPointer { } public PsiElement getElement() { - return pointer != null ? pointer.getElement():null; - } - - public void clear() { - pointer = null; - } - - public Project getProject() { - PsiElement element = getElement(); - return element == null ? null : element.getProject(); + return pointer.getElement(); } public boolean equals(Object o) { diff --git a/plugins/groovy/structuralsearch-groovy/src/com/intellij/structuralsearch/GroovyStructuralSearchProfile.java b/plugins/groovy/structuralsearch-groovy/src/com/intellij/structuralsearch/GroovyStructuralSearchProfile.java index e49674e30b49..ec18fcf9349e 100644 --- a/plugins/groovy/structuralsearch-groovy/src/com/intellij/structuralsearch/GroovyStructuralSearchProfile.java +++ b/plugins/groovy/structuralsearch-groovy/src/com/intellij/structuralsearch/GroovyStructuralSearchProfile.java @@ -53,7 +53,7 @@ public class GroovyStructuralSearchProfile extends StructuralSearchProfileBase { } @Override - public PsiCodeFragment createCodeFragment(Project project, String text, String contextId) { + public PsiCodeFragment createCodeFragment(@NotNull Project project, @NotNull String text, String contextId) { return new GroovyCodeFragment(project, text); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java index c467ea5f4458..2801d54cb969 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java @@ -229,7 +229,7 @@ public final class PyTypeChecker { } } - return StreamEx.of(actual.getMembers()).anyMatch(type -> match(expected, type, context).orElse(false)); + return ContainerUtil.or(actual.getMembers(), type -> match(expected, type, context).orElse(false)); } @NotNull @@ -244,7 +244,7 @@ public final class PyTypeChecker { } private static boolean match(@NotNull PyUnionType expected, @NotNull PyType actual, @NotNull MatchContext context) { - return StreamEx.of(expected.getMembers()).anyMatch(type -> match(type, actual, context).orElse(true)); + return ContainerUtil.or(expected.getMembers(), type -> match(type, actual, context).orElse(true)); } @NotNull @@ -405,11 +405,7 @@ public final class PyTypeChecker { final PyType superElementType = expected.getIteratedItemType(); final PyType subElementType = actual.getIteratedItemType(); - if (!match(superElementType, subElementType, context).orElse(true)) { - return false; - } - - return true; + return match(superElementType, subElementType, context).orElse(true); } private static boolean match(@NotNull PyStructuralType expected, @NotNull PyType actual, @NotNull TypeEvalContext context) { @@ -427,9 +423,8 @@ public final class PyTypeChecker { } final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context); - return StreamEx - .of(expected.getAttributeNames()) - .noneMatch(attribute -> ContainerUtil.isEmpty(actual.resolveMember(attribute, null, AccessDirection.READ, resolveContext))); + return !ContainerUtil.exists(expected.getAttributeNames(), attribute -> ContainerUtil + .isEmpty(actual.resolveMember(attribute, null, AccessDirection.READ, resolveContext))); } private static boolean match(@NotNull PyStructuralType expected, @NotNull PyStructuralType actual) { @@ -598,8 +593,8 @@ public final class PyTypeChecker { return !collected.isEmpty(); } - private static void collectGenerics(@Nullable PyType type, @NotNull TypeEvalContext context, @NotNull Set collected, - @NotNull Set visited) { + private static void collectGenerics(@Nullable PyType type, @NotNull TypeEvalContext context, @NotNull Set collected, + @NotNull Set visited) { if (visited.contains(type)) { return; } @@ -762,7 +757,7 @@ public final class PyTypeChecker { return substitutions; } - private static boolean matchContainer(@Nullable PyCallableParameter container, @NotNull List arguments, + private static boolean matchContainer(@Nullable PyCallableParameter container, @NotNull List arguments, @NotNull Map substitutions, @NotNull TypeEvalContext context) { if (container == null) { return true;