Skip to content

Commit

Permalink
Issue #14765: fix OverloadMethodsDeclarationOrderCheck
Browse files Browse the repository at this point in the history
  • Loading branch information
Zopsss authored and nrmancuso committed Apr 28, 2024
1 parent 5b05fff commit 4096711
Show file tree
Hide file tree
Showing 16 changed files with 66 additions and 15 deletions.
Expand Up @@ -110,7 +110,11 @@ private void checkOverloadMethodsGrouping(DetailAST objectBlock) {
final String methodName =
currentToken.findFirstToken(TokenTypes.IDENT).getText();
final Integer previousIndex = methodIndexMap.get(methodName);
if (previousIndex != null && currentIndex - previousIndex > allowedDistance) {
final DetailAST previousSibling = currentToken.getPreviousSibling();
final boolean isMethod = previousSibling.getType() == TokenTypes.METHOD_DEF;

if (previousIndex != null
&& (!isMethod || currentIndex - previousIndex > allowedDistance)) {
final int previousLineWithOverloadMethod =
methodLineNumberMap.get(methodName);
log(currentToken, MSG_KEY,
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=Nested if-else depth is {0,number,integer} (max allowed is {1,nu
nested.try.depth=Nested try depth is {0,number,integer} (max allowed is {1,number,integer}).
no.array.trailing.comma=Array should not contain trailing comma.
no.enum.trailing.comma=Enum should not contain trailing comma.
overload.methods.declaration=All overloaded methods should be placed next to each other. Placing non-overloaded methods in between overloaded methods with the same type is a violation. Previous overloaded method located at line ''{0}''.
overload.methods.declaration=All overloaded methods should be placed next to each other. Previous overloaded method located at line ''{0}''.
parameter.assignment=Assignment of parameter ''{0}'' is not allowed.
require.this.method=Method call to ''{0}'' needs \"{1}this.\".
require.this.variable=Reference to instance variable ''{0}'' needs \"{1}this.\".
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=La profundidad de if-else anidados es {0,number,integer} (máxim
nested.try.depth=La profundidad de try anidados es {0,number,integer} (máximo permitido es {1,number,integer}).
no.array.trailing.comma=La matriz no debe contener una coma final.
no.enum.trailing.comma=Enum no debe contener una coma final.
overload.methods.declaration=Todos los métodos sobrecargados deben colocarse uno al lado del otro. Colocar métodos no sobrecargados entre métodos sobrecargados con el mismo tipo es una violación. Método sobrecargado anterior ubicado en la línea ''{0} ''.
overload.methods.declaration=Todos los métodos sobrecargados deben colocarse uno al lado del otro. Método sobrecargado anterior ubicado en la línea ''{0}''.
parameter.assignment=No esta permitida la asignación del parámetro ''{0}''.
require.this.method=La llamada al método ''{0}'' necesita "{1}this.".
require.this.variable=La referencia a la variable de instancia ''{0}'' necesita "{1}this.".
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=Sisäkkäisten if-else -lausekkeiden syvyys on {0,number,integer
nested.try.depth=Sisäkkäisten try -lausekkeiden syvyys on {0,number,integer} (suurin sallittu on {1,number,integer}).
no.array.trailing.comma=Matriisissa ei tulisi olla takaosan pilkkua.
no.enum.trailing.comma=Enum ei saisi sisältää takaosan pilkkua.
overload.methods.declaration=Kaikki ylikuormitetut menetelmät tulisi asettaa vierekkäin. Ei-ylikuormitettujen menetelmien sijoittaminen samantyyppisiin ylikuormitettuihin menetelmiin on rikkomus. Aikaisempi ylikuormitettu menetelmä sijaitsee rivillä '' {0} ''.
overload.methods.declaration=Kaikki ylikuormitetut menetelmät tulee sijoittaa vierekkäin. Edellinen ylikuormitettu menetelmä sijaitsee rivillä ''{0}''.
parameter.assignment=Tehtävä parametrin ''{0}'' ei ole sallittu.
require.this.method=Menetelmä kehotus ''{0}'' tarvitsee "{1}this.".
require.this.variable=Viittaus Esimerkiksi muuttuja ''{0}'' tarvitsee "{1}this.".
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=Le nombre de ''if'' imbriqués est de {0,number,integer}, alors
nested.try.depth=Le nombre de ''try'' imbriqués est de {0,number,integer}, alors que le maximum autorisé est de {1,number,integer}.
no.array.trailing.comma=Le tableau ne doit pas contenir de virgule.
no.enum.trailing.comma=Enum ne doit pas contenir de virgule.
overload.methods.declaration=Toutes les méthodes surchargées doivent être placées côte à côte. Placer des méthodes non surchargées entre des méthodes surchargées avec le même type est une violation. La méthode surchargée précédente se trouve à la ligne '' {0} ''.
overload.methods.declaration=Toutes les méthodes surchargées doivent être placées les unes à côté des autres. Méthode surchargée précédente située à la ligne ''{0}''.
parameter.assignment=Il est interdit d''affecter une valeur au paramètre ''{0}''.
require.this.method=L''appel à la méthode ''{0}'' nécessite l''utilisation de "{1}this.".
require.this.variable=La référence à la variable d''instance ''{0}'' doit utiliser "{1}this.".
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=ネストした if-else の深さが {0,number,integer} (最
nested.try.depth=ネストした try の深さが {0,number,integer} (最大 {1,number,integer} まで)です。
no.array.trailing.comma=配列には末尾のコンマを含めないでください。
no.enum.trailing.comma=列挙には末尾のコンマを含めないでください。
overload.methods.declaration=すべてのオーバーロードされたメソッドは、互いに隣接して配置する必要があります。 同じタイプのオーバーロードされたメソッドの間に非オーバーロードされたメソッドを配置することは違反です。 最後のオーバーロードされたメソッドは、行 '' {0} ''にあります。
overload.methods.declaration=すべてのオーバーロードされたメソッドは隣り合って配置する必要があります。以前のオーバーロードされたメソッドは行 ''{0}'' にあります。
parameter.assignment=パラメータ ''{0}'' への代入は許可されていません。
require.this.method=メソッド ''{0}'' への呼び出しは、 "{1}this." が必要です。
require.this.variable=インスタンス変数 ''{0}'' への参照には "{1}this." が必要です。
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=A profundidade de aninhamento do "if-else" é {0,number,integer}
nested.try.depth=A profundidade de aninhamento do "try" é {0,number,integer} (o máximo permitido é {1,number,integer}).
no.array.trailing.comma=A matriz não deve conter vírgula à direita.
no.enum.trailing.comma=O enum não deve conter vírgula à direita.
overload.methods.declaration=Todos os métodos sobrecarregados devem ser colocados juntos. A colocação de métodos não sobrecarregados entre métodos sobrecarregados com o mesmo tipo é uma violação. O método sobrecarregado anterior foi encontrado na linha '' {0} ''.
overload.methods.declaration=Todos os métodos sobrecarregados devem ser colocados um ao lado do outro. Método sobrecarregado anterior localizado na linha ''{0}''.
parameter.assignment=A atribuição ao parâmetro ''{0}'' não é permitida.
require.this.method=A chamada de método no ''{0}'' precisa de "{1}this.".
require.this.variable=A referência à variável de instância ''{0}'' precisa de "{1}this.".
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=Глубина if-else {0,number,integer} (максимум {1,n
nested.try.depth=Глубина try {0,number,integer} (максимум {1,number,integer}).
no.array.trailing.comma=У последнего элемента массива не должно быть запятой.
no.enum.trailing.comma=У последней константы перечисления не должно быть запятой.
overload.methods.declaration=Все перегруженные методы должны быть размещены рядом друг с другом. Размещение не перегруженных методов между перегруженными методами одного и того же типа является нарушением. Предыдущий перегруженный метод расположен в строке ''{0}''.
overload.methods.declaration=Все перегруженные методы следует размещать рядом друг с другом. Предыдущий перегруженный метод расположен в строке ''{0}''.
parameter.assignment=Параметр метода ''{0}'' не должен менять значение.
require.this.method=При вызове метода ''{0}'' нужно использовать \"{1}this.\".
require.this.variable=При использовании переменной класса ''{0}'' нужно использовать \"{1}this.\".
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=İç içe kullanılan ''if-else'' sayısı {0,number,integer} (m
nested.try.depth=İç içe kullanılan ''try'' sayısı {0,number,integer} (maksimum izin verilen değer {1,number,integer}).
no.array.trailing.comma=Dizi sonda virgül içermemelidir.
no.enum.trailing.comma=Enum, sonda virgül içermemelidir.
overload.methods.declaration=Aşırı yüklenmiş tüm yöntemler yan yana yerleştirilmelidir. Aşırı yüklenmemiş yöntemleri aynı tip aşırı yüklenmiş yöntemler arasına yerleştirmek bir ihlaldir. '' {0} '' satırında önceki aşırı yüklenmiş yöntem.
overload.methods.declaration=Tüm aşırı yüklenmiş yöntemler yan yana yerleştirilmelidir. ''{0}'' satırında bulunan önceki aşırı yüklenmiş yöntem.
parameter.assignment=''{0}'' parametresine atama yapılamaz.
require.this.method=''{0}'' metoduna erişim "{1}this." kullanılarak yapılmalıdır.
require.this.variable=''{0}'' değişkenine erişim "{1}this." kullanılarak yapılmalıdır.
Expand Down
Expand Up @@ -44,7 +44,7 @@ nested.if.depth=至多{1,number,integer}层 if,目前{0,number,integer}层。
nested.try.depth=至多{1,number,integer}层 try,目前{0,number,integer}层。
no.array.trailing.comma=數組不應包含結尾逗號。
no.enum.trailing.comma=枚举不应包含结尾逗号。
overload.methods.declaration=所有重载的方法都应该相邻放置。在相同类型的重载方法之间放置非重载方法是违反的。最后一个重载方法在行 ''{0}''
overload.methods.declaration=所有重载方法应彼此相邻放置。上一个重载方法位于 ''{0}''
parameter.assignment=不应对方法参数''{0}''赋值。
require.this.method=对方法 ''{0}'' 的调用需要 "{1}this."
require.this.variable=对实例属性 ''{0}'' 的引用需要 "{1}this."
Expand Down
Expand Up @@ -41,8 +41,12 @@ public void testDefault() throws Exception {
final String[] expected = {
"32:5: " + getCheckMessage(MSG_KEY, 21),
"60:9: " + getCheckMessage(MSG_KEY, 49),
"72:5: " + getCheckMessage(MSG_KEY, 70),
"115:5: " + getCheckMessage(MSG_KEY, 104),
"65:9: " + getCheckMessage(MSG_KEY, 60),
"83:5: " + getCheckMessage(MSG_KEY, 81),
"127:5: " + getCheckMessage(MSG_KEY, 116),
"138:5: " + getCheckMessage(MSG_KEY, 132),
"149:9: " + getCheckMessage(MSG_KEY, 143),
"152:5: " + getCheckMessage(MSG_KEY, 138),
};
verifyWithInlineConfigParser(
getPath("InputOverloadMethodsDeclarationOrder.java"), expected);
Expand All @@ -55,6 +59,7 @@ public void testOverloadMethodsDeclarationOrderRecords() throws Exception {
"21:9: " + getCheckMessage(MSG_KEY, 15),
"41:9: " + getCheckMessage(MSG_KEY, 35),
"57:9: " + getCheckMessage(MSG_KEY, 50),
"63:9: " + getCheckMessage(MSG_KEY, 57),
};
verifyWithInlineConfigParser(
getNonCompilablePath("InputOverloadMethodsDeclarationOrderRecords.java"),
Expand Down
Expand Up @@ -60,7 +60,7 @@ public void foo() { // violation
public MyClass() {
}

public void foo(int i, String s) {
public void foo(int i, String s) { // violation
}

public void foo(String s, int i) {
Expand Down
Expand Up @@ -60,6 +60,17 @@ public void fooMethod()
public void overloadMethod(String s, Boolean b, int i) // violation
{
//some foo code
};

public void overloadMethod(double d)
{
// violation 2 lines above
/*
* Explanation of violation:
* There is a semicolon at the end of the previous method
* which is separating these overloaded methods
* and causing the violation.
*/
}
};
}
Expand Down Expand Up @@ -101,6 +112,7 @@ public void overloadMethod(String s)
//some foo code
}

// comments between overloaded methods are allowed.
public void overloadMethod(boolean b)
{
//some foo code
Expand All @@ -116,6 +128,28 @@ public void overloadMethod(String s, Boolean b, int i) // violation
{
//some foo code
}

void test() {}

String str;

private interface Testing {}

void test(int x) {} // violation

private class Inner {
void test() {}

void test(String str) {}

void test2() {}

String str;

void test(int x) {} // violation
}

void test(double d) {} // violation
}

enum Foo2 {
Expand Down
Expand Up @@ -8,8 +8,10 @@

// xdoc section -- start
public void foo(int i) {}
// comments between overloaded methods are allowed.
public void foo(String s) {}
public void foo(String s, int i) {}
public void foo(int i, String s) {}
public void notFoo() {}
private interface ExampleInterface() {}
// xdoc section -- end
Expand Up @@ -8,8 +8,10 @@

// xdoc section -- start
public void foo(int i) {} // OK
// comments between overloaded methods are allowed.
public void foo(String s) {} // OK
public void notFoo() {} // violation. Have to be after foo(String s, int i)
public void foo(int i, String s) {}
public void foo(String s, int i) {}
private interface ExampleInterface() {}
public void foo(String s, int i) {} // violation. Have to be after foo(int i, String s)
// xdoc section -- end
6 changes: 5 additions & 1 deletion src/xdocs/checks/coding/overloadmethodsdeclarationorder.xml
Expand Up @@ -28,18 +28,22 @@
<p id="Example1-code">Example of correct grouping of overloaded methods:</p>
<source>
public void foo(int i) {}
// comments between overloaded methods are allowed.
public void foo(String s) {}
public void foo(String s, int i) {}
public void foo(int i, String s) {}
public void notFoo() {}
private interface ExampleInterface() {}
</source>
<p id="Example2-code">Example of incorrect grouping of overloaded methods:</p>
<source>
public void foo(int i) {} // OK
// comments between overloaded methods are allowed.
public void foo(String s) {} // OK
public void notFoo() {} // violation. Have to be after foo(String s, int i)
public void foo(int i, String s) {}
public void foo(String s, int i) {}
private interface ExampleInterface() {}
public void foo(String s, int i) {} // violation. Have to be after foo(int i, String s)
</source>
</subsection>

Expand Down

0 comments on commit 4096711

Please sign in to comment.