Skip to content

Commit

Permalink
Issue checkstyle#14726: new check: ConstructorsDeclarationGroupingCheck
Browse files Browse the repository at this point in the history
  • Loading branch information
Zopsss committed Apr 14, 2024
1 parent 86195e0 commit 5c4be0c
Show file tree
Hide file tree
Showing 31 changed files with 716 additions and 3 deletions.
1 change: 1 addition & 0 deletions config/checkstyle-checks.xml
Expand Up @@ -539,6 +539,7 @@
<module name="NoFinalizer"/>
<module name="OneStatementPerLine"/>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="ConstructorsDeclarationGrouping"/>
<module name="PackageDeclaration"/>
<module name="ParameterAssignment"/>
<module name="RequireThis"/>
Expand Down
2 changes: 2 additions & 0 deletions config/checkstyle-non-main-files-suppressions.xml
Expand Up @@ -234,6 +234,8 @@
files="src[\\/]xdocs[\\/]checks[\\/]coding[\\/]nofinalizer.xml.template"/>
<suppress id="propertiesMacroMustExist"
files="src[\\/]xdocs[\\/]checks[\\/]coding[\\/]overloadmethodsdeclarationorder.xml.template"/>
<suppress id="propertiesMacroMustExist"
files="src[\\/]xdocs[\\/]checks[\\/]coding[\\/]constructorsdeclarationgrouping.xml.template"/>
<suppress id="propertiesMacroMustExist"
files="src[\\/]xdocs[\\/]checks[\\/]coding[\\/]parameterassignment.xml.template"/>
<suppress id="propertiesMacroMustExist"
Expand Down
1 change: 1 addition & 0 deletions config/jsoref-spellchecker/whitelist.words
Expand Up @@ -239,6 +239,7 @@ config
configurationloader
Connell's
constantname
constructorsdeclarationgrouping
Contextualizable
contextualization
contextualized
Expand Down
2 changes: 2 additions & 0 deletions config/linkcheck-suppressions.txt
Expand Up @@ -223,6 +223,7 @@
<a href="apidocs/com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.html#%3Cinit%3E()">#%3Cinit%3E()</a>: doesn't exist.
<a href="apidocs/com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsCheck.html#%3Cinit%3E()">#%3Cinit%3E()</a>: doesn't exist.
<a href="apidocs/com/puppycrawl/tools/checkstyle/checks/coding/AvoidNoArgumentSuperConstructorCallCheck.html#%3Cinit%3E()">#%3Cinit%3E()</a>: doesn't exist.
<a href="apidocs/com/puppycrawl/tools/checkstyle/checks/coding/ConstructorsDeclarationGroupingCheck.html#%3Cinit%3E()">#%3Cinit%3E()</a>: doesn't exist.
<a href="apidocs/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.html#%3Cinit%3E()">#%3Cinit%3E()</a>: doesn't exist.
<a href="apidocs/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.ScopeState.html#%3Cinit%3E()">#%3Cinit%3E()</a>: doesn't exist.
<a href="apidocs/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.html#%3Cinit%3E()">#%3Cinit%3E()</a>: doesn't exist.
Expand Down Expand Up @@ -949,6 +950,7 @@
<a href="com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.html#%3Cinit%3E()">com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.html#%3Cinit%3E()</a>: doesn't exist.
<a href="com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsCheck.html#%3Cinit%3E()">com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsCheck.html#%3Cinit%3E()</a>: doesn't exist.
<a href="com/puppycrawl/tools/checkstyle/checks/coding/AvoidNoArgumentSuperConstructorCallCheck.html#%3Cinit%3E()">com/puppycrawl/tools/checkstyle/checks/coding/AvoidNoArgumentSuperConstructorCallCheck.html#%3Cinit%3E()</a>: doesn't exist.
<a href="com/puppycrawl/tools/checkstyle/checks/coding/ConstructorsDeclarationGroupingCheck.html#%3Cinit%3E()">com/puppycrawl/tools/checkstyle/checks/coding/ConstructorsDeclarationGroupingCheck.html#%3Cinit%3E()</a>: doesn't exist.
<a href="com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.html#%3Cinit%3E()">com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.html#%3Cinit%3E()</a>: doesn't exist.
<a href="com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.ScopeState.html#%3Cinit%3E()">com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.ScopeState.html#%3Cinit%3E()</a>: doesn't exist.
<a href="com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.html#%3Cinit%3E()">com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.html#%3Cinit%3E()</a>: doesn't exist.
Expand Down
2 changes: 2 additions & 0 deletions pom.xml
Expand Up @@ -3264,6 +3264,7 @@
<param>com.puppycrawl.tools.checkstyle.checks.coding.AvoidDoubleBraceInitializationCheck*</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.AvoidInlineConditionalsCheck*</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.AvoidNoArgumentSuperConstructorCallCheck*</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.ConstructorsDeclarationGroupingCheck*</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.CovariantEqualsCheck*</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheck*</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.DefaultComesLastCheck*</param>
Expand All @@ -3288,6 +3289,7 @@
<param>com.puppycrawl.tools.checkstyle.checks.coding.AvoidDoubleBraceInitializationCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.AvoidInlineConditionalsCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.AvoidNoArgumentSuperConstructorCallCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.ConstructorsDeclarationGroupingCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.CovariantEqualsCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.coding.DefaultComesLastCheckTest</param>
Expand Down
@@ -0,0 +1,105 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
// Copyright (C) 2001-2024 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 org.checkstyle.suppressionxpathfilter;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.junit.jupiter.api.Test;

import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.checks.coding.ConstructorsDeclarationGroupingCheck;

public class XpathRegressionConstructorsDeclarationGroupingTest extends AbstractXpathTestSupport {

private final Class<ConstructorsDeclarationGroupingCheck> clazz =
ConstructorsDeclarationGroupingCheck.class;

@Override
protected String getCheckName() {
return clazz.getSimpleName();
}

@Test
public void testOne() throws Exception {
final File fileToProcess = new File(
getPath("InputXpathConstructorsDeclarationGroupingClass.java"));

final DefaultConfiguration moduleConfig = createModuleConfig(clazz);

final String[] expectedViolation = {
"10:5: " + getCheckMessage(clazz,
ConstructorsDeclarationGroupingCheck.MSG_KEY, 6),
};

final List<String> expectedXpathQueries = Arrays.asList(
"/COMPILATION_UNIT/CLASS_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingClass']]"
+ "/OBJBLOCK/CTOR_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingClass']]",
"/COMPILATION_UNIT/CLASS_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingClass']]"
+ "/OBJBLOCK/CTOR_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingClass']]"
+ "/MODIFIERS",
"/COMPILATION_UNIT/CLASS_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingClass']]"
+ "/OBJBLOCK/CTOR_DEF/IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingClass']"

);

runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries);
}

@Test
public void testTwo() throws Exception {
final File fileToProcess = new File(
getPath("InputXpathConstructorsDeclarationGroupingEnum.java"));

final DefaultConfiguration moduleConfig = createModuleConfig(clazz);

final String[] expectedViolation = {
"12:5: " + getCheckMessage(clazz,
ConstructorsDeclarationGroupingCheck.MSG_KEY, 8),
};

final List<String> expectedXpathQueries = Arrays.asList(
"/COMPILATION_UNIT/ENUM_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingEnum']]"
+ "/OBJBLOCK/CTOR_DEF"
+ "[./IDENT[@text='InputXpathConstructorsDeclarationGroupingEnum']]",

"/COMPILATION_UNIT/ENUM_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingEnum']]"
+ "/OBJBLOCK/CTOR_DEF"
+ "[./IDENT[@text='InputXpathConstructorsDeclarationGroupingEnum']]"
+ "/MODIFIERS",

"/COMPILATION_UNIT/ENUM_DEF[./IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingEnum']]"
+ "/OBJBLOCK/CTOR_DEF/IDENT"
+ "[@text='InputXpathConstructorsDeclarationGroupingEnum']"
);

runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries);
}
}
@@ -0,0 +1,11 @@
package org.checkstyle.suppressionxpathfilter.constructorsdeclarationgrouping;

public class InputXpathConstructorsDeclarationGroupingClass {
InputXpathConstructorsDeclarationGroupingClass() {}

InputXpathConstructorsDeclarationGroupingClass(int a) {}

int x;

InputXpathConstructorsDeclarationGroupingClass(String str) {} // warn
}
@@ -0,0 +1,13 @@
package org.checkstyle.suppressionxpathfilter.constructorsdeclarationgrouping;

public enum InputXpathConstructorsDeclarationGroupingEnum {
ONE;

InputXpathConstructorsDeclarationGroupingEnum() {}

InputXpathConstructorsDeclarationGroupingEnum(String str) {}

int f;

InputXpathConstructorsDeclarationGroupingEnum(int x) {} // warn
}
Expand Up @@ -557,6 +557,8 @@ private static void fillChecksFromCodingPackage() {
BASE_PACKAGE + ".checks.coding.OneStatementPerLineCheck");
NAME_TO_FULL_MODULE_NAME.put("OverloadMethodsDeclarationOrderCheck",
BASE_PACKAGE + ".checks.coding.OverloadMethodsDeclarationOrderCheck");
NAME_TO_FULL_MODULE_NAME.put("ConstructorsDeclarationGroupingCheck",
BASE_PACKAGE + ".checks.coding.ConstructorsDeclarationGroupingCheck");
NAME_TO_FULL_MODULE_NAME.put("PackageDeclarationCheck",
BASE_PACKAGE + ".checks.coding.PackageDeclarationCheck");
NAME_TO_FULL_MODULE_NAME.put("ParameterAssignmentCheck",
Expand Down
@@ -0,0 +1,109 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
// Copyright (C) 2001-2024 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.puppycrawl.tools.checkstyle.checks.coding;

import java.util.HashMap;
import java.util.Map;

import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;

/**
* <p>
* Checks that all constructors are grouped together.
* If there is anything between overloaded constructors ( expect comments )
* then this check will give an error.
* </p>
* <p>
* Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
* </p>
* <p>
* Violation Message Keys:
* </p>
* <ul>
* <li>
* {@code constructors.declaration.grouping}
* </li>
* </ul>
*
* @since 10.16.0
*/

@FileStatefulCheck
public class ConstructorsDeclarationGroupingCheck extends AbstractCheck {

/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "constructors.declaration.grouping";

/**
* Specifies different Object Blocks scope.
*/
private final Map<DetailAST, Integer> allObjBlocks = new HashMap<>();

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

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

@Override
public int[] getRequiredTokens() {
return new int[] {
TokenTypes.CTOR_DEF,
TokenTypes.COMPACT_CTOR_DEF,
};
}

@Override
public void beginTree(DetailAST rootAst) {
allObjBlocks.clear();
}

@Override
public void visitToken(DetailAST ast) {
final DetailAST currObjBlock = ast.getParent();
final Integer previousCtorLineNo = allObjBlocks.get(currObjBlock);

if (previousCtorLineNo != null) {
final DetailAST previousSibling = ast.getPreviousSibling();
final int siblingType = previousSibling.getType();
final boolean isCtor = siblingType == TokenTypes.CTOR_DEF;
final boolean isCompactCtor = siblingType == TokenTypes.COMPACT_CTOR_DEF;

if (!isCtor && !isCompactCtor) {
log(ast, MSG_KEY, previousCtorLineNo);
}

allObjBlocks.put(currObjBlock, ast.getLineNo());
}
else {
allObjBlocks.put(currObjBlock, ast.getLineNo());
}
}
}
Expand Up @@ -3,6 +3,7 @@ assignment.inner.avoid=Inner assignments should be avoided.
avoid.clone.method=Avoid using clone method.
avoid.double.brace.init=Avoid double brace initialization.
avoid.finalizer.method=Avoid using finalizer method.
constructors.declaration.grouping=All overloaded constructors should be grouped together. Previous constructor was at line number ''{0}''.
covariant.equals=covariant equals without overriding equals(java.lang.Object).
declaration.order.access=Variable access definition in wrong order.
declaration.order.constructor=Constructor definition in wrong order.
Expand Down
Expand Up @@ -3,6 +3,7 @@ assignment.inner.avoid=Innere Zuweisungen sollten vermieden werden.
avoid.clone.method=Die Methode clone() sollte vermieden werden.
avoid.double.brace.init=Vermeiden Sie doppelte geschweifte Klammern.
avoid.finalizer.method=Die Methode finalize() sollte vermieden werden.
constructors.declaration.grouping=Alle überladenen Konstruktoren sollten gruppiert werden. Der vorherige Konstruktor befand sich in der Zeilennummer „{0}“.
covariant.equals=Kovariante Definition von equals(), ohne equals(java.lang.Object) zu überschreiben.
declaration.order.access=Fehlerhafte Deklarationsreihenfolge für diesen Scope.
declaration.order.constructor=Der Konstruktor steht an der falschen Stelle.
Expand Down
Expand Up @@ -3,6 +3,7 @@ assignment.inner.avoid=Deben evitarse las asignaciones internas.
avoid.clone.method=Evite el uso de método clone.
avoid.double.brace.init=Evite la inicialización de llaves dobles.
avoid.finalizer.method=Evite el uso de método de finalizador.
constructors.declaration.grouping=Todos los constructores sobrecargados deben agruparse. El constructor anterior estaba en la línea número ''{0}''.
covariant.equals=equals covariante sin sobrescribir equals(java.lang.Object).
declaration.order.access=Definición de acceso a variable en orden incorrecto.
declaration.order.constructor=Definición de constructor en orden incorrecto.
Expand Down
Expand Up @@ -3,6 +3,7 @@ assignment.inner.avoid=Älä käytä sisäkkäisiä sijoituksia.
avoid.clone.method=Vältä klooni menetelmää.
avoid.double.brace.init=Vältä kaksinkertaista ahdintuen alustamista.
avoid.finalizer.method=Vältä Finalizer menetelmää.
constructors.declaration.grouping=Kaikki ylikuormitetut rakentajat tulee ryhmitellä yhteen. Edellinen rakentaja oli rivillä ''{0}''.
covariant.equals=covariant vastaa ilman painavaa tasavertaisten (java.lang.Object).
declaration.order.access=Muuttuja pääsy määritelmä väärässä järjestyksessä.
declaration.order.constructor=Rakentaja määritelmä väärässä järjestyksessä.
Expand Down
Expand Up @@ -3,6 +3,7 @@ assignment.inner.avoid=Évitez d''affecter une valeur à une variable au sein d'
avoid.clone.method=Évitez d''utiliser la méthode de clonage.
avoid.double.brace.init=Évitez l''initialisation à double accolade.
avoid.finalizer.method=Évitez d''utiliser la méthode de finalisation.
constructors.declaration.grouping=Tous les constructeurs surchargés doivent être regroupés. Le constructeur précédent se trouvait au numéro de ligne « {0} ».
covariant.equals=Votre méthode equals compare uniquement les objets de votre classe. N''oubliez pas de surcharger la méthode equals(java.lang.Object).
declaration.order.access=La définition des variables n''est pas triée suivant leur portée.
declaration.order.constructor=La définition des constructeurs n''apparaît pas dans le bon ordre.
Expand Down
Expand Up @@ -3,6 +3,7 @@ assignment.inner.avoid=式内部での代入は避けるべきです。
avoid.clone.method=cloneメソッドを使用しないでください。
avoid.double.brace.init=二重中括弧を使った初期化は使用しないでください。
avoid.finalizer.method=ファイナライザメソッドを使用しないでください。
constructors.declaration.grouping=オーバーロードされたコンストラクターはすべてグループ化する必要があります。前のコンストラクターは行番号 ''{0}'' にありました。
covariant.equals=equals(java.lang.Object) をオーバーライドせずに共変 な equals を定義しています。
declaration.order.access=変数アクセスの定義順序が間違っています。
declaration.order.constructor=コンストラクタの定義順序が間違っています。
Expand Down
Expand Up @@ -3,6 +3,7 @@ assignment.inner.avoid=Atribuições aninhadas devem ser evitadas.
avoid.clone.method=Evite o uso do método ''clone()''.
avoid.double.brace.init=Evite a inicialização entre chaves.
avoid.finalizer.method=Evite o uso do método ''finalize()''.
constructors.declaration.grouping=Todos os construtores sobrecarregados devem ser agrupados. O construtor anterior estava no número de linha ''{0}''.
covariant.equals="equals" covariante sem sobrescrever ''equals(java.lang.Object)''.
declaration.order.access=Definição de acesso a variável em ordem errada.
declaration.order.constructor=Definição de construtor em ordem errada.
Expand Down

0 comments on commit 5c4be0c

Please sign in to comment.