Class VariableDeclarationUsageDistanceCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
public class VariableDeclarationUsageDistanceCheck extends AbstractCheck
Checks the distance between declaration of variable and its first usage. Note : Variable declaration/initialization statements are not counted while calculating length.-
Property
allowedDistance
- Specify distance between declaration of variable and its first usage. Values should be greater than 0. Type isint
. Default value is3
. -
Property
ignoreFinal
- Allow to ignore variables with a 'final' modifier. Type isboolean
. Default value istrue
. -
Property
ignoreVariablePattern
- Define RegExp to ignore distance calculation for variables listed in this pattern. Type isjava.util.regex.Pattern
. Default value is""
. -
Property
validateBetweenScopes
- Allow to calculate the distance between declaration of variable and its first usage in the different scopes. Type isboolean
. Default value isfalse
.
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
variable.declaration.usage.distance
-
variable.declaration.usage.distance.extend
- Since:
- 5.8
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private int
allowedDistance
Specify distance between declaration of variable and its first usage.private static int
DEFAULT_DISTANCE
Default value of distance between declaration of variable and its first usage.private boolean
ignoreFinal
Allow to ignore variables with a 'final' modifier.private Pattern
ignoreVariablePattern
Define RegExp to ignore distance calculation for variables listed in this pattern.static String
MSG_KEY
Warning message key.static String
MSG_KEY_EXT
Warning message key.private boolean
validateBetweenScopes
Allow to calculate the distance between declaration of variable and its first usage in the different scopes.
-
Constructor Summary
Constructors Constructor Description VariableDeclarationUsageDistanceCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private static Map.Entry<DetailAST,Integer>
calculateDistanceBetweenScopes(DetailAST ast, DetailAST variable)
Calculates distance between declaration of variable and its first usage in multiple scopes.private static Map.Entry<DetailAST,Integer>
calculateDistanceInSingleScope(DetailAST semicolonAst, DetailAST variableIdentAst)
Calculates distance between declaration of variable and its first usage in single scope.int[]
getAcceptableTokens()
The configurable token set.int[]
getDefaultTokens()
Returns the default token a check is interested in.private static int
getDistToVariableUsageInChildNode(DetailAST childNode, int currentDistToVarUsage)
Returns the distance to variable usage for in the child node.private static DetailAST
getFirstNodeInsideForWhileDoWhileBlocks(DetailAST block, DetailAST variable)
Gets first Ast node inside FOR, WHILE or DO-WHILE blocks if variable usage is met only inside the block (not in its declaration!).private static DetailAST
getFirstNodeInsideIfBlock(DetailAST block, DetailAST variable)
Gets first Ast node inside IF block if variable usage is met only inside the block (not in its declaration!).private static DetailAST
getFirstNodeInsideSwitchBlock(DetailAST block, DetailAST variable)
Gets first Ast node inside SWITCH block if variable usage is met only inside the block (not in its declaration!).private static DetailAST
getFirstNodeInsideTryCatchFinallyBlocks(DetailAST block, DetailAST variable)
Gets first Ast node inside TRY-CATCH-FINALLY blocks if variable usage is met only inside the block (not in its declaration!).private static String
getInstanceName(DetailAST methodCallAst)
Get name of instance whose method is called.int[]
getRequiredTokens()
The tokens that this check must be registered for.private static List<DetailAST>
getVariableUsageExpressionsInsideSwitchBlock(DetailAST block, DetailAST variable)
Helper method for getFirstNodeInsideSwitchBlock to return all variable usage expressions inside a given switch block.private static boolean
isChild(DetailAST parent, DetailAST ast)
Checks if Ast node contains given element.private static boolean
isInitializationSequence(DetailAST variableUsageAst, String variableName)
Processes statements until usage of variable to detect sequence of initialization methods.private static boolean
isVariableInOperatorExpr(DetailAST operator, DetailAST variable)
Checks if variable is in operator declaration.private boolean
isVariableMatchesIgnorePattern(String variable)
Checks if entrance variable is contained in ignored pattern.private static boolean
isZeroDistanceToken(int type)
Check if the token should be ignored for distance counting.private static Map.Entry<List<DetailAST>,Integer>
searchVariableUsageExpressions(DetailAST variableAst, DetailAST statementAst)
Searches variable usages starting from specified statement.void
setAllowedDistance(int allowedDistance)
Setter to specify distance between declaration of variable and its first usage.void
setIgnoreFinal(boolean ignoreFinal)
Setter to allow to ignore variables with a 'final' modifier.void
setIgnoreVariablePattern(Pattern pattern)
Setter to define RegExp to ignore distance calculation for variables listed in this pattern.void
setValidateBetweenScopes(boolean validateBetweenScopes)
Setter to allow to calculate the distance between declaration of variable and its first usage in the different scopes.void
visitToken(DetailAST ast)
Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_KEY
public static final String MSG_KEY
Warning message key.- See Also:
- Constant Field Values
-
MSG_KEY_EXT
public static final String MSG_KEY_EXT
Warning message key.- See Also:
- Constant Field Values
-
DEFAULT_DISTANCE
private static final int DEFAULT_DISTANCE
Default value of distance between declaration of variable and its first usage.- See Also:
- Constant Field Values
-
allowedDistance
private int allowedDistance
Specify distance between declaration of variable and its first usage. Values should be greater than 0.
-
ignoreVariablePattern
private Pattern ignoreVariablePattern
Define RegExp to ignore distance calculation for variables listed in this pattern.
-
validateBetweenScopes
private boolean validateBetweenScopes
Allow to calculate the distance between declaration of variable and its first usage in the different scopes.
-
ignoreFinal
private boolean ignoreFinal
Allow to ignore variables with a 'final' modifier.
-
-
Constructor Detail
-
VariableDeclarationUsageDistanceCheck
public VariableDeclarationUsageDistanceCheck()
-
-
Method Detail
-
setAllowedDistance
public void setAllowedDistance(int allowedDistance)
Setter to specify distance between declaration of variable and its first usage. Values should be greater than 0.- Parameters:
allowedDistance
- Allowed distance between declaration of variable and its first usage.- Since:
- 5.8
-
setIgnoreVariablePattern
public void setIgnoreVariablePattern(Pattern pattern)
Setter to define RegExp to ignore distance calculation for variables listed in this pattern.- Parameters:
pattern
- a pattern.- Since:
- 5.8
-
setValidateBetweenScopes
public void setValidateBetweenScopes(boolean validateBetweenScopes)
Setter to allow to calculate the distance between declaration of variable and its first usage in the different scopes.- Parameters:
validateBetweenScopes
- Defines if allow to calculate distance between declaration of variable and its first usage in different scopes or not.- Since:
- 5.8
-
setIgnoreFinal
public void setIgnoreFinal(boolean ignoreFinal)
Setter to allow to ignore variables with a 'final' modifier.- Parameters:
ignoreFinal
- Defines if ignore variables with 'final' modifier or not.- Since:
- 5.8
-
getDefaultTokens
public int[] getDefaultTokens()
Description copied from class:AbstractCheck
Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokens
in classAbstractCheck
- Returns:
- the default tokens
- See Also:
TokenTypes
-
getAcceptableTokens
public int[] getAcceptableTokens()
Description copied from class:AbstractCheck
The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.- Specified by:
getAcceptableTokens
in classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
TokenTypes
-
getRequiredTokens
public int[] getRequiredTokens()
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
getInstanceName
private static String getInstanceName(DetailAST methodCallAst)
Get name of instance whose method is called.- Parameters:
methodCallAst
- DetailAST of METHOD_CALL.- Returns:
- name of instance.
-
isInitializationSequence
private static boolean isInitializationSequence(DetailAST variableUsageAst, String variableName)
Processes statements until usage of variable to detect sequence of initialization methods.- Parameters:
variableUsageAst
- DetailAST of expression that uses variable named variableName.variableName
- name of considered variable.- Returns:
- true if statements between declaration and usage of variable are initialization methods.
-
calculateDistanceInSingleScope
private static Map.Entry<DetailAST,Integer> calculateDistanceInSingleScope(DetailAST semicolonAst, DetailAST variableIdentAst)
Calculates distance between declaration of variable and its first usage in single scope.- Parameters:
semicolonAst
- Regular node of Ast which is checked for content of checking variable.variableIdentAst
- Variable which distance is calculated for.- Returns:
- entry which contains expression with variable usage and distance. If variable usage is not found, then the expression node is null, although the distance can be greater than zero.
-
getDistToVariableUsageInChildNode
private static int getDistToVariableUsageInChildNode(DetailAST childNode, int currentDistToVarUsage)
Returns the distance to variable usage for in the child node.- Parameters:
childNode
- child node.currentDistToVarUsage
- current distance to the variable usage.- Returns:
- the distance to variable usage for in the child node.
-
calculateDistanceBetweenScopes
private static Map.Entry<DetailAST,Integer> calculateDistanceBetweenScopes(DetailAST ast, DetailAST variable)
Calculates distance between declaration of variable and its first usage in multiple scopes.- Parameters:
ast
- Regular node of Ast which is checked for content of checking variable.variable
- Variable which distance is calculated for.- Returns:
- entry which contains expression with variable usage and distance.
-
searchVariableUsageExpressions
private static Map.Entry<List<DetailAST>,Integer> searchVariableUsageExpressions(DetailAST variableAst, DetailAST statementAst)
Searches variable usages starting from specified statement.- Parameters:
variableAst
- Variable that is used.statementAst
- DetailAST to start searching from.- Returns:
- entry which contains list with found expressions that use the variable and distance from specified statement to first found expression.
-
getFirstNodeInsideForWhileDoWhileBlocks
private static DetailAST getFirstNodeInsideForWhileDoWhileBlocks(DetailAST block, DetailAST variable)
Gets first Ast node inside FOR, WHILE or DO-WHILE blocks if variable usage is met only inside the block (not in its declaration!).- Parameters:
block
- Ast node represents FOR, WHILE or DO-WHILE block.variable
- Variable which is checked for content in block.- Returns:
- If variable usage is met only inside the block (not in its declaration!) then return the first Ast node of this block, otherwise - null.
-
getFirstNodeInsideIfBlock
private static DetailAST getFirstNodeInsideIfBlock(DetailAST block, DetailAST variable)
Gets first Ast node inside IF block if variable usage is met only inside the block (not in its declaration!).- Parameters:
block
- Ast node represents IF block.variable
- Variable which is checked for content in block.- Returns:
- If variable usage is met only inside the block (not in its declaration!) then return the first Ast node of this block, otherwise - null.
-
getFirstNodeInsideSwitchBlock
private static DetailAST getFirstNodeInsideSwitchBlock(DetailAST block, DetailAST variable)
Gets first Ast node inside SWITCH block if variable usage is met only inside the block (not in its declaration!).- Parameters:
block
- Ast node represents SWITCH block.variable
- Variable which is checked for content in block.- Returns:
- If variable usage is met only inside the block (not in its declaration!) then return the first Ast node of this block, otherwise - null.
-
getVariableUsageExpressionsInsideSwitchBlock
private static List<DetailAST> getVariableUsageExpressionsInsideSwitchBlock(DetailAST block, DetailAST variable)
Helper method for getFirstNodeInsideSwitchBlock to return all variable usage expressions inside a given switch block.- Parameters:
block
- the switch block to check.variable
- variable which is checked for in switch block.- Returns:
- List of usages or empty list if none are found.
-
getFirstNodeInsideTryCatchFinallyBlocks
private static DetailAST getFirstNodeInsideTryCatchFinallyBlocks(DetailAST block, DetailAST variable)
Gets first Ast node inside TRY-CATCH-FINALLY blocks if variable usage is met only inside the block (not in its declaration!).- Parameters:
block
- Ast node represents TRY-CATCH-FINALLY block.variable
- Variable which is checked for content in block.- Returns:
- If variable usage is met only inside the block (not in its declaration!) then return the first Ast node of this block, otherwise - null.
-
isVariableInOperatorExpr
private static boolean isVariableInOperatorExpr(DetailAST operator, DetailAST variable)
Checks if variable is in operator declaration. For instance:boolean b = true; if (b) {...}
Variable 'b' is in declaration of operator IF.- Parameters:
operator
- Ast node which represents operator.variable
- Variable which is checked for content in operator.- Returns:
- true if operator contains variable in its declaration, otherwise - false.
-
isChild
private static boolean isChild(DetailAST parent, DetailAST ast)
Checks if Ast node contains given element.- Parameters:
parent
- Node of AST.ast
- Ast element which is checked for content in Ast node.- Returns:
- true if Ast element was found in Ast node, otherwise - false.
-
isVariableMatchesIgnorePattern
private boolean isVariableMatchesIgnorePattern(String variable)
Checks if entrance variable is contained in ignored pattern.- Parameters:
variable
- Variable which is checked for content in ignored pattern.- Returns:
- true if variable was found, otherwise - false.
-
isZeroDistanceToken
private static boolean isZeroDistanceToken(int type)
Check if the token should be ignored for distance counting. For example,try (final AutoCloseable t = new java.io.StringReader(a);) { }
final is a zero-distance token and should be ignored for distance counting.class Table implements Comparator<Integer>{ }
An inner class may be defined. Both tokens implements and extends are zero-distance tokens.public int method(Object b){ }
public is a modifier and zero-distance token. int is a type and zero-distance token.- Parameters:
type
- Token type of the ast node.- Returns:
- true if it should be ignored for distance counting, otherwise false.
-
-