Skip to content

Commit

Permalink
Issue #598: Forbid field access check implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
yaziza committed Apr 14, 2020
1 parent bd5ca6b commit 76c9cd6
Show file tree
Hide file tree
Showing 13 changed files with 415 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ ForbidCertainMethodCheck.desc = Forbids certain method usage. <br/><br/>You can
ForbidCertainMethodCheck.methodName = Regex to match name of the forbidden method. When blank or unspecified, all the methods will be allowed.
ForbidCertainMethodCheck.argumentCount = Number or range to match number of arguments the forbidden method takes. Multiple ranges are separated by comma. When unspecified, only method name will be used for check.
ForbidFieldAccessCheck.name = Forbid certain field access
ForbidFieldAccessCheck.desc = <p>Checks that certain fields are not used. This can be used to enforce that fields like e.g. {@link java.util.Locale#ROOT} are not used.</p>
ForbidFieldAccessCheck.packageName = The field package name to be forbidden. (default 'java.util')
ForbidFieldAccessCheck.className = The field class name to be forbidden. (default 'Locale')
ForbidFieldAccessCheck.fieldName = The field name to be forbidden. (default 'ROOT')
ForbidInstantiationCheck.name = Forbid Instantiation
ForbidInstantiationCheck.desc = Forbids instantiation of certain object types by their full classname.<br><p>For example:<br>"java.lang.NullPointerException" will forbid the NPE instantiation.</p><p>Note: className should to be full: use "java.lang.NullPointerException" instead of "NullpointerException".</p>
ForbidInstantiationCheck.forbiddenClasses = ClassNames for objects that are forbidden to instantiate.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,22 @@
<message-key key="forbid.certain.method"/>
</rule-metadata>

<rule-metadata name="%ForbidFieldAccessCheck.name" internal-name="ForbidFieldAccessCheck" parent="TreeWalker">
<alternative-name internal-name="com.github.sevntu.checkstyle.checks.coding.ForbidFieldAccessCheck"/>
<description>%ForbidFieldAccessCheck.desc</description>
<property-metadata name="packageName" datatype="String" default-value="java.util">
<description>%ForbidFieldAccessCheck.packageName</description>
</property-metadata>
<property-metadata name="className" datatype="String" default-value="Locale">
<description>%ForbidFieldAccessCheck.className</description>
</property-metadata>
<property-metadata name="fieldName" datatype="String" default-value="ROOT">
<description>%ForbidFieldAccessCheck.fieldName</description>
</property-metadata>

<message-key key="forbid.field.access"/>
</rule-metadata>

<rule-metadata name="%ForbidInstantiationCheck.name" internal-name="ForbidInstantiationCheck" parent="TreeWalker">
<alternative-name internal-name="com.github.sevntu.checkstyle.checks.coding.ForbidInstantiationCheck"/>
<description>%ForbidInstantiationCheck.desc</description>
Expand Down
5 changes: 5 additions & 0 deletions sevntu-checks/sevntu-checks.xml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@
<property name="methodName" value="assert(True|False)"/>
<property name="argumentCount" value="1"/>
</module>
<module name="com.github.sevntu.checkstyle.checks.coding.ForbidFieldAccessCheck">
<property name="packageName" value="java.util"/>
<property name="className" value="Locale"/>
<property name="fieldName" value="ROOT"/>
</module>
<module name="com.github.sevntu.checkstyle.checks.coding.OverridableMethodInConstructorCheck">
<property name="checkCloneMethod" value="false"/>
<property name="checkReadObjectMethod" value="false"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.TokenUtil;

/**
Expand Down Expand Up @@ -76,4 +78,30 @@ public static DetailAST getNextSubTreeNode(DetailAST node, DetailAST subTreeRoot
return toVisitAst;
}

/**
* Gets package/import text representation from node of PACKAGE_DEF or IMPORT type.
* @param packageDefOrImportNode
* - DetailAST node is pointing to package or import definition
* (should be a PACKAGE_DEF or IMPORT type).
* @return The fully qualified name of package or import without
* "package"/"import" words or semicolons.
*/
public static String getText(DetailAST packageDefOrImportNode) {
String result = null;

final DetailAST identNode = packageDefOrImportNode.findFirstToken(TokenTypes.IDENT);

if (identNode == null) {
final DetailAST parentDotAST = packageDefOrImportNode.findFirstToken(TokenTypes.DOT);
final FullIdent dottedPathIdent = FullIdent
.createFullIdentBelow(parentDotAST);
final DetailAST nameAST = parentDotAST.getLastChild();
result = dottedPathIdent.getText() + "." + nameAST.getText();
}
else {
result = identNode.getText();
}
return result;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import com.github.sevntu.checkstyle.SevntuUtil;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;

/**
Expand Down Expand Up @@ -160,20 +159,20 @@ public void visitToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.PACKAGE_DEF:
if (packageNamesRegexp != null) {
final String packageQualifiedName = getText(ast);
final String packageQualifiedName = SevntuUtil.getText(ast);
packageMatches = packageNamesRegexp.matcher(packageQualifiedName)
.matches();
}
break;
case TokenTypes.IMPORT:
final String importQualifiedText = getText(ast);
final String importQualifiedText = SevntuUtil.getText(ast);
if (isImportForbidden(importQualifiedText)) {
log(ast, importQualifiedText);
}
break;
case TokenTypes.LITERAL_NEW:
if (ast.findFirstToken(TokenTypes.DOT) != null) {
final String classQualifiedText = getText(ast);
final String classQualifiedText = SevntuUtil.getText(ast);
if (isImportForbidden(classQualifiedText)) {
log(ast, classQualifiedText);
}
Expand Down Expand Up @@ -211,30 +210,4 @@ private void log(DetailAST nodeToWarn, String importText) {
getForbiddenImportRegexp(), importText);
}

/**
* Gets package/import text representation from node of PACKAGE_DEF or IMPORT type.
* @param packageDefOrImportNode
* - DetailAST node is pointing to package or import definition
* (should be a PACKAGE_DEF or IMPORT type).
* @return The fully qualified name of package or import without
* "package"/"import" words or semicolons.
*/
private static String getText(DetailAST packageDefOrImportNode) {
String result = null;

final DetailAST identNode = packageDefOrImportNode.findFirstToken(TokenTypes.IDENT);

if (identNode == null) {
final DetailAST parentDotAST = packageDefOrImportNode.findFirstToken(TokenTypes.DOT);
final FullIdent dottedPathIdent = FullIdent
.createFullIdentBelow(parentDotAST);
final DetailAST nameAST = parentDotAST.getLastChild();
result = dottedPathIdent.getText() + "." + nameAST.getText();
}
else {
result = identNode.getText();
}
return result;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2020 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////

package com.github.sevntu.checkstyle.checks.coding;

import com.github.sevntu.checkstyle.SevntuUtil;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;

/**
* <p>
* Checks that certain fields are not used. This can be used to enforce that fields like e.g.
* {@link java.util.Locale#ROOT}.
* </p>
*
* <p>
* Parameters are:
* </p>
*
* <ul>
* <li><b>packageName</b> - The field package name to be forbidden.</li>
* <li><b>className</b> - The field class name to be forbidden.</li>
* <li><b>fieldName</b> - The field name to be forbidden.</li>
* </ul>
*
* <p>
* Together, these three parameters forms the field fully qualified name.
* </p>
*
* <p>
* Default parameters are:
* </p>
*
* <ul>
* <li><b>packageName</b>java.util</li>
* <li><b>className</b>Locale</li>
* <li><b>fieldName</b>ROOT</li>
* </ul>
*
* <p>
* which forbids the usage of {@link java.util.Locale#ROOT}.
* </p>
*
* @author <a href="mailto:[email protected]">Yasser Aziza</a>
* @since 1.38.0
*/
public class ForbidFieldAccessCheck extends AbstractCheck {

/**
* Warning message key.
*/
public static final String MSG_KEY = "forbid.field.access";

/**
* '.' character used as separator between FQN elements.
*/
private static final char DOT = '.';

/**
* Package name.
*/
private String packageName = "java.util";

/**
* Class name.
*/
private String className = "Locale";

/**
* Field name.
*/
private String fieldName = "ROOT";

/**
* Whether the field class was imported.
*/
private boolean wasPackageImported;

/**
* Sets the package name, in which the field is declared.
* @param packageName the field name
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}

/**
* Sets the class name, which declares the field.
* @param className the class name
*/
public void setClassName(String className) {
this.className = className;
}

/**
* Sets the Field name, which should be forbidden to use.
* @param fieldName the field name
*/
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}

/**
* Gets the field fully qualified name.
* @return {@link String} containing the field FQN
*/
private String getFieldFullyQualifiedName() {
return packageName + DOT + className + DOT + fieldName;
}

@Override
public int[] getDefaultTokens() {
return new int[] {
TokenTypes.STATIC_IMPORT,
TokenTypes.IMPORT,
TokenTypes.IDENT,
};
}

@Override
public int[] getAcceptableTokens() {
return getDefaultTokens();
}

@Override
public int[] getRequiredTokens() {
return getDefaultTokens();
}

@Override
public void visitToken(DetailAST ast) {
if (isStaticImported(ast)) {
log(ast, MSG_KEY, getFieldFullyQualifiedName());
}
else if (isPackageImported(ast)) {
// Mark forbidden field package as imported
wasPackageImported = true;
}
else if (wasPackageImported && TokenTypes.IDENT == ast.getType() && isSameType(ast)) {
log(ast.getPreviousSibling(), MSG_KEY, getFieldFullyQualifiedName());
}
}

/**
* Checks whether the field is static imported.
*
* @param ast the {@link TokenTypes#STATIC_IMPORT} node to be checked
* @return {@code true} if the field was static imported, {@code false} otherwise
*/
private boolean isStaticImported(DetailAST ast) {
return TokenTypes.STATIC_IMPORT == ast.getType()
&& getFieldFullyQualifiedName().equals(SevntuUtil.getText(ast));
}

/**
* Checks whether the field package is imported.
*
* @param ast the {@link TokenTypes#IMPORT} node to be checked
* @return {@code true} if the field was imported, {@code false} otherwise
*/
private boolean isPackageImported(DetailAST ast) {
final String importName = packageName + DOT + className;

return TokenTypes.IMPORT == ast.getType()
&& importName.equals(FullIdent.createFullIdentBelow(ast).getText());
}

/**
* Checks if the given {@link TokenTypes#IDENT} node has the same type as the forbidden field.
*
* @param ast the {@link TokenTypes#IDENT} node to be checked
* @return {@code true} if the field has the same FQN, {@code false} otherwise
*/
private boolean isSameType(DetailAST ast) {
return fieldName.equals(ast.getText())
&& ast.getPreviousSibling() != null
&& className.equals(ast.getPreviousSibling().getText());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ finalize.implementation.useless=finalize() method is useless: it does nothing ex
forbid.c.comments.in.the.method.body=C-style comments (/*...*/) inside method body are not allowed.
forbid.certain.imports=Import ''{1}'' should not match ''{0}'' pattern, it is forbidden.
forbid.certain.method=Call to ''{0}'' method (matches pattern ''{1}'') with ''{2}'' arguments (matches pattern ''{3}'') is forbidden.
forbid.field.access=Field access of type ''{0}'' is forbidden
forbid.instantiation=Instantiation of ''{0}'' is not allowed.
forbid.return.in.finally.block=Finally block should not contain return statements.
forbid.throw.anonymous.exception=Avoid throwing anonymous exception.
Expand Down
Loading

0 comments on commit 76c9cd6

Please sign in to comment.