Skip to content

Commit

Permalink
Issue checkstyle#15107: Add input file for guarded pattern syntax in …
Browse files Browse the repository at this point in the history
…MagicNumberCheck
  • Loading branch information
mahfouz72 authored and nrmancuso committed Jun 26, 2024
1 parent 6781733 commit 8a8b7de
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -727,4 +727,21 @@ public void testMagicNumber3() throws Exception {
verifyWithInlineConfigParser(
getPath("InputMagicNumberMagicNumber3.java"), expected);
}

@Test
public void testMagicNumberInGuards() throws Exception {
final String[] expected = {
"21:63: " + getCheckMessage(MSG_KEY, "3"),
"21:72: " + getCheckMessage(MSG_KEY, "8"),
"27:58: " + getCheckMessage(MSG_KEY, "3"),
"27:68: " + getCheckMessage(MSG_KEY, "6"),
"31:50: " + getCheckMessage(MSG_KEY, "10.88"),
"33:46: " + getCheckMessage(MSG_KEY, "6"),
"39:59: " + getCheckMessage(MSG_KEY, "0.5"),
"39:67: " + getCheckMessage(MSG_KEY, "5"),
"44:23: " + getCheckMessage(MSG_KEY, "6"),
};
verifyWithInlineConfigParser(
getNonCompilablePath("InputMagicNumberMagicNumberInGuards.java"), expected);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
MagicNumber
ignoreNumbers = (default)-1, 0, 1, 2
ignoreHashCodeMethod = (default)false
ignoreAnnotation = (default)false
ignoreFieldDeclaration = (default)false
ignoreAnnotationElementDefaults = (default)true
constantWaiverParentToken = (default)TYPECAST, METHOD_CALL, EXPR, ARRAY_INIT, UNARY_MINUS, \
UNARY_PLUS, ELIST, STAR, ASSIGN, PLUS, MINUS, DIV, LITERAL_NEW
tokens = (default)NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG
*/

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

public class InputMagicNumberMagicNumberInGuards {

void m(Object o) {
if (o instanceof Point(int x, int y, double z) && x < 3 && y > 8) {}
// 2 violations above:
// ''3' is a magic number'
// ''8' is a magic number'

switch (o) {
case Point(int x, int y, double z) when (x < 3 && y != 6) -> {}
// 2 violations above:
// ''3' is a magic number.'
// ''6' is a magic number.'
case Point(_, _, double z) when z > (10.88) -> {}
// violation above, ''10.88' is a magic number'
case String s when s.length() != 6 -> {}
// violation above, ''6' is a magic number'
default -> {}
}

int w = switch (o) {
case Point(int x, int y, double z) when (z == 0.5) -> 5;
// 2 violations above:
// ''0.5' is a magic number.'
// ''5' is a magic number.'
case String s -> {
yield 6; // violation, ''6' is a magic number'
}
default -> 0;
};
}

record Point(int x, int y, double z) { }
}

0 comments on commit 8a8b7de

Please sign in to comment.