Skip to content

Commit 651588d

Browse files
graememorganError Prone Team
authored andcommitted
Multiple top level records: also evil.
PiperOrigin-RevId: 762147462
1 parent a71e7e5 commit 651588d

File tree

2 files changed

+24
-14
lines changed

2 files changed

+24
-14
lines changed

core/src/main/java/com/google/errorprone/bugpatterns/MultipleTopLevelClasses.java

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,24 +49,17 @@ public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState s
4949
List<String> names = new ArrayList<>();
5050
for (Tree member : tree.getTypeDecls()) {
5151
if (member instanceof ClassTree classMember) {
52-
switch (classMember.getKind()) {
53-
case CLASS, INTERFACE, ANNOTATION_TYPE, ENUM -> {
54-
if (isSuppressed(classMember, state)) {
55-
// If any top-level classes have @SuppressWarnings("TopLevel"), ignore
56-
// this compilation unit. We can't rely on the normal suppression
57-
// mechanism because the only enclosing element is the package declaration,
58-
// and @SuppressWarnings can't be applied to packages.
59-
return NO_MATCH;
60-
}
61-
names.add(classMember.getSimpleName().toString());
62-
}
63-
default -> {}
52+
if (isSuppressed(classMember, state)) {
53+
// If any top-level classes have @SuppressWarnings("TopLevel"), ignore
54+
// this compilation unit. We can't rely on the normal suppression
55+
// mechanism because the only enclosing element is the package declaration,
56+
// and @SuppressWarnings can't be applied to packages.
57+
return NO_MATCH;
6458
}
59+
names.add(classMember.getSimpleName().toString());
6560
}
6661
}
6762
if (names.size() <= 1) {
68-
// this can happen with multiple type declarations if some of them are
69-
// empty (e.g. ";" at the top level counts as an empty type decl)
7063
return NO_MATCH;
7164
}
7265
String message =

core/src/test/java/com/google/errorprone/bugpatterns/MultipleTopLevelClassesTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,21 @@ public void semiInImportList() {
124124
"class Extra {}")
125125
.doTest();
126126
}
127+
128+
@Test
129+
public void twoRecords() {
130+
compilationHelper
131+
.addSourceLines(
132+
"a/A.java",
133+
"""
134+
package a;
135+
136+
// BUG: Diagnostic contains: one top-level class declaration, instead found: One, Two
137+
record One() {}
138+
139+
// BUG: Diagnostic contains:
140+
record Two() {}
141+
""")
142+
.doTest();
143+
}
127144
}

0 commit comments

Comments
 (0)