Class CheckUtil
java.lang.Object
com.puppycrawl.tools.checkstyle.utils.CheckUtil
Contains utility methods for the checks.
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final PatternCompiled pattern for all system newlines.private static final intDecimal radix.private static final intHex radix.private static final intBinary radix.private static final intOctal radix.private static final charPackage separator.private static final PatternPattern matching underscore characters ('_'). -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static booleanChecks if a given IF terminated by return, throw or, if allowed break, continue.private static booleanChecks if a given loop terminated by return, throw or, if allowed break, continue.private static booleancheckSlist(DetailAST slistAst, boolean useBreak, boolean useContinue, Set<String> labels) Checks if a given SLIST terminated by return, throw or, if allowed break, continue.private static booleancheckSwitch(DetailAST literalSwitchAst, boolean useContinue, Set<String> labels) Checks if a given switch terminated by return, throw or, if allowed break, continue.private static booleancheckSynchronized(DetailAST synchronizedAst, boolean useBreak, boolean useContinue, Set<String> labels) Checks if a given synchronized block terminated by return, throw or, if allowed break, continue.private static booleanChecks if a given try/catch/finally block terminated by return, throw or, if allowed break, continue.static StringGet name of package and super class of anon inner class by concatenating the identifier values underTokenTypes.DOT.static AccessModifierOptionReturns the access modifier of the method/constructor at the specified AST.private static AccessModifierOptiongetAccessModifierFromModifiersTokenDirectly(DetailAST modifiersToken) ReturnsAccessModifierOptionbased on the information about access modifier taken from the given token of typeTokenTypes.MODIFIERS.static DetailASTgetFirstNode(DetailAST node) Finds sub-node for given node minimal (line, column) pair.static DetailASTThis method will skip the comment content while finding the next ast of current ast.static StringgetQualifiedTypeDeclarationName(String packageName, String outerClassQualifiedName, String className) Get the qualified name of type declaration by combiningpackageName,outerClassQualifiedNameandclassName.static StringgetShortNameOfAnonInnerClass(DetailAST literalNewAst) Get the short name of super class of anonymous inner class.private static intgetSmallestIndent(Collection<String> lines) Helper method for stripIndentAndInitialNewLineFromTextBlock, to determine the smallest indent in a text block string literal.static Optional<AccessModifierOption> Returns the access modifier of the surrounding "block".Retrieves the names of the type parameters to the node.getTypeParameters(DetailAST node) Retrieves the type parameters to the node.private static booleanChecks if given break or continue ast has outer label.static booleanisBeforeInSource(DetailAST ast1, DetailAST ast2) Retrieves whether ast1 is located before ast2.static booleanisEqualsMethod(DetailAST ast) Tests whether a method definition AST defines an equals covariant.static booleanisNonVoidMethod(DetailAST methodDefAst) Checks whether a method is a not void one.static booleanisPackageInfo(String filePath) Checks if the given file path is a package-info.java file.static booleanisReceiverParameter(DetailAST parameterDefAst) Checks whether a parameter is a receiver.static booleanisTerminated(DetailAST ast) Checks if a given subtree is terminated by return, throw, break, continue, or yield.private static booleanisTerminated(DetailAST ast, boolean useBreak, boolean useContinue, Set<String> labelsForCurrentSwitchScope) Checks if a given subtree terminated by return, throw, yield or, if allowed break, continue.private static intHelper method to find the index of the last non-whitespace character in a string.parseClassNames(String... classNames) Create set of class names and short class names.static doubleparseDouble(String text, int type) Returns the value represented by the specified string of the specified type.private static doubleparseNumber(String text, int radix, int type) Parses the string argument as an integer or a long in the radix specified by the second argument.static StringstripIndentAndInitialNewLineFromTextBlock(String textBlockContent) Strip initial newline and preceding whitespace on each line from text block content.private static StringstripIndentAndTrailingWhitespaceFromLine(String line, int indent) Helper method for stripIndentAndInitialNewLineFromTextBlock, strips correct indent from string, and trailing whitespace, or returns empty string if no text.static inttypeDeclarationNameMatchingCount(String patternClass, String classToBeMatched) Calculates and returns the type declaration name matching count.
-
Field Details
-
BASE_2
Binary radix.- See Also:
-
BASE_8
Octal radix.- See Also:
-
BASE_10
Decimal radix.- See Also:
-
BASE_16
Hex radix.- See Also:
-
UNDERSCORE_PATTERN
Pattern matching underscore characters ('_'). -
ALL_NEW_LINES
Compiled pattern for all system newlines. -
PACKAGE_SEPARATOR
Package separator.- See Also:
-
-
Constructor Details
-
CheckUtil
private CheckUtil()Prevent instances.
-
-
Method Details
-
isEqualsMethod
Tests whether a method definition AST defines an equals covariant.- Parameters:
ast- the method definition AST to test. Precondition: ast is a TokenTypes.METHOD_DEF node.- Returns:
- true if ast defines an equals covariant.
-
parseDouble
Returns the value represented by the specified string of the specified type. Returns 0 for types other than float, double, int, and long.- Parameters:
text- the string to be parsed.type- the token type of the text. Should be a constant ofTokenTypes.- Returns:
- the double value represented by the string argument.
-
parseNumber
Parses the string argument as an integer or a long in the radix specified by the second argument. The characters in the string must all be digits of the specified radix.- Parameters:
text- the String containing the integer representation to be parsed. Precondition: text contains a parsable int.radix- the radix to be used while parsing text.type- the token type of the text. Should be a constant ofTokenTypes.- Returns:
- the number represented by the string argument in the specified radix.
-
getFirstNode
Finds sub-node for given node minimal (line, column) pair.- Parameters:
node- the root of tree for search.- Returns:
- sub-node with minimal (line, column) pair.
-
isBeforeInSource
Retrieves whether ast1 is located before ast2.- Parameters:
ast1- the first node.ast2- the second node.- Returns:
- true, if ast1 is located before ast2.
-
getTypeParameterNames
Retrieves the names of the type parameters to the node.- Parameters:
node- the parameterized AST node- Returns:
- a list of type parameter names
-
getTypeParameters
Retrieves the type parameters to the node.- Parameters:
node- the parameterized AST node- Returns:
- a list of type parameter names
-
isNonVoidMethod
Checks whether a method is a not void one.- Parameters:
methodDefAst- the method node.- Returns:
- true if method is a not void one.
-
isReceiverParameter
Checks whether a parameter is a receiver.A receiver parameter is a special parameter that represents the object for which the method is invoked. It is denoted by the reserved keyword
thisin the method declaration. Check PARAMETER_DEF- Parameters:
parameterDefAst- the parameter node.- Returns:
- true if the parameter is a receiver.
- See Also:
-
getAccessModifierFromModifiersToken
Returns the access modifier of the method/constructor at the specified AST. If the method is in an interface or annotation block, the access modifier is assumed to be public.- Parameters:
ast- the token of the method/constructor.- Returns:
- the access modifier of the method/constructor.
-
getAccessModifierFromModifiersTokenDirectly
private static AccessModifierOption getAccessModifierFromModifiersTokenDirectly(DetailAST modifiersToken) ReturnsAccessModifierOptionbased on the information about access modifier taken from the given token of typeTokenTypes.MODIFIERS.- Parameters:
modifiersToken- token of typeTokenTypes.MODIFIERS.- Returns:
AccessModifierOption.- Throws:
IllegalArgumentException- when expected non-null modifiersToken with type 'MODIFIERS'
-
getSurroundingAccessModifier
Returns the access modifier of the surrounding "block".- Parameters:
node- the node to return the access modifier for- Returns:
- the access modifier of the surrounding block
-
parseClassNames
Create set of class names and short class names.- Parameters:
classNames- array of class names.- Returns:
- set of class names and short class names.
-
stripIndentAndInitialNewLineFromTextBlock
Strip initial newline and preceding whitespace on each line from text block content. In order to be consistent with how javac handles this task, we have modeled this implementation after the code from: github.com/openjdk/jdk14u/blob/master/src/java.base/share/classes/java/lang/String.java- Parameters:
textBlockContent- the actual content of the text block.- Returns:
- string consistent with javac representation.
-
stripIndentAndTrailingWhitespaceFromLine
Helper method for stripIndentAndInitialNewLineFromTextBlock, strips correct indent from string, and trailing whitespace, or returns empty string if no text.- Parameters:
line- the string to strip indent and trailing whitespace fromindent- the amount of indent to remove- Returns:
- modified string with removed indent and trailing whitespace, or empty string.
-
getSmallestIndent
Helper method for stripIndentAndInitialNewLineFromTextBlock, to determine the smallest indent in a text block string literal.- Parameters:
lines- collection of actual text block content, split by line.- Returns:
- number of spaces representing the smallest indent in this text block.
-
lastIndexOfNonWhitespace
Helper method to find the index of the last non-whitespace character in a string.- Parameters:
line- the string to find the last index of a non-whitespace character for.- Returns:
- the index of the last non-whitespace character.
-
typeDeclarationNameMatchingCount
Calculates and returns the type declaration name matching count.Suppose our pattern class is
foo.a.band class to be matched isfoo.a.ballthen type declaration name matching count would be calculated by comparing every character, and updating main counter when we hit "." to prevent matching "a.b" with "a.ball". In this case type declaration name matching count would be equal to 6 and not 7 (b of ball is not counted).- Parameters:
patternClass- class against which the given class has to be matchedclassToBeMatched- class to be matched- Returns:
- class name matching count
-
getQualifiedTypeDeclarationName
public static String getQualifiedTypeDeclarationName(String packageName, String outerClassQualifiedName, String className) Get the qualified name of type declaration by combiningpackageName,outerClassQualifiedNameandclassName.- Parameters:
packageName- packageNameouterClassQualifiedName- outerClassQualifiedNameclassName- className- Returns:
- the qualified name of type declaration by combining
packageName,outerClassQualifiedNameandclassName
-
extractQualifiedName
Get name of package and super class of anon inner class by concatenating the identifier values underTokenTypes.DOT.- Parameters:
ast- ast to extract superclass or package name from- Returns:
- qualified name
-
getShortNameOfAnonInnerClass
Get the short name of super class of anonymous inner class. Example:TestClass.NestedClass obj = new Test().new NestedClass() {}; // Short name will be Test.NestedClass- Parameters:
literalNewAst- ast node of typeTokenTypes.LITERAL_NEW- Returns:
- short name of base class of anonymous inner class
-
isPackageInfo
Checks if the given file path is a package-info.java file.- Parameters:
filePath- path to the file.- Returns:
- true if the package file.
-
isTerminated
Checks if a given subtree is terminated by return, throw, break, continue, or yield.- Parameters:
ast- root of given subtree- Returns:
- true if the subtree is terminated.
-
isTerminated
private static boolean isTerminated(DetailAST ast, boolean useBreak, boolean useContinue, Set<String> labelsForCurrentSwitchScope) Checks if a given subtree terminated by return, throw, yield or, if allowed break, continue. When analyzing fall-through cases in switch statements, a Set of String labels is used to keep track of the labels encountered in the enclosing switch statements.- Parameters:
ast- root of given subtreeuseBreak- should we consider break as terminatoruseContinue- should we consider continue as terminatorlabelsForCurrentSwitchScope- the Set labels for the current scope of the switch- Returns:
- true if the subtree is terminated.
-
hasLabel
Checks if given break or continue ast has outer label.- Parameters:
statement- break or continue nodelabelsForCurrentSwitchScope- the Set labels for the current scope of the switch- Returns:
- true if local label used
-
checkSlist
private static boolean checkSlist(DetailAST slistAst, boolean useBreak, boolean useContinue, Set<String> labels) Checks if a given SLIST terminated by return, throw or, if allowed break, continue.- Parameters:
slistAst- SLIST to checkuseBreak- should we consider break as terminatoruseContinue- should we consider continue as terminatorlabels- label names- Returns:
- true if SLIST is terminated.
-
checkIf
private static boolean checkIf(DetailAST ast, boolean useBreak, boolean useContinue, Set<String> labels) Checks if a given IF terminated by return, throw or, if allowed break, continue.- Parameters:
ast- IF to checkuseBreak- should we consider break as terminatoruseContinue- should we consider continue as terminatorlabels- label names- Returns:
- true if IF is terminated.
-
getNextNonCommentAst
This method will skip the comment content while finding the next ast of current ast.- Parameters:
ast- current ast- Returns:
- next ast after skipping comment
-
checkLoop
Checks if a given loop terminated by return, throw or, if allowed break, continue.- Parameters:
ast- loop to checklabels- label names- Returns:
- true if loop is terminated.
-
checkTry
private static boolean checkTry(DetailAST ast, boolean useBreak, boolean useContinue, Set<String> labels) Checks if a given try/catch/finally block terminated by return, throw or, if allowed break, continue.- Parameters:
ast- loop to checkuseBreak- should we consider break as terminatoruseContinue- should we consider continue as terminatorlabels- label names- Returns:
- true if try/catch/finally block is terminated
-
checkSwitch
private static boolean checkSwitch(DetailAST literalSwitchAst, boolean useContinue, Set<String> labels) Checks if a given switch terminated by return, throw or, if allowed break, continue.- Parameters:
literalSwitchAst- loop to checkuseContinue- should we consider continue as terminatorlabels- label names- Returns:
- true if switch is terminated
-
checkSynchronized
private static boolean checkSynchronized(DetailAST synchronizedAst, boolean useBreak, boolean useContinue, Set<String> labels) Checks if a given synchronized block terminated by return, throw or, if allowed break, continue.- Parameters:
synchronizedAst- synchronized block to check.useBreak- should we consider break as terminatoruseContinue- should we consider continue as terminatorlabels- label names- Returns:
- true if synchronized block is terminated
-