public class RequireThisCheck extends AbstractCheck
Checks that references to instance variables and methods of the present object are explicitly of the form "this.varName" or "this.methodName(args)" and that those references don't rely on the default behavior when "this." is absent.
Warning: the Check is very controversial if 'validateOnlyOverlapping' option is set to 'false' and not that actual nowadays.
Rationale:
Limitations: Nothing is currently done about static variables or catch-blocks. Static methods invoked on a class name seem to be OK; both the class name and the method name have a DOT parent. Non-static methods invoked on either this or a variable name seem to be OK, likewise.
checkFields - Control whether to check references to fields.
Type is boolean.
Default value is true.
checkMethods - Control whether to check references to methods.
Type is boolean.
Default value is true.
validateOnlyOverlapping - Control whether to check only
overlapping by variables or arguments.
Type is boolean.
Default value is true.
To configure the default check:
<module name="RequireThis"/>
Example:
public class Test {
private int a;
private int b;
private int c;
public Test(int a) {
// overlapping by constructor argument
this.a = a; // OK, this keyword used
b = 0; // OK, no overlap
foo(5); // OK
}
public void foo(int c) {
// overlapping by method argument
c = c; // violation, reference to instance variable "c" requires "this"
}
}
To configure the check for fields only:
<module name="RequireThis"> <property name="checkMethods" value="false"/> </module>
Example:
public class Test {
private int a;
private int b;
private int c;
public Test(int a) {
// overlapping by constructor argument
this.a = a; // OK, this keyword used
b = 0; // OK, no overlap
foo(5); // OK, no validation for methods
}
public void foo(int c) {
// overlapping by method argument
c = c; // violation, reference to instance variable "c" requires "this"
}
}
To configure the check for methods only:
<module name="RequireThis"> <property name="checkFields" value="false"/> </module>
Example:
public class Test {
private int a;
private int b;
private int c;
public Test(int a) {
// overlapping by constructor argument
this.a = a; // OK, no validation for fields
b = 0; // OK, no validation for fields
foo(5); // OK, no overlap
}
public void foo(int c) {
// overlapping by method argument
c = c; // OK, no validation for fields
}
}
Note that method call foo(5) does not raise a violation because methods cannot be overlapped in java.
To configure the check to validate for non-overlapping fields and methods:
<module name="RequireThis"> <property name="validateOnlyOverlapping" value="false"/> </module>
Example:
public class Test {
private int a;
private int b;
private int c;
public Test(int a) {
// overlapping by constructor argument
this.a = a; // OK, no validation for fields
b = 0; // violation, reference to instance variable "b" requires "this"
foo(5); // violation, method call "foo(5)" requires "this"
}
public void foo(int c) {
// overlapping by method argument
c = c; // violation, reference to instance variable "c" requires "this"
}
}
Please, be aware of the following logic, which is implemented in the check:
1) If you arrange 'this' in your code on your own, the check will not raise violation for variables which use 'this' to reference a class field, for example:
public class C {
private int scale;
private int x;
public void foo(int scale) {
scale = this.scale; // no violation
if (scale > 0) {
scale = -scale; // no violation
}
x *= scale;
}
}
2) If method parameter is returned from the method, the check will not raise violation for returned variable/parameter, for example:
public class D {
private String prefix;
public String modifyPrefix(String prefix) {
prefix = "^" + prefix + "$"; // no violation, because method parameter is returned
return prefix;
}
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
require.this.method
require.this.variable
| Modifier and Type | Class and Description |
|---|---|
private static class |
RequireThisCheck.AbstractFrame
A declaration frame.
|
private static class |
RequireThisCheck.AnonymousClassFrame
An anonymous class frame; holds instance variable names.
|
private static class |
RequireThisCheck.BlockFrame
A frame initiated on entering a statement list; holds local variable names.
|
private static class |
RequireThisCheck.CatchFrame
A frame initiated on entering a catch block; holds local catch variable names.
|
private static class |
RequireThisCheck.ClassFrame
A frame initiated at class, enum or interface definition; holds instance variable names.
|
private static class |
RequireThisCheck.ConstructorFrame
A frame initiated at constructor definition.
|
private static class |
RequireThisCheck.ForFrame
A frame initiated on entering a for block; holds local for variable names.
|
private static class |
RequireThisCheck.FrameType
An AbstractFrame type.
|
private static class |
RequireThisCheck.MethodFrame
A frame initiated at method definition; holds a method definition token.
|
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private static java.util.Set<java.lang.Integer> |
ASSIGN_TOKENS
Set of all assign tokens.
|
private boolean |
checkFields
Control whether to check references to fields.
|
private boolean |
checkMethods
Control whether to check references to methods.
|
private static java.util.Set<java.lang.Integer> |
COMPOUND_ASSIGN_TOKENS
Set of all compound assign tokens.
|
private java.util.Deque<RequireThisCheck.AbstractFrame> |
current
Frame for the currently processed AST.
|
private static java.util.Set<java.lang.Integer> |
DECLARATION_TOKENS
Set of all declaration tokens.
|
private java.util.Map<DetailAST,RequireThisCheck.AbstractFrame> |
frames
Tree of all the parsed frames.
|
static java.lang.String |
MSG_METHOD
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_VARIABLE
A key is pointing to the warning message text in "messages.properties"
file.
|
private boolean |
validateOnlyOverlapping
Control whether to check only overlapping by variables or arguments.
|
| Constructor and Description |
|---|
RequireThisCheck() |
| Modifier and Type | Method and Description |
|---|---|
void |
beginTree(DetailAST rootAST)
Called before the starting to process a tree.
|
private boolean |
canAssignValueToClassField(DetailAST ast)
Checks whether a value can be assigned to a field.
|
private boolean |
canBeReferencedFromStaticContext(DetailAST ident)
Checks whether a field can be referenced from a static context.
|
private static void |
collectDeclarations(java.util.Deque<RequireThisCheck.AbstractFrame> frameStack,
DetailAST ast)
Parses the next AST for declarations.
|
private static void |
collectVariableDeclarations(DetailAST ast,
RequireThisCheck.AbstractFrame frame)
Collects variable declarations.
|
private void |
endCollectingDeclarations(java.util.Queue<RequireThisCheck.AbstractFrame> frameStack,
DetailAST ast)
Ends parsing of the AST for declarations.
|
private RequireThisCheck.AbstractFrame |
findClassFrame(DetailAST name,
boolean lookForMethod)
Find the class frame containing declaration.
|
private RequireThisCheck.AbstractFrame |
findFrame(DetailAST name,
boolean lookForMethod)
Find frame containing declaration.
|
private static RequireThisCheck.AbstractFrame |
findFrame(RequireThisCheck.AbstractFrame frame,
DetailAST name,
boolean lookForMethod)
Find frame containing declaration.
|
int[] |
getAcceptableTokens()
The configurable token set.
|
private static java.util.Set<DetailAST> |
getAllTokensOfType(DetailAST ast,
int tokenType)
Collects all tokens of specific type starting with the current ast node.
|
private static java.util.Set<DetailAST> |
getAllTokensOfType(DetailAST ast,
int tokenType,
int endLineNumber)
Collects all tokens of specific type starting with the current ast node and which line
number is lower or equal to the end line number.
|
private static java.util.Set<DetailAST> |
getAllTokensWhichAreEqualToCurrent(DetailAST ast,
DetailAST token,
int endLineNumber)
Collects all tokens which are equal to current token starting with the current ast node and
which line number is lower or equal to the end line number.
|
private static DetailAST |
getBlockEndToken(DetailAST blockNameIdent,
DetailAST blockStartToken)
Returns the token which ends the code block.
|
private RequireThisCheck.AbstractFrame |
getClassFrameWhereViolationIsFound(DetailAST ast)
Returns the class frame where violation is found (where the field is used without 'this')
or null otherwise.
|
private static DetailAST |
getCodeBlockDefinitionToken(DetailAST ident)
Returns code block definition token for current identifier.
|
int[] |
getDefaultTokens()
Returns the default token a check is interested in.
|
private RequireThisCheck.AbstractFrame |
getFieldWithoutThis(DetailAST ast,
int parentType)
Returns the frame where the field is declared, if the given field is used without
'this', and null otherwise.
|
private RequireThisCheck.AbstractFrame |
getMethodWithoutThis(DetailAST ast)
Returns the frame where the method is declared, if the given method is used without
'this' and null otherwise.
|
private java.lang.String |
getNearestClassFrameName()
Gets the name of the nearest parent ClassFrame.
|
int[] |
getRequiredTokens()
The tokens that this check must be registered for.
|
private static boolean |
isAnonymousClassDef(DetailAST ast)
Whether the AST is a definition of an anonymous class.
|
private static boolean |
isAssignToken(int tokenType)
Check that token is related to assign tokens.
|
private static boolean |
isAstInside(DetailAST tree,
DetailAST ast)
Checks if the given
ast is equal to the tree or a child of it. |
private static boolean |
isAstSimilar(DetailAST left,
DetailAST right)
Checks if 2 AST are similar by their type and text.
|
private static boolean |
isCompoundAssignToken(int tokenType)
Check that token is related to compound assign tokens.
|
private static boolean |
isDeclarationToken(int parentType)
Check that token is related to Definition tokens.
|
private static boolean |
isInCompactConstructor(DetailAST ast)
Return whether ast is in a COMPACT_CTOR_DEF.
|
private static boolean |
isInExpression(DetailAST ast)
Checks ast parent is in expression.
|
private static boolean |
isInsideConstructorFrame(RequireThisCheck.AbstractFrame frame)
Checks whether a field usage frame is inside constructor frame.
|
private static boolean |
isLambdaParameter(DetailAST ast)
Checks if the token is a Lambda parameter.
|
private boolean |
isOverlappingByArgument(DetailAST ast)
Checks whether an overlapping by method or constructor argument takes place.
|
private boolean |
isOverlappingByLocalVariable(DetailAST ast)
Checks whether an overlapping by local variable takes place.
|
private static boolean |
isReturnedVariable(RequireThisCheck.AbstractFrame currentFrame,
DetailAST ident)
Checks whether the current variable is returned from the method.
|
private static boolean |
isUserDefinedArrangementOfThis(RequireThisCheck.AbstractFrame currentFrame,
DetailAST ident)
Checks whether user arranges 'this' for variable in method, constructor, or block on his own.
|
void |
leaveToken(DetailAST ast)
Called after all the child nodes have been process.
|
private void |
logViolation(java.lang.String msgKey,
DetailAST ast,
RequireThisCheck.AbstractFrame frame)
Helper method to log a Violation.
|
private void |
processIdent(DetailAST ast)
Checks if a given IDENT is method call or field name which
requires explicit
this qualifier. |
void |
setCheckFields(boolean checkFields)
Setter to control whether to check references to fields.
|
void |
setCheckMethods(boolean checkMethods)
Setter to control whether to check references to methods.
|
void |
setValidateOnlyOverlapping(boolean validateOnlyOverlapping)
Setter to control whether to check only overlapping by variables or arguments.
|
void |
visitToken(DetailAST ast)
Called to process a token.
|
clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final java.lang.String MSG_METHOD
public static final java.lang.String MSG_VARIABLE
private static final java.util.Set<java.lang.Integer> DECLARATION_TOKENS
private static final java.util.Set<java.lang.Integer> ASSIGN_TOKENS
private static final java.util.Set<java.lang.Integer> COMPOUND_ASSIGN_TOKENS
private final java.util.Deque<RequireThisCheck.AbstractFrame> current
private java.util.Map<DetailAST,RequireThisCheck.AbstractFrame> frames
private boolean checkFields
private boolean checkMethods
private boolean validateOnlyOverlapping
public RequireThisCheck()
public void setCheckFields(boolean checkFields)
checkFields - should we check fields usage or not.public void setCheckMethods(boolean checkMethods)
checkMethods - should we check methods usage or not.public void setValidateOnlyOverlapping(boolean validateOnlyOverlapping)
validateOnlyOverlapping - should we check only overlapping by variables or arguments.public int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic void beginTree(DetailAST rootAST)
AbstractCheckbeginTree in class AbstractCheckrootAST - the root of the treepublic void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processpublic void leaveToken(DetailAST ast)
AbstractCheckleaveToken in class AbstractCheckast - the token leavingprivate void processIdent(DetailAST ast)
this qualifier.ast - IDENT to check.private void logViolation(java.lang.String msgKey, DetailAST ast, RequireThisCheck.AbstractFrame frame)
msgKey - key to locale message format.ast - a node to get line id column numbers associated with the message.frame - the class frame where the violation is found.private RequireThisCheck.AbstractFrame getFieldWithoutThis(DetailAST ast, int parentType)
ast - field definition ast token.parentType - type of the parent.private static boolean isInCompactConstructor(DetailAST ast)
ast - The token to checkprivate static void collectDeclarations(java.util.Deque<RequireThisCheck.AbstractFrame> frameStack, DetailAST ast)
frameStack - stack containing the FrameTree being built.ast - AST to parse.private static void collectVariableDeclarations(DetailAST ast, RequireThisCheck.AbstractFrame frame)
ast - variable token.frame - current frame.private void endCollectingDeclarations(java.util.Queue<RequireThisCheck.AbstractFrame> frameStack, DetailAST ast)
frameStack - Stack containing the FrameTree being built.ast - AST that was parsed.private static boolean isAnonymousClassDef(DetailAST ast)
ast - the AST to process.private RequireThisCheck.AbstractFrame getClassFrameWhereViolationIsFound(DetailAST ast)
ast - IDENT ast to check.private static boolean isInExpression(DetailAST ast)
ast - token to checkprivate static boolean isUserDefinedArrangementOfThis(RequireThisCheck.AbstractFrame currentFrame, DetailAST ident)
currentFrame - current frame.ident - ident token.private static DetailAST getBlockEndToken(DetailAST blockNameIdent, DetailAST blockStartToken)
blockNameIdent - block name identifier.blockStartToken - token which starts the block.private static boolean isReturnedVariable(RequireThisCheck.AbstractFrame currentFrame, DetailAST ident)
currentFrame - current frame.ident - variable ident token.private static boolean isAstInside(DetailAST tree, DetailAST ast)
ast is equal to the tree or a child of it.tree - The tree to search.ast - The AST to look for.true if the ast was found.private boolean canBeReferencedFromStaticContext(DetailAST ident)
ident - ident token.private static DetailAST getCodeBlockDefinitionToken(DetailAST ident)
ident - ident token.private boolean canAssignValueToClassField(DetailAST ast)
ast - an identifier token.private static boolean isInsideConstructorFrame(RequireThisCheck.AbstractFrame frame)
frame - frame, where field is used.private boolean isOverlappingByArgument(DetailAST ast)
ast - an identifier.private boolean isOverlappingByLocalVariable(DetailAST ast)
ast - an identifier.private static java.util.Set<DetailAST> getAllTokensOfType(DetailAST ast, int tokenType)
ast - ast node.tokenType - token type.private static java.util.Set<DetailAST> getAllTokensOfType(DetailAST ast, int tokenType, int endLineNumber)
ast - ast node.tokenType - token type.endLineNumber - end line number.private static java.util.Set<DetailAST> getAllTokensWhichAreEqualToCurrent(DetailAST ast, DetailAST token, int endLineNumber)
ast - ast node.token - token.endLineNumber - end line number.private RequireThisCheck.AbstractFrame getMethodWithoutThis(DetailAST ast)
ast - the IDENT ast of the name to check.private RequireThisCheck.AbstractFrame findClassFrame(DetailAST name, boolean lookForMethod)
name - IDENT ast of the declaration to find.lookForMethod - whether we are looking for a method name.private RequireThisCheck.AbstractFrame findFrame(DetailAST name, boolean lookForMethod)
name - IDENT ast of the declaration to find.lookForMethod - whether we are looking for a method name.private static RequireThisCheck.AbstractFrame findFrame(RequireThisCheck.AbstractFrame frame, DetailAST name, boolean lookForMethod)
frame - The parent frame to searching in.name - IDENT ast of the declaration to find.lookForMethod - whether we are looking for a method name.private static boolean isDeclarationToken(int parentType)
parentType - token Type.private static boolean isAssignToken(int tokenType)
tokenType - token type.private static boolean isCompoundAssignToken(int tokenType)
tokenType - token type.private java.lang.String getNearestClassFrameName()
private static boolean isLambdaParameter(DetailAST ast)
ast - the DetailAST value of the token to be checkedprivate static boolean isAstSimilar(DetailAST left, DetailAST right)
left - The first AST to check.right - The second AST to check.true if they are similar.Copyright © 2001-2022. All Rights Reserved.