Skip to content

Commit

Permalink
Issue checkstyle#11807: fixes exception on records and fields in Requ…
Browse files Browse the repository at this point in the history
…ireThis
  • Loading branch information
rnveach committed Dec 2, 2022
1 parent 488ed2d commit f5105f5
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 5 deletions.
Expand Up @@ -1562,11 +1562,14 @@ public boolean hasStaticMethod(final DetailAST ident) {
public boolean hasFinalField(final DetailAST instanceMember) {
boolean result = false;
for (DetailAST member : instanceMembers) {
final DetailAST mods = member.getParent().findFirstToken(TokenTypes.MODIFIERS);
final boolean finalMod = mods.findFirstToken(TokenTypes.FINAL) != null;
if (finalMod && isAstSimilar(member, instanceMember)) {
result = true;
break;
final DetailAST parent = member.getParent();
if (parent.getType() != TokenTypes.RECORD_COMPONENT_DEF) {
final DetailAST mods = parent.findFirstToken(TokenTypes.MODIFIERS);
final boolean finalMod = mods.findFirstToken(TokenTypes.FINAL) != null;
if (finalMod && isAstSimilar(member, instanceMember)) {
result = true;
break;
}
}
}
return result;
Expand Down
Expand Up @@ -471,6 +471,17 @@ public void testRecordsDefault() throws Exception {
expected);
}

@Test
public void testRecordsWithCheckFields() throws Exception {
final String[] expected = {
"16:9: " + getCheckMessage(MSG_VARIABLE, "a", ""),
"32:9: " + getCheckMessage(MSG_VARIABLE, "a", ""),
};
verifyWithInlineConfigParser(
getNonCompilablePath("InputRequireThisRecordsWithCheckFields.java"),
expected);
}

@Test
public void testLocalClassesInsideLambdas() throws Exception {
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
Expand Down
@@ -0,0 +1,42 @@
/*
RequireThis
checkFields = true
checkMethods = (default)true
validateOnlyOverlapping = (default)true
*/

//non-compiled with javac: Compilable with Java14
package com.puppycrawl.tools.checkstyle.checks.coding.requirethis;

public record InputRequireThisRecordsWithCheckFields(int a) {
void method() {
String a = "BUG";
a = a.substring(0, 1); // violation 'Reference to instance variable 'a' needs "this."'
}

void method2() {
String a = "BUG".substring(0, 1); // ok
}
}
class InputRequireThisRecordsWithCheckFieldsClass {
int a;

public InputRequireThisRecordsWithCheckFieldsClass(int a) {
this.a = a;
}

void method() {
String a = "BUG";
a = a.substring(0, 1); // violation 'Reference to instance variable 'a' needs "this."'
}

void method2() {
String a = "BUG".substring(0, 1); // ok
}

public int a() {
return a;
}
}

0 comments on commit f5105f5

Please sign in to comment.