Class UnusedTryResourceShouldBeUnnamedCheck
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.UnusedTryResourceShouldBeUnnamedCheck
- All Implemented Interfaces:
Configurable,Contextualizable
Ensures that try-with-resources resource variables that are not used
are declared as an unnamed variable.
Rationale:
- Improves code readability by clearly indicating which resources are unused.
-
Follows Java conventions for denoting unused variables with an underscore
(
_).
Only declared resources inside the try-with-resources parentheses are checked
(i.e. var a = lock() or AutoCloseable a = lock()).
Resources that are referenced but not declared inside the try
(e.g. try (releaser) { }) are never flagged, because those resources
cannot be replaced with _.
See the Java Language Specification for more information about unnamed variables.
Attention: This check should be activated only on source code that is compiled by jdk21 or higher; unnamed variables came out as a preview feature in Java 21 and became a standard part of the language in Java 22.
- Since:
- 13.5.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final classMaintains tracking information about a single try-with-resources resource.Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final int[]Parent token types for anTokenTypes.IDENTthat indicate the identifier is not a plain variable reference and should therefore be excluded from "used" detection.static final StringA key pointing to the warning message text in "messages.properties" file.private final Deque<Deque<UnusedTryResourceShouldBeUnnamedCheck.TryResourceDetails>> A stack of per-try resource-detail lists.private static final StringThe unnamed variable identifier introduced in Java 21. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidCalled before the starting to process a tree.private static Deque<UnusedTryResourceShouldBeUnnamedCheck.TryResourceDetails> collectTrackedResources(DetailAST tryAst) Collects all tracked resources from theRESOURCE_SPECIFICATIONof a try-with-resources statement.int[]The configurable token set.int[]Returns the default token a check is interested in.int[]The tokens that this check must be registered for.private static booleanisObjectReferenceInDot(DetailAST identAst) ReturnstruewhenidentAstis the first child of aTokenTypes.DOTnode, meaning it is the object reference in an expression such asa.close()— a genuine use of the variable.private static booleanisResourceDeclarationIdent(DetailAST identAst) ReturnstruewhenidentAstis the variable-name token inside aTokenTypes.RESOURCEnode (i.e. the declaration site, not a use).private static booleanisResourceUsageCandidate(DetailAST identAst) Determines whether anTokenTypes.IDENTtoken is a candidate for being a use of a tracked try resource.private static booleanisShadowedByCatchParameter(DetailAST identAst) ReturnstruewhenidentAstis shadowed by a catch parameter of an immediately enclosingTokenTypes.LITERAL_CATCHblock.voidleaveToken(DetailAST ast) Called after all the child nodes have been process.voidvisitToken(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, log, log, log, setFileContents, setTabWidth, setTokensMethods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityMethods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_UNUSED_TRY_RESOURCE
A key pointing to the warning message text in "messages.properties" file.- See Also:
-
UNNAMED_VARIABLE_IDENTIFIER
The unnamed variable identifier introduced in Java 21.- See Also:
-
INVALID_RESOURCE_IDENT_PARENTS
Parent token types for anTokenTypes.IDENTthat indicate the identifier is not a plain variable reference and should therefore be excluded from "used" detection. -
tryResources
A stack of per-try resource-detail lists.
-
-
Constructor Details
-
UnusedTryResourceShouldBeUnnamedCheck
-
-
Method Details
-
getDefaultTokens
Description copied from class:AbstractCheckReturns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokensin classAbstractCheck- Returns:
- the default tokens
- See Also:
-
getAcceptableTokens
Description copied from class:AbstractCheckThe 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:
getAcceptableTokensin classAbstractCheck- Returns:
- the token set this check is designed for.
- See Also:
-
getRequiredTokens
Description copied from class:AbstractCheckThe tokens that this check must be registered for.- Specified by:
getRequiredTokensin classAbstractCheck- Returns:
- the token set this must be registered for.
- See Also:
-
beginTree
Description copied from class:AbstractCheckCalled before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTreein classAbstractCheck- Parameters:
rootAST- the root of the tree
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
leaveToken
Description copied from class:AbstractCheckCalled after all the child nodes have been process.- Overrides:
leaveTokenin classAbstractCheck- Parameters:
ast- the token leaving
-
collectTrackedResources
private static Deque<UnusedTryResourceShouldBeUnnamedCheck.TryResourceDetails> collectTrackedResources(DetailAST tryAst) Collects all tracked resources from theRESOURCE_SPECIFICATIONof a try-with-resources statement.- Parameters:
tryAst- theTokenTypes.LITERAL_TRYtoken- Returns:
- a deque of
UnusedTryResourceShouldBeUnnamedCheck.TryResourceDetailsfor trackable resources; nevernull, but may be empty for plain try statements
-
isResourceUsageCandidate
Determines whether anTokenTypes.IDENTtoken is a candidate for being a use of a tracked try resource.- Parameters:
identAst- theTokenTypes.IDENTtoken to inspect- Returns:
trueif the token could represent a reference to a resource variable
-
isShadowedByCatchParameter
ReturnstruewhenidentAstis shadowed by a catch parameter of an immediately enclosingTokenTypes.LITERAL_CATCHblock.- Parameters:
identAst- theTokenTypes.IDENTtoken to inspect- Returns:
trueif a catch parameter with the same name is in scope
-
isResourceDeclarationIdent
ReturnstruewhenidentAstis the variable-name token inside aTokenTypes.RESOURCEnode (i.e. the declaration site, not a use).- Parameters:
identAst- theTokenTypes.IDENTtoken- Returns:
trueif this IDENT is the name in a resource declaration/reference
-
isObjectReferenceInDot
ReturnstruewhenidentAstis the first child of aTokenTypes.DOTnode, meaning it is the object reference in an expression such asa.close()— a genuine use of the variable.- Parameters:
identAst- theTokenTypes.IDENTtoken- Returns:
trueif the IDENT is the left-hand operand of a dot expression
-