repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java10/LocalVariableTypeInferenceForLoop.java
public class LocalVariableTypeInferenceForLoop { public void aMethod() { for (var i = 1; i < 10; i++) { System.out.println(i); } } }
169
20.25
48
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java15/NonSealedIdentifier.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ public class NonSealedIdentifier { public static void main(String[] args) { int result = 0; int non = 1; // sealed is a valid identifier name in both Java15 and Java15 Preview int sealed = 2; // non-sealed is a valid subtraction expression in both Java15 and Java15 Preview result = non-sealed; System.out.println(result); } }
479
29
89
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java15/TextBlocks.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /** * Text Blocks are a permanent language feature with JDK 15. * * @see <a href="https://openjdk.java.net/jeps/378>JEP 378: Text Blocks</a> */ public class TextBlocks { public static void main(String[] args) throws Exception { // note: there is trailing whitespace!! String html = """ <html> <body> <p>Hello, world</p> </body> </html> """; System.out.println(html); String query = """ SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` WHERE `CITY` = 'INDIANAPOLIS' ORDER BY `EMP_ID`, `LAST_NAME`; """; System.out.println(query); ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); Object obj = engine.eval(""" function hello() { print('"Hello, world"'); } hello(); """); // Escape sequences String htmlWithEscapes = """ <html>\r <body>\r <p>Hello, world</p>\r </body>\r </html>\r """; System.out.println(htmlWithEscapes); String season = """ winter"""; // the six characters w i n t e r String period = """ winter """; // the seven characters w i n t e r LF String greeting = """ Hi, "Bob" """; // the ten characters H i , SP " B o b " LF String salutation = """ Hi, "Bob" """; // the eleven characters H i , LF SP " B o b " LF String empty = """ """; // the empty string (zero length) String quote = """ " """; // the two characters " LF String backslash = """ \\ """; // the two characters \ LF String normalStringLiteral = "test"; String code = """ String text = \""" A text block inside a text block \"""; """; // new escape sequences String text = """ Lorem ipsum dolor sit amet, consectetur adipiscing \ elit, sed do eiusmod tempor incididunt ut labore \ et dolore magna aliqua.\ """; System.out.println(text); String colors = """ red \s green\s blue \s """; System.out.println(colors); // empty new line as first content String emptyLine = """ test """; System.out.println(emptyLine.replaceAll("\n", "<LF>")); // backslash escapes String bs = """ \\test """; System.out.println(bs.replaceAll("\n", "<LF>")); } }
3,564
28.708333
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java9/jdk9_module_info_with_annot.java
/* * See §7.7 Module Declarations in JLS */ @Deprecated(since = "11", forRemoval = true) module jdk.pack { }
111
15
44
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java9/jdk9_private_interface_methods.java
/** * With java9, private methods are allowed in interface. */ public class Java9Interface { public interface Tool { void use(); default String getName() { return determineName(); } default String getStaticName() { return determineNameStatic(); } private String determineName() { return "unknown:" + this.getClass().getSimpleName(); } private static String determineNameStatic() { return "unknown:" + Tool.class.getSimpleName(); } } public static class SampleTool implements Tool { public void use() { if (true) { // force a PMD violation: java-basic/UnconditionalIfStatement System.out.println("Instance: " + getName()); System.out.println(" Static: " + getStaticName()); } } } public static void main(String... args) { Tool tool = new SampleTool(); tool.use(); } }
1,010
23.658537
85
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java9/jdk9_try_with_resources.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ public class InputJava9TryWithResources { public static void main() { MyResource resource1 = new MyResource(); MyResource resource2 = new MyResource(); try (resource1) { } try (resource1;) { } try (resource1; resource2) { } try (resource1.foo) { } try (resource1.foo.a) { } try (resource1.foo.Type v = null) { } try (this.foo.aa) { } try (this.foo) { } } }
467
23.631579
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java9/jdk9_module_info.java
/* * See §7.7 Module Declarations in JLS */ open module com.example.foo { requires com.example.foo.http; requires java.logging; requires transitive com.example.foo.network; exports com.example.foo.bar; exports com.example.foo.internal to com.example.foo.probe; uses com.example.foo.spi.Intf; provides com.example.foo.spi.Intf with com.example.foo.Impl; provides com.example.foo.spi.Intf2 with com.example.foo.Impl, com.example.foo.Impl2; }
477
27.117647
88
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java9/jdk9_invalid_identifier.java
/** * Using "_" as an identifier is not allowed anymore with java9. */ public class Java9Identifier { /* * see https://bugs.openjdk.java.net/browse/JDK-8061549 */ public interface Lambda { public int a(int _); public default void t(Lambda l) { t(_ -> 0); } } }
322
19.1875
64
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java9/jdk9_anonymous_diamond.java
import java.util.HashSet; import java.util.Set; public class Java9AnonymousDiamond { public static void main(String... args) { Set<String> set = new HashSet<>() { }; } }
186
22.375
46
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/PatternsInSwitchLabels.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> */ public class PatternsInSwitchLabels { public static void main(String[] args) { Object o = 123L; String formatted = switch (o) { case Integer i -> String.format("int %d", i); case Long l -> String.format("long %d", l); case Double d -> String.format("double %f", d); case String s -> String.format("String %s", s); default -> o.toString(); }; System.out.println(formatted); } }
691
29.086957
103
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/GuardedAndParenthesizedPatterns.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> */ public class GuardedAndParenthesizedPatterns { static void test(Object o) { switch (o) { case String s when s.length() == 1 -> System.out.println("single char string"); case String s -> System.out.println("string"); case Integer i when i.intValue() == 1 -> System.out.println("integer 1"); case (Long l) when l.longValue() == 1L -> System.out.println("long 1 with parens"); case (((Double d))) -> System.out.println("double with parens"); default -> System.out.println("default case"); } } // verify that "when" can still be used as an identifier void testIdentifierWhen(String when) { System.out.println(when); } // verify that "when" can still be used as an identifier void testIdentifierWhen() { int when = 1; System.out.println(when); } // verify that "when" can still be used as a type name private static class when {} static void testWithNull(Object o) { switch (o) { case String s when (s.length() == 1) -> System.out.println("single char string"); case String s -> System.out.println("string"); case (Integer i) when i.intValue() == 1 -> System.out.println("integer 1"); case ((Long l)) when ((l.longValue() == 1L)) -> System.out.println("long 1 with parens"); case (((Double d))) -> System.out.println("double with parens"); case null -> System.out.println("null!"); default -> System.out.println("default case"); } } static void instanceOfPattern(Object o) { if (o instanceof String s && s.length() > 2) { System.out.println("A string containing at least two characters"); } if (o != null && (o instanceof String s && s.length() > 3)) { System.out.println("A string containing at least three characters"); } // note: with this 3rd preview, the following is not allowed anymore: // if (o instanceof (String s && s.length() > 4)) { // > An alternative to guarded pattern labels is to support guarded patterns directly as a special pattern form, // > e.g. p && e. Having experimented with this in previous previews, the resulting ambiguity with boolean // > expressions have lead us to prefer when clauses in pattern switches. if ((o instanceof String s) && (s.length() > 4)) { System.out.println("A string containing at least four characters"); } } public static void main(String[] args) { test("a"); test("fooo"); test(1); test(1L); instanceOfPattern("abcde"); try { test(null); // throws NPE } catch (NullPointerException e) { e.printStackTrace(); } testWithNull(null); } }
3,252
39.160494
121
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/ExhaustiveSwitch.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> */ public class ExhaustiveSwitch { static int coverage(Object o) { return switch (o) { case String s -> s.length(); case Integer i -> i; default -> 0; }; } static int coverageDefaultCase(Object o) { return switch (o) { case String s -> s.length(); case Integer i -> i; case default -> 0; }; } static void coverageStatement(Object o) { switch (o) { case String s: System.out.println(s); break; case Integer i: System.out.println("Integer"); break; default: // Now exhaustive! break; } } sealed interface S permits A, B, C {} final static class A implements S {} final static class B implements S {} record C(int i) implements S {} // Implicitly final static int testSealedExhaustive(S s) { return switch (s) { case A a -> 1; case B b -> 2; case C c -> 3; }; } static void switchStatementExhaustive(S s) { switch (s) { case A a : System.out.println("A"); break; case C c : System.out.println("C"); break; default: System.out.println("default case, should be B"); break; }; } sealed interface I<T> permits E, F {} final static class E<X> implements I<String> {} final static class F<Y> implements I<Y> {} static int testGenericSealedExhaustive(I<Integer> i) { return switch (i) { // Exhaustive as no E case possible! case F<Integer> bi -> 42; }; } public static void main(String[] args) { System.out.println(coverage("a string")); System.out.println(coverage(42)); System.out.println(coverage(new Object())); coverageStatement("a string"); coverageStatement(21); coverageStatement(new Object()); System.out.println("A:" + testSealedExhaustive(new A())); System.out.println("B:" + testSealedExhaustive(new B())); System.out.println("C:" + testSealedExhaustive(new C(1))); switchStatementExhaustive(new A()); switchStatementExhaustive(new B()); switchStatementExhaustive(new C(2)); System.out.println("F:" + testGenericSealedExhaustive(new F<Integer>())); } }
2,739
27.842105
103
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/RecordPatterns.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/405">JEP 405: Record Patterns (Preview)</a> */ public class RecordPatterns { record Point(int x, int y) {} enum Color { RED, GREEN, BLUE } record ColoredPoint(Point p, Color c) {} record Rectangle(ColoredPoint upperLeft, ColoredPoint lowerRight) {} void printSum1(Object o) { if (o instanceof Point p) { int x = p.x(); int y = p.y(); System.out.println(x+y); } } // record pattern void printSum2(Object o) { if (o instanceof Point(int x, int y)) { System.out.println(x+y); } } void printUpperLeftColoredPoint(Rectangle r) { if (r instanceof Rectangle(ColoredPoint ul, ColoredPoint lr)) { System.out.println(ul.c()); } } // nested record pattern void printColorOfUpperLeftPoint(Rectangle r) { if (r instanceof Rectangle(ColoredPoint(Point p, Color c), ColoredPoint lr)) { System.out.println(c); } } // fully nested record pattern, also using "var" void printXCoordOfUpperLeftPointWithPatterns(Rectangle r) { if (r instanceof Rectangle(ColoredPoint(Point(var x, var y), var c), var lr)) { System.out.println("Upper-left corner: " + x); } } // record patterns with generic types record Box<T>(T t) {} void test1(Box<Object> bo) { if (bo instanceof Box<Object>(String s)) { System.out.println("String " + s); } } void test2(Box<String> bo) { if (bo instanceof Box<String>(var s)) { System.out.println("String " + s); } } }
1,804
27.203125
85
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/RefiningPatternsInSwitch.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> */ public class RefiningPatternsInSwitch { static class Shape {} static class Rectangle extends Shape {} static class Triangle extends Shape { private int area; Triangle(int area) { this.area = area; } int calculateArea() { return area; } } static void testTriangle(Shape s) { switch (s) { case null: break; case Triangle t: if (t.calculateArea() > 100) { System.out.println("Large triangle"); break; } default: System.out.println("A shape, possibly a small triangle"); } } static void testTriangleRefined(Shape s) { switch (s) { case Triangle t when t.calculateArea() > 100 -> System.out.println("Large triangle"); default -> System.out.println("A shape, possibly a small triangle"); } } static void testTriangleRefined2(Shape s) { switch (s) { case Triangle t when t.calculateArea() > 100 -> System.out.println("Large triangle"); case Triangle t -> System.out.println("Small triangle"); default -> System.out.println("Non-triangle"); } } public static void main(String[] args) { Triangle large = new Triangle(200); Triangle small = new Triangle(10); Rectangle rect = new Rectangle(); testTriangle(large); testTriangle(small); testTriangle(rect); testTriangleRefined(large); testTriangleRefined(small); testTriangleRefined(rect); testTriangleRefined2(large); testTriangleRefined2(small); testTriangleRefined2(rect); } }
2,048
27.458333
103
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/DealingWithNull.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> */ public class DealingWithNull { static void testFooBar(String s) { switch (s) { case null -> System.out.println("Oops"); case "Foo", "Bar" -> System.out.println("Great"); default -> System.out.println("Ok"); } } static void testStringOrNull(Object o) { switch (o) { case null, String s -> System.out.println("String: " + s); case default -> System.out.print("default case"); } } static void test(Object o) { switch (o) { case null -> System.out.println("null!"); case String s -> System.out.println("String"); default -> System.out.println("Something else"); } } static void test2(Object o) { switch (o) { case null -> throw new NullPointerException(); case String s -> System.out.println("String: "+s); case Integer i -> System.out.println("Integer"); default -> System.out.println("default"); } } static void test3(Object o) { switch(o) { case null: case String s: System.out.println("String, including null"); break; default: System.out.println("default case"); break; } switch(o) { case null, String s -> System.out.println("String, including null"); default -> System.out.println("default case"); } switch(o) { case null: default: System.out.println("The rest (including null)"); } switch(o) { case null, default -> System.out.println("The rest (including null)"); } } public static void main(String[] args) { test("test"); test2(2); try { test2(null); } catch (NullPointerException e) { System.out.println(e); } test3(3); test3("test"); test3(null); testFooBar(null); testFooBar("Foo"); testFooBar("Bar"); testFooBar("baz"); testStringOrNull(null); testStringOrNull("some string"); } }
2,466
26.10989
103
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/EnhancedTypeCheckingSwitch.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> */ public class EnhancedTypeCheckingSwitch { static void typeTester(Object o) { switch (o) { case null -> System.out.println("null"); case String s -> System.out.println("String"); case Color c -> System.out.println("Color with " + c.values().length + " values"); case Point p -> System.out.println("Record class: " + p.toString()); case int[] ia -> System.out.println("Array of ints of length" + ia.length); default -> System.out.println("Something else"); } } public static void main(String[] args) { Object o = "test"; typeTester(o); } } record Point(int i, int j) {} enum Color { RED, GREEN, BLUE; }
937
30.266667
103
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java19p/ScopeOfPatternVariableDeclarations.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> */ public class ScopeOfPatternVariableDeclarations { static void test(Object o) { switch (o) { case Character c -> { if (c.charValue() == 7) { System.out.println("Ding!"); } System.out.println("Character"); } case Integer i -> throw new IllegalStateException("Invalid Integer argument of value " + i.intValue()); default -> { break; } } } static void test2(Object o) { switch (o) { case Character c: if (c.charValue() == 7) { System.out.print("Ding "); } if (c.charValue() == 9) { System.out.print("Tab "); } System.out.println("character"); default: System.out.println(); } } public static void main(String[] args) { test('A'); test2('\t'); } }
1,241
24.346939
103
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java8/type_annotations.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ // From https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeAnnotations.java // and https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarationsAndAnno.java // and https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterNewTypeStructure.java // and https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/java8/InputAnnotations12.java @Target(ElementType.TYPE_USE) @interface NonNull {} class AnnotedArrayType { @NonNull int @NonNull[] @NonNull[] field1; @NonNull int @NonNull [] @NonNull [] field2; private @NonNull int array2 @NonNull [] @NonNull []; public String m2()@NonNull[]@NonNull[] { return null; } public String@NonNull[]@NonNull[] m2a() { return null; } public void run() { for (String a@NonNull[] : m2()) { } } void vararg(@NonNull String @NonNull [] @NonNull ... vararg2) { } public void vararg2(@NonNull int @NonNull ... vararg) {} public void vararg3(@NonNull int[] @NonNull ... vararg) {} } // From https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/avoidnoargumentsuperconstructorcall/InputAvoidNoArgumentSuperConstructorCall.java // and https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/antlr4/InputAntlr4AstRegressionAnnotationOnQualifiedTypes.java // and https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/antlr4/InputAntlr4AstRegressionNestedTypeParametersAndArrayDeclarators.java @Target({ ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.PARAMETER, ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) @interface TypeAnnotation { } class Rectangle2D { class Double{} } class TypeAnnotations { // We can use type Annotations with generic type arguments private Map.@TypeAnnotation Entry entry; // Type annotations in instanceof statements boolean isNonNull = "string" instanceof @TypeAnnotation String; // java.awt.geom.Rectangle2D public final Rectangle2D.@TypeAnnotation Double getRect1() { return new Rectangle2D.Double(); } public final Rectangle2D.Double getRect2() { return new Rectangle2D.@TypeAnnotation Double(); } public final Rectangle2D.Double getRect3() { Rectangle2D.@TypeAnnotation Double rect = null; int[][] i = new int @TypeAnnotation [1] @TypeAnnotation[]; i = new @TypeAnnotation int [1] @TypeAnnotation[]; return rect; } class Outer { class Inner { class Inner2 { } } class GInner<X> { class GInner2<Y, Z> {} } class Static {} class GStatic<X, Y> { class GStatic2<Z> {} } } class MyList<K> { } class Test1 { @TypeAnnotation Outer . @TypeAnnotation GInner<@TypeAnnotation MyList<@TypeAnnotation Object @TypeAnnotation[] @TypeAnnotation[]>> .@TypeAnnotation GInner2<@TypeAnnotation Integer, @TypeAnnotation Object> @TypeAnnotation[] @TypeAnnotation[] f4arrtop; } }
3,653
46.454545
215
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/SealedInnerClasses.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ public class SealedInnerClasses { sealed class Square implements Squircle { non-sealed private class OtherSquare extends Square {} static non-sealed class StaticClass implements Squircle {} } sealed interface Squircle permits Square, Square.StaticClass {} }
375
27.923077
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/LocalVars.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ public class LocalVars { public void aMethod() { String sealed = null; sealed = this.getClass().getName(); // error: sealed or non-sealed local classes are not allowed // sealed class LocalSealedClass {} } }
343
20.5
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/expression/TimesExpr.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.expression; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public final class TimesExpr implements Expr { }
260
25.1
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/expression/Expr.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.expression; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public sealed interface Expr permits ConstantExpr, PlusExpr, TimesExpr, NegExpr { }
296
26
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/expression/ConstantExpr.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.expression; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public final class ConstantExpr implements Expr { }
260
25.1
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/expression/PlusExpr.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.expression; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public final class PlusExpr implements Expr { }
260
25.1
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/expression/NegExpr.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.expression; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public final class NegExpr implements Expr { }
260
25.1
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/geometry/Rectangle.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.geometry; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public sealed class Rectangle extends Shape permits TransparentRectangle, FilledRectangle { }
306
24.583333
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/geometry/Shape.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.geometry; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public sealed class Shape permits Circle, Rectangle, Square { }
275
22
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/geometry/Square.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.geometry; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public non-sealed class Square extends Shape { }
256
22.363636
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/geometry/FilledRectangle.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.geometry; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public final class FilledRectangle extends Rectangle { }
264
23.090909
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/geometry/TransparentRectangle.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.geometry; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public final class TransparentRectangle extends Rectangle { }
269
23.545455
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java17/geometry/Circle.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package com.example.geometry; /** * @see <a href="https://openjdk.java.net/jeps/409">JEP 409: Sealed Classes</a> */ public final class Circle extends Shape { }
250
24.1
79
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java5/generic_super_ctor.java
// From https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/InputRegressionJavaClass2.java class c4<A,B> { class c4a {} public c4() { <String>super(); } } class c5 extends c4.c4a { c5() { new c4().super(); } c5(int a) { new c4().<String>super(); } }
335
29.545455
158
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java5/generic_ctors.java
// From https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/genericwhitespace/InputGenericWhitespaceDefault.java // and https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/antlr4/InputAntlr4AstRegressionUncommon4.java class GenericConstructor { Object ok = new <String>Object(); Object okWithPackage = new <String>java.lang.Object(); Object ok2 = new <String>Outer.Inner(); Object o3 = new <String>Outer().new <String>NonStatic(); Object o4 = new <String>GenericOuter<String>(); Object o5 = new <String>GenericOuter<String>().new <String>GenericInner<String>(); } class Outer { static class Inner {} class NonStatic {} } class GenericOuter<T> { class GenericInner<U> { } }
857
41.9
190
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java5/annotation_array_init.java
// From https://github.com/checkstyle/checkstyle/blob/checkstyle-9.1/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/antlr4/InputAntlr4AstRegressionSingleCommaInArrayInit.java class AnnotationCommaArrayInit { @Foo({,}) void b() { } @interface Foo { int[] value(); } }
287
47
186
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java14/SwitchExpressions.java
/** * @see <a href="https://openjdk.java.net/jeps/361">JEP 361: Switch Expressions (Standard)</a> */ public class SwitchExpressions { private enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public static final int BAZ = 3; public static void main(String[] args) { Day day = Day.THURSDAY; // SwitchStatement switch (day) { case MONDAY, FRIDAY, SUNDAY -> System.out.println(6); case TUESDAY -> System.out.println(7); case THURSDAY, SATURDAY -> System.out.println(8); case WEDNESDAY -> System.out.println(9); } // SwitchExpression int numLetters = switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; }; System.out.printf("numLetters=%d%n", numLetters); howMany(1); howMany(2); howMany(3); howManyExpr(1); howManyExpr(2); howManyExpr(3); // SwitchExpression int j = switch (day) { case MONDAY -> 0; case TUESDAY -> 1; default -> { int k = day.toString().length(); int result = f(k); yield result; } }; System.out.printf("j=%d%n", j); String s = "Foo"; // SwitchExpression int result = switch (s) { case "Foo": yield 1; case "Bar": yield 2; case "Baz": yield SwitchExpressions.BAZ; default: System.out.println("Neither Foo nor Bar, hmmm..."); yield 0; }; System.out.printf("result=%d%n", result); } private static void howMany(int k) { // SwitchStatement switch (k) { case 1 -> System.out.println("one"); case 2 -> System.out.println("two"); default -> System.out.println("many"); } } private static void howManyExpr(int k) { System.out.println( // SwitchExpression switch (k) { case 1 -> "one"; case 2 -> "two"; default -> "many"; } ); } private static int f(int k) { return k*2; } }
2,487
26.644444
94
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java14/YieldStatements.java
/** * @see <a href="https://openjdk.java.net/jeps/361">JEP 361: Switch Expressions (Standard)</a> */ public class YieldStatements { { int yield = 0; yield = 2; // should be an assignment yield (2); // should be a method call yield(a,b); // should be a method call yield = switch (e) { // must be a switch expr case 1 -> { yield(a,b); // should be a method call yield = 2; // should be an assignment yield (2); // should be a yield statement yield++bar; // should be a yield statement (++bar is an expression) yield--bar; // should be a yield statement (--bar is an expression) yield++; // should be an increment (not an error) yield--; // should be a decrement (not an error) if (true) yield(2); else yield 4; yield = switch (foo) { // putting a switch in the middles checks the reset behavior case 4 -> {yield(5);} // should be a yield statement }; yield () -> {}; // should be a yield statement yield (); // should be a method call yield (2); // should be a yield statement } }; } }
1,264
34.138889
95
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java14/SimpleSwitchExpressions.java
/** * * @see <a href="https://openjdk.java.net/jeps/325">JEP 325: Switch Expressions (Preview)</a> */ public class SimpleSwitchExpressions { private static final int MONDAY = 1; private static final int TUESDAY = 2; private static final int WEDNESDAY = 3; private static final int THURSDAY = 4; private static final int FRIDAY = 5; private static final int SATURDAY = 6; private static final int SUNDAY = 7; public static void main(String[] args) { int day = FRIDAY; var numLetters = switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; default -> { int k = day * 2; int result = f(k); yield result; } }; System.out.printf("NumLetters: %d%n", numLetters); } private static int f(int k) { return k*3; } }
1,113
29.944444
93
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java14/SwitchRules.java
/** * * @see <a href="https://openjdk.java.net/jeps/325">JEP 325: Switch Expressions (Preview)</a> */ public class SwitchRules { private static final int MONDAY = 1; private static final int TUESDAY = 2; private static final int WEDNESDAY = 3; private static final int THURSDAY = 4; private static final int FRIDAY = 5; private static final int SATURDAY = 6; private static final int SUNDAY = 7; public static void main(String[] args) { int day = WEDNESDAY; switch (day) { case MONDAY, FRIDAY, SUNDAY -> System.out.println(" 6"); case TUESDAY -> System.out.println(" 7"); case THURSDAY, SATURDAY -> System.out.println(" 8"); case WEDNESDAY -> { System.out.println(" 9"); } default -> throw new IllegalArgumentException(); } } }
899
33.615385
93
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java14/TextBlocks.java
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /** * @see <a href="https://openjdk.java.net/jeps/368">JEP 368: Text Blocks (Second Preview)</a> */ public class TextBlocks { public static void main(String[] args) throws Exception { // note: there is trailing whitespace!! String html = """ <html> <body> <p>Hello, world</p> </body> </html> """; System.out.println(html); String query = """ SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` WHERE `CITY` = 'INDIANAPOLIS' ORDER BY `EMP_ID`, `LAST_NAME`; """; System.out.println(query); ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); Object obj = engine.eval(""" function hello() { print('"Hello, world"'); } hello(); """); // Escape sequences String htmlWithEscapes = """ <html>\r <body>\r <p>Hello, world</p>\r </body>\r </html>\r """; System.out.println(htmlWithEscapes); String season = """ winter"""; // the six characters w i n t e r String period = """ winter """; // the seven characters w i n t e r LF String greeting = """ Hi, "Bob" """; // the ten characters H i , SP " B o b " LF String salutation = """ Hi, "Bob" """; // the eleven characters H i , LF SP " B o b " LF String empty = """ """; // the empty string (zero length) String quote = """ " """; // the two characters " LF String backslash = """ \\ """; // the two characters \ LF String normalStringLiteral = "test"; String code = """ String text = \""" A text block inside a text block \"""; """; // new escape sequences String text = """ Lorem ipsum dolor sit amet, consectetur adipiscing \ elit, sed do eiusmod tempor incididunt ut labore \ et dolore magna aliqua.\ """; System.out.println(text); String colors = """ red \s green\s blue \s """; System.out.println(colors); // empty new line as first content String emptyLine = """ test """; System.out.println(emptyLine.replaceAll("\n", "<LF>")); // backslash escapes String bs = """ \\test """; System.out.println(bs.replaceAll("\n", "<LF>")); } }
3,430
29.096491
93
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java14/MultipleCaseLabels.java
/** * * @see <a href="https://openjdk.java.net/jeps/325">JEP 325: Switch Expressions (Preview)</a> */ public class MultipleCaseLabels { private static final int MONDAY = 1; private static final int TUESDAY = 2; private static final int WEDNESDAY = 3; private static final int THURSDAY = 4; private static final int FRIDAY = 5; private static final int SATURDAY = 6; private static final int SUNDAY = 7; public static void main(String[] args) { int day = THURSDAY; switch (day) { case MONDAY, FRIDAY, SUNDAY: System.out.println(" 6"); break; case TUESDAY : System.out.println(" 7"); break; case THURSDAY, SATURDAY : System.out.println(" 8"); break; case WEDNESDAY : System.out.println(" 9"); break; } } }
851
31.769231
93
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/PatternsInSwitchLabels.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ public class PatternsInSwitchLabels { public static void main(String[] args) { Object o = 123L; String formatted = switch (o) { case Integer i -> String.format("int %d", i); case Long l -> String.format("long %d", l); case Double d -> String.format("double %f", d); case String s -> String.format("String %s", s); default -> o.toString(); }; System.out.println(formatted); } }
692
29.130435
104
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/RecordPatternsInEnhancedFor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a> */ public class RecordPatternsInEnhancedFor { record Point(int x, int y) {} enum Color { RED, GREEN, BLUE } record ColoredPoint(Point p, Color c) {} record Rectangle(ColoredPoint upperLeft, ColoredPoint lowerRight) {} // record patterns in for-each loop (enhanced for statement) static void dump(Point[] pointArray) { for (Point(var x, var y) : pointArray) { // Record Pattern in header! System.out.println("(" + x + ", " + y + ")"); } } // nested record patterns in enhanced for statement static void printUpperLeftColors(Rectangle[] r) { for (Rectangle(ColoredPoint(Point p, Color c), ColoredPoint lr): r) { System.out.println(c); } } record Pair(Object fst, Object snd){} static void exceptionTest() { Pair[] ps = new Pair[]{ new Pair(1,2), null, new Pair("hello","world") }; for (Pair(var f, var s): ps) { // Run-time MatchException System.out.println(f + " -> " + s); } } public static void main(String[] args) { exceptionTest(); } }
1,353
29.772727
92
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/GuardedAndParenthesizedPatterns.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ public class GuardedAndParenthesizedPatterns { static void test(Object o) { switch (o) { case String s when s.length() == 1 -> System.out.println("single char string"); case String s -> System.out.println("string"); case Integer i when i.intValue() == 1 -> System.out.println("integer 1"); case (Long l) when l.longValue() == 1L -> System.out.println("long 1 with parens"); case (((Double d))) -> System.out.println("double with parens"); default -> System.out.println("default case"); } } // verify that "when" can still be used as an identifier -> formal parameter void testIdentifierWhen(String when) { System.out.println(when); } // verify that "when" can still be used as an identifier -> local variable void testIdentifierWhen() { int when = 1; System.out.println(when); } // verify that "when" can still be used as a type name private static class when {} static void testWithNull(Object o) { switch (o) { case String s when (s.length() == 1) -> System.out.println("single char string"); case String s -> System.out.println("string"); case (Integer i) when i.intValue() == 1 -> System.out.println("integer 1"); case ((Long l)) when ((l.longValue() == 1L)) -> System.out.println("long 1 with parens"); case (((Double d))) -> System.out.println("double with parens"); case null -> System.out.println("null!"); default -> System.out.println("default case"); } } static void instanceOfPattern(Object o) { if (o instanceof String s && s.length() > 2) { System.out.println("A string containing at least two characters"); } if (o != null && (o instanceof String s && s.length() > 3)) { System.out.println("A string containing at least three characters"); } // note: with this 3rd preview, the following is not allowed anymore: // if (o instanceof (String s && s.length() > 4)) { // > An alternative to guarded pattern labels is to support guarded patterns directly as a special pattern form, // > e.g. p && e. Having experimented with this in previous previews, the resulting ambiguity with boolean // > expressions have lead us to prefer when clauses in pattern switches. if ((o instanceof String s) && (s.length() > 4)) { System.out.println("A string containing at least four characters"); } } static void testScopeOfPatternVariableDeclarations(Object obj) { if ((obj instanceof String s) && s.length() > 3) { System.out.println(s); } else { System.out.println("Not a string"); } } public static void main(String[] args) { test("a"); test("fooo"); test(1); test(1L); instanceOfPattern("abcde"); try { test(null); // throws NPE } catch (NullPointerException e) { e.printStackTrace(); } testWithNull(null); testScopeOfPatternVariableDeclarations("a"); testScopeOfPatternVariableDeclarations("long enough"); } }
3,719
39.879121
121
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/ExhaustiveSwitch.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ public class ExhaustiveSwitch { static int coverage(Object o) { return switch (o) { case String s -> s.length(); case Integer i -> i; default -> 0; }; } static void coverageStatement(Object o) { switch (o) { case String s: System.out.println(s); break; case Integer i: System.out.println("Integer"); break; default: // Now exhaustive! break; } } sealed interface S permits A, B, C {} final static class A implements S {} final static class B implements S {} record C(int i) implements S {} // Implicitly final static int testSealedExhaustive(S s) { return switch (s) { case A a -> 1; case B b -> 2; case C c -> 3; }; } static void switchStatementExhaustive(S s) { switch (s) { case A a : System.out.println("A"); break; case C c : System.out.println("C"); break; default: System.out.println("default case, should be B"); break; }; } sealed interface I<T> permits E, F {} final static class E<X> implements I<String> {} final static class F<Y> implements I<Y> {} static int testGenericSealedExhaustive(I<Integer> i) { return switch (i) { // Exhaustive as no E case possible! case F<Integer> bi -> 42; }; } public static void main(String[] args) { System.out.println(coverage("a string")); System.out.println(coverage(42)); System.out.println(coverage(new Object())); coverageStatement("a string"); coverageStatement(21); coverageStatement(new Object()); System.out.println("A:" + testSealedExhaustive(new A())); System.out.println("B:" + testSealedExhaustive(new B())); System.out.println("C:" + testSealedExhaustive(new C(1))); switchStatementExhaustive(new A()); switchStatementExhaustive(new B()); switchStatementExhaustive(new C(2)); System.out.println("F:" + testGenericSealedExhaustive(new F<Integer>())); } }
2,542
27.897727
104
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/RecordPatterns.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a> */ public class RecordPatterns { record Point(int x, int y) {} enum Color { RED, GREEN, BLUE } record ColoredPoint(Point p, Color c) {} record Rectangle(ColoredPoint upperLeft, ColoredPoint lowerRight) {} void printSum1(Object o) { if (o instanceof Point p) { int x = p.x(); int y = p.y(); System.out.println(x+y); } } // record pattern void printSum2(Object o) { if (o instanceof Point(int x, int y)) { System.out.println(x+y); } } void printUpperLeftColoredPoint(Rectangle r) { if (r instanceof Rectangle(ColoredPoint ul, ColoredPoint lr)) { System.out.println(ul.c()); } } // nested record pattern void printColorOfUpperLeftPoint(Rectangle r) { if (r instanceof Rectangle(ColoredPoint(Point p, Color c), ColoredPoint lr)) { System.out.println(c); } } Rectangle createRectangle(int x1, int y1, Color c1, int x2, int y2, Color c2) { Rectangle r = new Rectangle(new ColoredPoint(new Point(x1, y1), c1), new ColoredPoint(new Point(x2, y2), c2)); return r; } // fully nested record pattern, also using "var" void printXCoordOfUpperLeftPointWithPatterns(Rectangle r) { if (r instanceof Rectangle(ColoredPoint(Point(var x, var y), var c), var lr)) { System.out.println("Upper-left corner: " + x); } } record Pair(Object x, Object y) {} void nestedPatternsCanFailToMatch() { Pair p = new Pair(42, 42); if (p instanceof Pair(String s, String t)) { System.out.println(s + ", " + t); } else { System.out.println("Not a pair of strings"); } } // record patterns with generic types record Box<T>(T t) {} void test1a(Box<Object> bo) { if (bo instanceof Box<Object>(String s)) { System.out.println("String " + s); } } void test1(Box<String> bo) { if (bo instanceof Box<String>(var s)) { System.out.println("String " + s); } } // type argument is inferred void test2(Box<String> bo) { if (bo instanceof Box(var s)) { // Inferred to be Box<String>(var s) System.out.println("String " + s); } } // nested record patterns void test3(Box<Box<String>> bo) { if (bo instanceof Box<Box<String>>(Box(var s))) { System.out.println("String " + s); } } void test4(Box<Box<String>> bo) { if (bo instanceof Box(Box(var s))) { System.out.println("String " + s); } } }
2,910
27.821782
92
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/RefiningPatternsInSwitch.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ public class RefiningPatternsInSwitch { static class Shape {} static class Rectangle extends Shape {} static class Triangle extends Shape { private int area; Triangle(int area) { this.area = area; } int calculateArea() { return area; } } static void testTriangle(Shape s) { switch (s) { case null: break; case Triangle t: if (t.calculateArea() > 100) { System.out.println("Large triangle"); break; } default: System.out.println("A shape, possibly a small triangle"); } } static void testTriangleRefined(Shape s) { switch (s) { case null -> { break; } case Triangle t when t.calculateArea() > 100 -> System.out.println("Large triangle"); default -> System.out.println("A shape, possibly a small triangle"); } } static void testTriangleRefined2(Shape s) { switch (s) { case null -> { break; } case Triangle t when t.calculateArea() > 100 -> System.out.println("Large triangle"); case Triangle t -> System.out.println("Small triangle"); default -> System.out.println("Non-triangle"); } } public static void main(String[] args) { Triangle large = new Triangle(200); Triangle small = new Triangle(10); Rectangle rect = new Rectangle(); testTriangle(large); testTriangle(small); testTriangle(rect); testTriangleRefined(large); testTriangleRefined(small); testTriangleRefined(rect); testTriangleRefined2(large); testTriangleRefined2(small); testTriangleRefined2(rect); } }
2,176
26.910256
104
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/DealingWithNull.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ public class DealingWithNull { static void testFooBar(String s) { switch (s) { case null -> System.out.println("Oops"); case "Foo", "Bar" -> System.out.println("Great"); // CaseConstant default -> System.out.println("Ok"); } } static void testStringOrNull(Object o) { switch (o) { case String s -> System.out.println("String: " + s); // CasePattern case null -> System.out.println("null"); default -> System.out.println("default case"); } } static void testStringOrDefaultNull(Object o) { switch (o) { case String s -> System.out.println("String: " + s); case null, default -> System.out.println("null or default case"); } } static void test2(Object o) { switch (o) { case null -> throw new NullPointerException(); case String s -> System.out.println("String: "+s); case Integer i -> System.out.println("Integer"); default -> System.out.println("default"); } } static void test3(Object o) { switch(o) { case null: System.out.println("null"); break; // note: fall-through to a CasePattern is not allowed, as the pattern variable is not initialized case String s: System.out.println("String"); break; default: System.out.println("default case"); break; } switch(o) { case null -> System.out.println("null"); case String s -> System.out.println("String"); default -> System.out.println("default case"); } switch(o) { case null: default: System.out.println("The rest (including null)"); } switch(o) { case null, default -> System.out.println("The rest (including null)"); } } public static void main(String[] args) { testStringOrDefaultNull("test"); test2(2); try { test2(null); } catch (NullPointerException e) { System.out.println(e); } test3(3); test3("test"); test3(null); testFooBar(null); testFooBar("Foo"); testFooBar("Bar"); testFooBar("baz"); testStringOrNull(null); testStringOrNull("some string"); } }
2,764
28.414894
120
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/RecordPatternsExhaustiveSwitch.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a> */ public class RecordPatternsExhaustiveSwitch { class A {} class B extends A {} sealed interface I permits C, D {} final class C implements I {} final class D implements I {} record Pair<T>(T x, T y) {} static void test() { Pair<A> p1 = null; Pair<I> p2 = null; switch (p1) { // Error! case Pair<A>(A a, B b) -> System.out.println("a"); case Pair<A>(B b, A a) -> System.out.println("a"); case Pair<A>(A a1, A a2) -> System.out.println("exhaustive now"); // without this case, compile error } switch (p2) { case Pair<I>(I i, C c) -> System.out.println("a"); case Pair<I>(I i, D d) -> System.out.println("a"); } switch (p2) { case Pair<I>(C c, I i) -> System.out.println("a"); case Pair<I>(D d, C c) -> System.out.println("a"); case Pair<I>(D d1, D d2) -> System.out.println("a"); } } }
1,184
30.184211
113
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/EnhancedTypeCheckingSwitch.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ public class EnhancedTypeCheckingSwitch { static void typeTester(Object o) { switch (o) { case null -> System.out.println("null"); case String s -> System.out.println("String"); case Color c -> System.out.println("Color with " + c.values().length + " values"); case Point p -> System.out.println("Record class: " + p.toString()); case int[] ia -> System.out.println("Array of ints of length " + ia.length); default -> System.out.println("Something else"); } } public static void main(String[] args) { Object o = "test"; typeTester(o); typeTester(Color.BLUE); o = new int[] {1, 2, 3, 4}; typeTester(o); o = new Point(7, 8); typeTester(o); o = new Object(); typeTester(o); } } record Point(int i, int j) {} enum Color { RED, GREEN, BLUE; }
1,134
27.375
104
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/ast/jdkversiontests/java20p/ScopeOfPatternVariableDeclarations.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> */ public class ScopeOfPatternVariableDeclarations { static void testSwitchBlock(Object obj) { switch (obj) { case Character c when c.charValue() == 7: System.out.println("Ding!"); break; default: break; } } static void testSwitchRule(Object o) { switch (o) { case Character c -> { if (c.charValue() == 7) { System.out.println("Ding!"); } System.out.println("Character"); } case Integer i -> throw new IllegalStateException("Invalid Integer argument of value " + i.intValue()); default -> { break; } } } static void test2(Object o) { switch (o) { case Character c: if (c.charValue() == 7) { System.out.print("Ding "); } if (c.charValue() == 9) { System.out.print("Tab "); } System.out.println("character"); default: System.out.println("fall-through"); } } public static void main(String[] args) { testSwitchBlock('\u0007'); testSwitchRule('A'); try { testSwitchRule(42); // throws } catch (IllegalStateException e) { System.out.println(e); } test2('\t'); } }
1,727
25.584615
104
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/tabWidth.java
class tabWidth { int i = 0; }
31
7
16
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/ignoreIdentsPreservesClassLiteral.java
package foo.bar.baz; public class Foo { Foo() { } public void bar() { Bar.baz(Foo.class, () -> {}); } }
129
12
37
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/ignoreSpecialAnnotations.java
package foo.bar.baz; @SuppressWarnings({"woof","CPD-START"}) @SuppressWarnings("CPD-START") @ MyAnnotation ("ugh") @NamedQueries({ @NamedQuery( )}) public class Foo {} @SuppressWarnings({"ugh","CPD-END"}) class Other {}
259
17.571429
39
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/ignoreLiterals.java
public class Foo { public void bar() { System.out.println("hello"); System.out.println("hello"); int i = 5; System.out.print("hello"); } }
179
19
36
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/simpleClassWithComments.java
/* * This comment is ignored too */ public class Foo { // class Bar // comments are ignored }
100
13.428571
31
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/ignoreIdentsPreservesEnum.java
package foo.bar.baz; public enum Foo { BAR(1), BAZ(2); Foo(int val) { } }
91
9.222222
20
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/specialComments.java
package foo.bar.baz; // CPD-OFF // CPD-OFF // another irrelevant comment @ MyAnnotation ("ugh") @NamedQueries({ @NamedQuery( )}) public class Foo {// CPD-ON // special multiline comments class Foo /* CPD-OFF */{ } /* CPD-ON */ class Foo /* CPD-OFF */{ {something();} } /* CPD-ON */ }
330
11.730769
43
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/discardedElements.java
/* * This comment is ignored */ package a.b.c; // ignored // imports are ignored import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.List; import java.util.Properties; @Foo // ignored public class Foo { // class Bar // comments are ignored // semicolons are ignored int x; { x++; foo(); } // annotations are ignored @AnnotationWithParams("ugh") @AnnotationWithParams({@Nested(1) , @Nested(2) , @Nested }) public void foo() { } }
595
15.555556
44
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/cpd/testdata/ignoreIdentsPreservesCtor.java
package foo.bar.baz; public class Foo extends Bar { private Foo notAConstructor; public Foo(int i) { super(i); } private Foo(int i, String s) { super(i, s); } /* default */ Foo(int i, String s, Object o) { super(i, s, o); } private static class Inner { Inner() { System.out.println("Guess who?"); } } }
342
18.055556
68
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/types/IteratorUtilCopy.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; import java.util.Spliterators; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; public final class IteratorUtilCopy { private static final int MATCH_ANY = 0; private static final int MATCH_ALL = 1; private static final int MATCH_NONE = 2; private IteratorUtilCopy() { } @Target(ElementType.TYPE_USE) @interface Nullable {} public static <T> Iterator<T> takeWhile(Iterator<T> iter, Predicate<? super T> predicate) { return new AbstractIterator<T>() { @Override protected void computeNext() { T next = iter.next(); if (predicate.test(next)) { setNext(next); } else { done(); } } }; } public static <T> Iterator<T> reverse(Iterator<T> it) { List<T> tmp = toList(it); Collections.reverse(tmp); return tmp.iterator(); } public static <T, R> Iterator<R> flatMap(Iterator<? extends T> iter, Function<? super T, ? extends @Nullable Iterator<? extends R>> f) { return new AbstractIterator<R>() { private Iterator<? extends R> current = null; @Override protected void computeNext() { if (current != null && current.hasNext()) { setNext(current.next()); } else { while (iter.hasNext()) { Iterator<? extends R> next = f.apply(iter.next()); if (next != null && next.hasNext()) { current = next; setNext(current.next()); return; } } done(); } } }; } public static <R> Iterator<R> flatMapWithSelf(Iterator<? extends R> iter, Function<? super R, ? extends Iterator<? extends R>> f) { return new AbstractIterator<R>() { private Iterator<? extends R> current = null; @Override protected void computeNext() { if (current != null && current.hasNext()) { setNext(current.next()); } else { // current is exhausted current = null; if (iter.hasNext()) { R next = iter.next(); setNext(next); current = f.apply(next); } else { done(); } } } }; } public static <T> Iterator<T> filterNotNull(Iterator<? extends T> it) { return filter(it, Objects::nonNull); } public static <T, R> Iterator<R> mapNotNull(Iterator<? extends T> it, Function<? super T, ? extends R> mapper) { return new AbstractIterator<R>() { @Override protected void computeNext() { while (it.hasNext()) { T next = it.next(); if (next != null) { R map = mapper.apply(next); if (map != null) { setNext(map); return; } } } done(); } }; } public static <T> Iterator<T> filter(Iterator<? extends T> it, Predicate<? super T> filter) { return new AbstractIterator<T>() { @Override protected void computeNext() { while (it.hasNext()) { T next = it.next(); if (filter.test(next)) { setNext(next); return; } } done(); } }; } public static <T> Iterator<T> peek(Iterator<? extends T> iter, Consumer<? super T> action) { return map(iter, it -> { action.accept(it); return it; }); } public static <T, R> Iterator<R> map(Iterator<? extends T> iter, Function<? super T, ? extends R> mapper) { return new Iterator<R>() { @Override public boolean hasNext() { return iter.hasNext(); } @Override public R next() { return mapper.apply(iter.next()); } }; } public static <T, R> Iterable<R> mapIterator(Iterable<? extends T> iter, Function<? super Iterator<? extends T>, ? extends Iterator<R>> mapper) { return () -> mapper.apply(iter.iterator()); } @SafeVarargs public static <T> Iterator<T> iterate(T... elements) { return Arrays.asList(elements).iterator(); } public static <T> Iterator<T> concat(Iterator<? extends T> as, Iterator<? extends T> bs) { if (!as.hasNext()) { return (Iterator<T>) bs; } else if (!bs.hasNext()) { return (Iterator<T>) as; } return new Iterator<T>() { @Override public boolean hasNext() { return as.hasNext() || bs.hasNext(); } @Override public T next() { return as.hasNext() ? as.next() : bs.next(); } }; } public static <T> Iterator<T> distinct(Iterator<? extends T> iter) { Set<T> seen = new HashSet<>(); return filter(iter, seen::add); } public static <T> List<T> toList(Iterator<? extends T> it) { List<T> list = new ArrayList<>(); while (it.hasNext()) { list.add(it.next()); } return list; } public static <T> List<T> toNonNullList(Iterator<? extends T> it) { List<T> list = new ArrayList<>(); while (it.hasNext()) { T next = it.next(); if (next != null) { list.add(next); } } return list; } public static <T> Iterable<T> toIterable(final Iterator<T> it) { return () -> it; } public static int count(Iterator<?> it) { int count = 0; while (it.hasNext()) { it.next(); count++; } return count; } public static <T> T last(Iterator<? extends T> iterator) { T next = null; while (iterator.hasNext()) { next = iterator.next(); } return next; } public static <T> T getNth(Iterator<? extends T> iterator, int n) { advance(iterator, n); return iterator.hasNext() ? iterator.next() : null; } public static void advance(Iterator<?> iterator, int n) { while (n > 0 && iterator.hasNext()) { iterator.next(); n--; } } public static <T> Iterator<T> take(Iterator<? extends T> iterator, final int n) { if (n == 0) { return Collections.emptyIterator(); } return new AbstractIterator<T>() { private int yielded = 0; @Override protected void computeNext() { if (yielded >= n || !iterator.hasNext()) { done(); } else { setNext(iterator.next()); } yielded++; } }; } public static <T> Iterator<T> drop(Iterator<? extends T> source, final int n) { if (n == 0) { return (Iterator<T>) source; } return new AbstractIterator<T>() { private int yielded = 0; @Override protected void computeNext() { while (yielded++ < n && source.hasNext()) { source.next(); } if (!source.hasNext()) { done(); } else { setNext(source.next()); } } }; } public static <T> Iterator<T> generate(T seed, Function<? super T, ? extends T> stepper) { return new AbstractIterator<T>() { T next = seed; @Override protected void computeNext() { if (next == null) { done(); return; } setNext(next); next = stepper.apply(next); } }; } public static <T> boolean anyMatch(Iterator<? extends T> iterator, Predicate<? super T> pred) { return matches(iterator, pred, MATCH_ANY); } public static <T> boolean allMatch(Iterator<? extends T> iterator, Predicate<? super T> pred) { return matches(iterator, pred, MATCH_ALL); } public static <T> boolean noneMatch(Iterator<? extends T> iterator, Predicate<? super T> pred) { return matches(iterator, pred, MATCH_NONE); } private static <T> boolean matches(Iterator<? extends T> iterator, Predicate<? super T> pred, int matchKind) { final boolean kindAny = matchKind == MATCH_ANY; final boolean kindAll = matchKind == MATCH_ALL; while (iterator.hasNext()) { final T value = iterator.next(); final boolean match = pred.test(value); if (match ^ kindAll) { // xor return kindAny && match; } } return !kindAny; } public static <T> Iterator<T> singletonIterator(T value) { class SingletonIterator implements Iterator<T> { private boolean done; @Override public boolean hasNext() { return !done; } @Override public T next() { if (done) { throw new NoSuchElementException(); } done = true; return value; } @Override public void forEachRemaining(Consumer<? super T> action) { action.accept(value); } } return new SingletonIterator(); } public static <T> Iterable<T> asReversed(final List<T> lst) { return () -> new Iterator<T>() { ListIterator<T> li = lst.listIterator(lst.size()); @Override public boolean hasNext() { return li.hasPrevious(); } @Override public T next() { return li.previous(); } @Override public void remove() { li.remove(); } }; } public static <T> Stream<T> toStream(Iterator<? extends T> iter) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, 0), false); } public abstract static class AbstractIterator<T> implements Iterator<T> { private State state = State.NOT_READY; private T next = null; @Override public boolean hasNext() { switch (state) { case DONE: return false; case READY: return true; default: state = null; computeNext(); if (state == null) { throw new IllegalStateException("Should have called done or setNext"); } return state == State.READY; } } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } state = State.NOT_READY; return next; } protected final void setNext(T t) { next = t; state = State.READY; } protected final void done() { state = State.DONE; } protected abstract void computeNext(); enum State { READY, NOT_READY, DONE } @Deprecated @Override public final void remove() { throw new UnsupportedOperationException(); } } public abstract static class AbstractPausingIterator<T> extends AbstractIterator<T> { private int numYielded = 0; private T currentValue; @Override public T next() { T next = super.next(); currentValue = next; prepareViewOn(next); numYielded++; return next; } protected void prepareViewOn(T current) { // to be overridden } protected final int getIterationCount() { return numYielded; } protected T getCurrentValue() { ensureReadable(); return currentValue; } protected void ensureReadable() { if (numYielded == 0) { throw new IllegalStateException("No values were yielded, should have called next"); } } } }
13,622
26.521212
149
java
pmd
pmd-master/pmd-java/src/test/resources/net/sourceforge/pmd/ast/FullTypeAnnotations.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ import java.io.File; import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.NonNull; /** * Type annotation syntax. * * See https://checkerframework.org/jsr308/java-annotation-design.html * for precise spec including BNF. * * https://checkerframework.org/jsr308/java-annotation-design.html#type-names * is particularly interesting */ public class FullTypeAnnotations { private String myString; // A type annotation appears before the type’s simple name, as in @NonNull String or java.lang.@NonNull String. // Here are examples: // for generic typearguments to parameterized classes: Map<@NonNull String, @NonEmpty List<@Readonly Document>> files; // for generic type arguments in a generic method or constructor invocation: { o.<@NonNull String>m("..."); } // for type parameterbounds, including wildcard bounds: class Folder<F extends @Existing File> { } Collection<? super @Existing File> field; // for class inheritance: class UnmodifiableList<T> implements @Readonly List<@Readonly T> { } // for throws clauses: void monitorTemperature() throws @Critical TemperatureException { } // for constructor invocationresults(that is, for object creation): { new @Interned MyObject(); new @NonEmpty @Readonly List<String>(myNonEmptyStringSet); myVar.new @Tainted NestedClass(); // For generic constructors(JLS §8.8.4),the annotation follows the explicit type arguments (JLS §15.9): new <String>@Interned MyObject(); } // for nested types: Map.@NonNull Entry mapField; // for casts: { myString = (@NonNull String) myObject; x = (@A Type1 & @B Type2) y; // It is not permitted to omit the Java type, as in // myString = (@NonNull) myObject;. } // for type tests: boolean isNonNull = myString instanceof @NonNull String; // It is not permitted to omit the Java type, as in myString instanceof @NonNull. // for method and constructor references, including their receiver, // receiver type arguments, and type arguments to the method or // constructor itself: { Supplier<@Vernal Date> sup = @Vernal Date::getDay; sup = List<@English String>::size; sup = Arrays::<@NonNegative Integer>sort; } // The annotation on a given array level prefixes the brackets that // introduce that level. To declare a non-empty array of English-language // strings, write @English String @NonEmpty []. The varargs syntax “...” // is treated analogously to array brackets and may also be prefixed by // an annotation. Here are examples: @Readonly Document[][] docs1 = new @Readonly Document[2][12]; // array of arrays of read-only documents Document @Readonly [][] docs2 = new Document@Readonly[2][12]; // read-only array of arrays of documents Document[] @Readonly [] docs3 = new Document[2]@Readonly[12]; // array of read-only arrays of documents Document[] docs4@Readonly[] = new Document@Readonly[2][12]; // read-only array of arrays of documents Document @Readonly [] docs5[] = new Document[2]@Readonly[12]; // array of read-only arrays of documents { // all of the above for local vars @Readonly Document[][] docs1 = new @Readonly Document[2][12]; // array of arrays of read-only documents Document @Readonly [][] docs2 = new Document@Readonly[2][12]; // read-only array of arrays of documents Document[] @Readonly [] docs3 = new Document[2]@Readonly[12]; // array of read-only arrays of documents Document[] docs4@Readonly[] = new Document@Readonly[2][12]; // read-only array of arrays of documents Document @Readonly [] docs5[] = new Document[2]@Readonly[12]; // array of read-only arrays of documents } class MyClass { public String toString(@Readonly MyClass this) { } public boolean equals(Object @Readonly ... other) @K[][]{ } MyClass(Object @Readonly [] @ß... other) { } } }
4,195
31.78125
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/JavaLanguageModule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java; import static net.sourceforge.pmd.util.CollectionUtil.listOf; import java.util.List; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageModuleBase; import net.sourceforge.pmd.lang.LanguageProcessor; import net.sourceforge.pmd.lang.LanguagePropertyBundle; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.java.internal.JavaLanguageProcessor; import net.sourceforge.pmd.lang.java.internal.JavaLanguageProperties; /** * Created by christoferdutz on 20.09.14. */ public class JavaLanguageModule extends LanguageModuleBase { public static final String NAME = "Java"; public static final String TERSE_NAME = "java"; @InternalApi public static final List<String> EXTENSIONS = listOf("java"); public JavaLanguageModule() { super(LanguageMetadata.withId(TERSE_NAME).name(NAME).extensions(EXTENSIONS.get(0)) .addVersion("1.3") .addVersion("1.4") .addVersion("1.5", "5") .addVersion("1.6", "6") .addVersion("1.7", "7") .addVersion("1.8", "8") .addVersion("9", "1.9") .addVersion("10", "1.10") .addVersion("11") .addVersion("12") .addVersion("13") .addVersion("14") .addVersion("15") .addVersion("16") .addVersion("17") .addVersion("18") .addVersion("19") .addVersion("19-preview") .addDefaultVersion("20") // 20 is the default .addVersion("20-preview")); } @Override public LanguagePropertyBundle newPropertyBundle() { return new JavaLanguageProperties(); } @Override public LanguageProcessor createProcessor(LanguagePropertyBundle bundle) { return new JavaLanguageProcessor((JavaLanguageProperties) bundle); } public static Language getInstance() { return LanguageRegistry.PMD.getLanguageByFullName(NAME); } }
2,543
35.869565
90
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JAccessibleElementSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.reflect.Modifier; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents declarations having access modifiers common to {@link JFieldSymbol}, * {@link JClassSymbol}, {@link JMethodSymbol}, and {@link JConstructorSymbol}. * * @since 7.0.0 */ public interface JAccessibleElementSymbol extends JElementSymbol, AnnotableSymbol { /** * Conventional return value of {@link #getPackageName()} for * primitive types. */ String PRIMITIVE_PACKAGE = "java.lang"; /** * Returns the modifiers of the element represented by this symbol, * as decodable by the standard {@link Modifier} API. */ int getModifiers(); default boolean isStatic() { return Modifier.isStatic(getModifiers()); } /** * Returns the class that directly encloses this declaration. * This is equivalent to {@link Class#getEnclosingClass()}. * Returns null if this is a top-level type declaration. * * <p>This is necessarily an already resolved symbol, because * 1. if it's obtained from reflection, then the enclosing class is available * 2. if it's obtained from an AST, then the enclosing class is in the same source file so we can * know about it */ @Nullable JClassSymbol getEnclosingClass(); /** * Returns the name of the package this element is declared in. This * recurses into the enclosing elements if needed. If this is an array * symbol, returns the package name of the element symbol. If this is * a primitive type, returns {@value #PRIMITIVE_PACKAGE}. * * <p>This is consistent with Java 9's {@code getPackageName()}. */ @NonNull String getPackageName(); }
1,944
28.029851
101
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/package-info.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * Prototype of a new symbol resolution framework * that inter-operates cleanly with type resolution. * * @see net.sourceforge.pmd.lang.java.symbols.JElementSymbol * @see net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable * @see net.sourceforge.pmd.lang.java.symbols.SymbolResolver */ @Experimental package net.sourceforge.pmd.lang.java.symbols; import net.sourceforge.pmd.annotation.Experimental;
504
27.055556
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JLocalVariableSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; /** * Represents all use cases of {@link ASTVariableDeclaratorId} except field declarations. * Method formal parameter symbols extend this interface. * * @since 7.0.0 */ public interface JLocalVariableSymbol extends JVariableSymbol { @Override default <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) { return visitor.visitLocal(this, param); } }
590
23.625
89
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JTypeParameterSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.reflect.Modifier; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.ASTTypeParameter; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.JTypeVar; /** * Represents the declaration of a type variable, ie a type parameter. Type variables are reference * types, but not class or interface types. They're also not declared with the same node. For those * reasons this type of references is distinct from {@link JClassSymbol}. * * @since 7.0.0 */ public interface JTypeParameterSymbol extends JTypeDeclSymbol, BoundToNode<ASTTypeParameter> { /** * Returns the {@link JClassSymbol} or {@link JMethodSymbol} which declared * this type parameter. */ JTypeParameterOwnerSymbol getDeclaringSymbol(); JTypeVar getTypeMirror(); /** * Returns the upper bound of this type variable. This may be an * intersection type. If the variable is unbounded, returns Object. */ JTypeMirror computeUpperBound(); @Override @NonNull default String getPackageName() { return getDeclaringSymbol().getPackageName(); } @Override default int getModifiers() { return getDeclaringSymbol().getModifiers() | Modifier.ABSTRACT | Modifier.FINAL; } @Override @NonNull default JClassSymbol getEnclosingClass() { JTypeParameterOwnerSymbol ownerSymbol = getDeclaringSymbol(); return ownerSymbol instanceof JClassSymbol ? (JClassSymbol) ownerSymbol : ownerSymbol.getEnclosingClass(); } @Override default <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) { return visitor.visitTypeParam(this, param); } }
1,892
26.838235
114
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/AnnotWrapper.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Objects; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot; import net.sourceforge.pmd.lang.java.symbols.internal.SymbolEquality; import net.sourceforge.pmd.lang.java.symbols.internal.SymbolToStrings; import net.sourceforge.pmd.lang.java.types.TypeSystem; /** * Wraps an instance of a JVM {@link Annotation} and provide the same API as {@link SymAnnot}. */ final class AnnotWrapper implements SymAnnot { private final Annotation annotation; private final Class<? extends Annotation> annotationClass; private final JClassSymbol annotationClassSymbol; private AnnotWrapper(JClassSymbol annotationClassSymbol, @NonNull Annotation annotation) { this.annotationClassSymbol = annotationClassSymbol; this.annotation = annotation; this.annotationClass = annotation.annotationType(); } static SymAnnot wrap(TypeSystem ts, @NonNull Annotation annotation) { JClassSymbol sym = ts.getClassSymbol(annotation.annotationType()); if (sym == null) { return null; } return new AnnotWrapper(sym, annotation); } @Override public @NonNull JClassSymbol getAnnotationSymbol() { return annotationClassSymbol; } @Override public @Nullable SymbolicValue getAttribute(String attrName) { return Arrays.stream(annotationClass.getDeclaredMethods()) .filter(it -> it.getName().equals(attrName) && it.getParameterCount() == 0) .map(it -> { try { Object result = it.invoke(annotation); return SymbolicValue.of(annotationClassSymbol.getTypeSystem(), result); } catch (Exception ignored) { return null; } }) .filter(Objects::nonNull) .findAny().orElse(null); } @Override public boolean valueEquals(Object o) { return annotation.equals(o); } @Override public boolean equals(Object o) { return SymbolEquality.ANNOTATION.equals(this, o); } @Override public int hashCode() { return SymbolEquality.ANNOTATION.hash(this); } @Override public String toString() { return SymbolToStrings.FAKE.toString(this); } }
2,721
31.404762
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/SymbolResolver.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import static net.sourceforge.pmd.util.CollectionUtil.listOf; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Resolves symbols from their global name. This abstracts over whether * we're looking on a classpath, in a file tree, in a serialized index, etc. */ public interface SymbolResolver { /** * Resolves a class symbol from its canonical name. Periods ('.') will * not be interpreted as nested-class separators, so this performs at * most one classloader lookup. Note that external symbol resolvers * do not need to implement lookup for primitive types, for local * and anonymous classes, or for array classes. This is handled by * the AST implementation or by the type system. Looking up such symbols * is undefined behaviour. */ @Nullable JClassSymbol resolveClassFromBinaryName(@NonNull String binaryName); /** * Resolves a class symbol from its canonical name. Periods ('.') may * be interpreted as nested-class separators, so for n segments, this * performs at most n classloader lookups. */ @Nullable default JClassSymbol resolveClassFromCanonicalName(@NonNull String canonicalName) { JClassSymbol symbol = resolveClassFromBinaryName(canonicalName); if (symbol != null) { return symbol; } int lastDotIdx = canonicalName.lastIndexOf('.'); if (lastDotIdx < 0) { return null; } else { JClassSymbol outer = resolveClassFromCanonicalName(canonicalName.substring(0, lastDotIdx)); if (outer != null) { String innerName = canonicalName.substring(lastDotIdx + 1); return outer.getDeclaredClass(innerName); } } return null; } /** * Produce a symbol resolver that asks the given resolvers in order. * * @param first First resolver * @param others Rest of the resolvers */ static SymbolResolver layer(SymbolResolver first, SymbolResolver... others) { assert first != null : "Null first table"; assert others != null : "Null array"; assert !ArrayUtils.contains(others, null) : "Null component"; return new SymbolResolver() { private final List<SymbolResolver> stack = listOf(first, others); @Override public @Nullable JClassSymbol resolveClassFromBinaryName(@NonNull String binaryName) { for (SymbolResolver resolver : stack) { JClassSymbol sym = resolver.resolveClassFromBinaryName(binaryName); if (sym != null) { return sym; } } return null; } }; } }
3,046
33.625
103
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JConstructorSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; /** * Represents a constructor declaration. * * @since 7.0.0 */ public interface JConstructorSymbol extends JExecutableSymbol, BoundToNode<ASTConstructorDeclaration> { /** Common dummy name for constructor symbols. */ String CTOR_NAME = "new"; /** For constructors, this returns the special name {@value CTOR_NAME}. */ @Override default String getSimpleName() { return CTOR_NAME; } @Override default <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) { return visitor.visitCtor(this, param); } }
775
21.171429
103
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/BoundToNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.JavaNode; /** * Constrains the return type of getDeclaration. This is used to avoid having * a type parameter directly on {@link JElementSymbol}, which would get * in the way most of the time. Not visible outside this package, it's just * a code organisation device. * * @since 7.0.0 */ interface BoundToNode<N extends JavaNode> extends JElementSymbol { @Override default @Nullable N tryGetNode() { return null; } }
686
22.689655
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JFormalParamSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; /** * Represents a formal parameter of a {@link JExecutableSymbol}. * * @since 7.0.0 */ public interface JFormalParamSymbol extends JLocalVariableSymbol { /** Returns the symbol declaring this parameter. */ JExecutableSymbol getDeclaringSymbol(); @Override default <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) { return visitor.visitFormal(this, param); } }
545
21.75
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JFieldSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.reflect.Modifier; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents a field declaration. * * @since 7.0.0 */ public interface JFieldSymbol extends JVariableSymbol, JAccessibleElementSymbol { @Override default boolean isField() { return true; } /** Returns true if this field is an enum constant. */ boolean isEnumConstant(); @Override default boolean isFinal() { return Modifier.isFinal(getModifiers()); } /** * Returns the compile-time value of this field if this is a compile-time constant. * Otherwise returns null. */ default @Nullable Object getConstValue() { return null; } @Override @NonNull JClassSymbol getEnclosingClass(); @Override @NonNull default String getPackageName() { return getEnclosingClass().getPackageName(); } @Override default <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) { return visitor.visitField(this, param); } }
1,250
20.20339
87
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JTypeDeclSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.types.JTypeMirror; /** * A symbol that declares a type. These include * <ul> * <li>{@linkplain JClassSymbol class, interface, array & primitive symbols}</li> * <li>{@linkplain JTypeParameterSymbol type parameters symbols}</li> * </ul> * * <p>Note: type symbols are not <i>types</i>, they <i>declare</i> types. * See {@link JTypeMirror#getSymbol()} for more details. * * @since 7.0.0 */ public interface JTypeDeclSymbol extends JElementSymbol, JAccessibleElementSymbol { /** * Returns true if this class is a symbolic reference to an unresolved * class. In that case no information about the symbol are known except * its name, and the accessors of this class return default values. * * <p>This kind of symbol is introduced to allow for some best-effort * symbolic resolution. For example in: * <pre>{@code * import org.Bar; * * Bar foo = new Bar(); * }</pre> * and supposing {@code org.Bar} is not on the classpath. The type * of {@code foo} is {@code Bar}, which we can qualify to {@code org.Bar} thanks to the * import (via symbol tables, and without even querying the classpath). * Even though we don't know what members {@code org.Bar} has, a * test for {@code typeIs("org.Bar")} would succeed with certainty, * so it makes sense to preserve the name information and not give * up too early. * * <p>Note that unresolved types are always created from an unresolved * <i>canonical name</i>, so they can't be just <i>any</i> type. For example, * they can't be array types, nor local classes (since those are lexically * scoped, so always resolvable), nor anonymous classes (can only be referenced * on their declaration site), type variables, etc. */ @Override default boolean isUnresolved() { return false; } /** * Returns the simple name of this class, as specified by * {@link Class#getSimpleName()}. */ @Override @NonNull String getSimpleName(); /** * This returns true if this is an interface. Annotation types are * also interface types. */ default boolean isInterface() { return false; } }
2,472
31.973333
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JExecutableSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.Substitution; /** * Common supertype for {@linkplain JMethodSymbol method} * and {@linkplain JConstructorSymbol constructor symbols}. */ public interface JExecutableSymbol extends JAccessibleElementSymbol, JTypeParameterOwnerSymbol { /** * Returns the formal parameters this executable declares. These are * only non-synthetic parameters. For example, a constructor for an * inner non-static class will not reflect a parameter for the enclosing * instance. */ List<JFormalParamSymbol> getFormalParameters(); default boolean isDefaultMethod() { // Default methods are public non-abstract instance methods // declared in an interface. return this instanceof JMethodSymbol && (getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC && getEnclosingClass().isInterface(); } /** Returns true if the last formal parameter is a varargs parameter. */ boolean isVarargs(); /** * Returns the number of formal parameters expected. This must be the * length of {@link #getFormalParameters()} but if it can be implemented * without creating the formal parameters, it should. * * <p>A varargs parameter counts as a single parameter. */ int getArity(); /** * Return the receiver type with all type annotations, when viewed * under the given substitution. Return null if this method * {@linkplain #hasReceiver() has no receiver}. * * @throws IllegalArgumentException If the argument is not the receiver type of this type. */ @Nullable JTypeMirror getAnnotatedReceiverType(Substitution subst); /** * Return true if this method needs to be called on a receiver instance. * This is not the case if the method is static, or a constructor of an * outer or static class. */ default boolean hasReceiver() { if (isStatic()) { return false; } if (this instanceof JConstructorSymbol) { return !getEnclosingClass().isStatic() && getEnclosingClass().getEnclosingClass() != null; } return true; } /** * Returns the class symbol declaring this method or constructor. * This is similar to {@link Constructor#getDeclaringClass()}, resp. * {@link Method#getDeclaringClass()}. Never null. */ @Override @NonNull JClassSymbol getEnclosingClass(); @Override default @NonNull String getPackageName() { return getEnclosingClass().getPackageName(); } /** * Returns the types of the formal parameters, when viewed under the * given substitution. The returned list has one item for each formal. * * @see #getFormalParameters() */ List<JTypeMirror> getFormalParameterTypes(Substitution subst); /** * Returns the types of the thrown exceptions, when viewed under the * given substitution. */ List<JTypeMirror> getThrownExceptionTypes(Substitution subst); }
3,555
30.192982
108
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JElementSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeSystem; /** * Represents a named program element that can be referred to by simple name. Abstracts over * whether the declaration is in the analysed file or not, using reflection when it's not. * * <p>This type hierarchy is probably not directly relevant to users writing * rules. It's mostly intended to unify the representation of type resolution * and symbol analysis. * * @since 7.0.0 */ @Experimental @InternalApi public interface JElementSymbol { /** * Gets the name with which this declaration may be referred to, * eg the name of the method, or the simple name of the class. * * @return the name */ String getSimpleName(); /** * Returns true if the simple name of this symbol is the same as the given * name. * * @param name Simple name * * @throws NullPointerException If the parameter is null */ default boolean nameEquals(@NonNull String name) { // implicit null check of the parameter return name.equals(getSimpleName()); } /** * Returns the type system that created this symbol. The symbol uses * this instance to create new types, for example to reflect its * superclass. */ TypeSystem getTypeSystem(); /** * Returns true if this symbol is a placeholder, created to fill-in * an unresolved reference. Depending on the type of this symbol, * this may be: * <ul> * <li>An unresolved class (more details on {@link JTypeDeclSymbol#isUnresolved()}) * <li>An unresolved field * <li>An unresolved method or constructor. Note that we cheat and * represent them only with the constant {@link TypeSystem#UNRESOLVED_METHOD TypeSystem.UNRESOLVED_METHOD.getSymbol()}, * which may not match its usage site in either name, formal parameters, * location, etc. * </ul> * * <p>We try to recover some information about the missing * symbol from the references we found, currently this includes * only the number of type parameters of an unresolved class. * * <p>Rules should care about unresolved symbols to avoid false * positives or logic errors. The equivalent for {@linkplain JTypeMirror types} * is {@link TypeSystem#UNKNOWN}. * * <p>The following symbols are never unresolved, because they are * lexically scoped: * <ul> * <li>{@linkplain JTypeParameterSymbol type parameters} * <li>{@linkplain JLocalVariableSymbol local variables} * <li>{@linkplain JFormalParamSymbol formal parameters} * <li>local classes, anonymous classes * </ul> */ default boolean isUnresolved() { return false; } /** * Returns the node that declares this symbol. Eg for {@link JMethodSymbol}, * it's an {@link ASTMethodDeclaration}. Will only return non-null * if the symbol is declared in the file currently being analysed. */ default @Nullable JavaNode tryGetNode() { return null; } /** * Two symbols representing the same program element should be equal. * So eg two {@link JClassSymbol}, even if their implementation class * is different, should compare publicly observable properties (their * binary name is enough). {@code #hashCode()} must of course be consistent * with this contract. * * <p>Symbols should only be compared using this method, never with {@code ==}, * because their unicity is not guaranteed. * * @param o Comparand * * @return True if the other is a symbol for the same program element */ @Override boolean equals(Object o); /** * Dispatch to the appropriate visit method of the visitor and returns its result. */ <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param); }
4,403
32.618321
123
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JClassSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.List; import java.util.Optional; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.pcollections.HashTreePSet; import org.pcollections.PSet; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot; import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymEnum; import net.sourceforge.pmd.lang.java.types.JArrayType; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JPrimitiveType; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.Substitution; /** * Abstraction over a {@link Class} instance. This is not a type, it's * the *declaration* of a type. For example, a class symbol representing * a generic class can provide access to the formal type parameters, but * the symbol does not represent a specific parametrization of a type. * * <p>Class symbols represent the full range of types represented by {@link Class}: * classes, interfaces, arrays, and primitives. This excludes type variables, * intersection types, parameterized types, wildcard types, etc., which are only * compile-time constructs. * * <p>Class symbols are used to back {@link JClassType}, {@link JArrayType}, * and {@link JPrimitiveType}. See {@link JTypeMirror#getSymbol()}. * * @since 7.0.0 */ public interface JClassSymbol extends JTypeDeclSymbol, JTypeParameterOwnerSymbol, BoundToNode<ASTAnyTypeDeclaration> { /** * Returns the binary name of this type, as specified by the JLS: * <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html#jls-13.1">the JLS</a>. * For array types this returns the binary name of the component followed by "[]". * This differs from {@link Class#getName()}, which for array types outputs an * <i>internal name</i>. * * <p>For example: * <pre>{@code * int.class.getName() == "int" * int[].class.getName() == "[I" * String.class.getName() == "java.lang.String" * String[].class.getName() == "[Ljava.lang.String;" * }</pre> * whereas * <pre>{@code * symbolOf(int.class).getBinaryName() == "int" * symbolOf(int[].class).getBinaryName() == "int[]" * symbolOf(String.class).getBinaryName() == "java.lang.String" * symbolOf(String[].class).getBinaryName() == "java.lang.String[]" * }</pre> */ @NonNull String getBinaryName(); /** * Returns the simple name of this class, as specified by * {@link Class#getCanonicalName()}. */ @Nullable String getCanonicalName(); /** * Returns the method or constructor this symbol is declared in, if * it represents a {@linkplain #isLocalClass() local class declaration}. * * <p>Notice, that this returns null also if this class is local to * a class or instance initializer. */ @Nullable JExecutableSymbol getEnclosingMethod(); @Override default JTypeParameterOwnerSymbol getEnclosingTypeParameterOwner() { JExecutableSymbol enclosingMethod = getEnclosingMethod(); return enclosingMethod != null ? enclosingMethod : getEnclosingClass(); } /** * Returns the member classes declared directly in this class. * * @see Class#getDeclaredClasses() */ List<JClassSymbol> getDeclaredClasses(); /** Returns a class with the given name defined in this class. */ @Nullable default JClassSymbol getDeclaredClass(String name) { for (JClassSymbol klass : getDeclaredClasses()) { if (klass.nameEquals(name)) { return klass; } } return null; } /** * Returns the methods declared directly in this class. * <i>This excludes bridges and other synthetic methods.</i> * * <p>For an array type T[], to the difference of {@link Class}, * this method returns a one-element list with the {@link Object#clone()} * method, as if declared like so: {@code public final T[] clone() {...}}. * * @see Class#getDeclaredMethods() */ List<JMethodSymbol> getDeclaredMethods(); /** * Returns the constructors declared by this class. * <i>This excludes synthetic constructors.</i> * * <p>For an array type T[], and to the difference of {@link Class}, * this should return a one-element list with a constructor * having the same modifiers as the array type, and a single * {@code int} parameter. * * @see Class#getDeclaredConstructors() */ List<JConstructorSymbol> getConstructors(); /** * Returns the fields declared directly in this class. * <i>This excludes synthetic fields.</i> * * <p>For arrays, and to the difference of {@link Class}, * this should return a one-element list with the * {@code public final int length} field. * * @see Class#getDeclaredFields() */ List<JFieldSymbol> getDeclaredFields(); /** Returns a field with the given name defined in this class. */ @Nullable default JFieldSymbol getDeclaredField(String name) { for (JFieldSymbol field : getDeclaredFields()) { if (field.nameEquals(name)) { return field; } } return null; } /** * Returns a list with all enum constants. If this symbol does * not represent an enum, returns an empty set. The returned list * is a subset of {@link #getDeclaredFields()}. The order of fields * denotes the normal order of enum constants. */ default @NonNull List<JFieldSymbol> getEnumConstants() { return Collections.emptyList(); } /** Returns the list of super interface types, under the given substitution. */ List<JClassType> getSuperInterfaceTypes(Substitution substitution); /** Returns the superclass type, under the given substitution. */ @Nullable JClassType getSuperclassType(Substitution substitution); /** * Returns the superclass symbol if it exists. Returns null if this * class represents the class {@link Object}, or a primitive type. * If this symbol is an interface, returns the symbol for {@link Object}. */ @Nullable JClassSymbol getSuperclass(); /** Returns the direct super-interfaces of this class or interface symbol. */ List<JClassSymbol> getSuperInterfaces(); default boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } /** Returns the component symbol, returns null if this is not an array. */ @Nullable JTypeDeclSymbol getArrayComponent(); boolean isArray(); boolean isPrimitive(); boolean isEnum(); boolean isRecord(); boolean isAnnotation(); boolean isLocalClass(); boolean isAnonymousClass(); /** * Return the simple names of all annotation attributes. If this * is not an annotation type, return an empty set. */ default PSet<String> getAnnotationAttributeNames() { return HashTreePSet.empty(); } /** * Return the default value of the attribute if this is an annotation type * with a default. Return null if this is not an annotation type, if there * is no such attribute, or the attribute has no default value. If the name * is in the {@linkplain #getAnnotationAttributeNames() attribute name set}, * then the null return value can only mean that the attribute exists but has * no default value. * * @param attrName Attribute name */ default @Nullable SymbolicValue getDefaultAnnotationAttributeValue(String attrName) { if (!isAnnotation()) { return null; } for (JMethodSymbol m : getDeclaredMethods()) { if (m.nameEquals(attrName) && m.isAnnotationAttribute()) { return m.getDefaultAnnotationValue(); // nullable } } return null; } /** * Returns the retention policy of this annotation, if this is an * annotation symbol. Otherwise returns null. */ default @Nullable RetentionPolicy getAnnotationRetention() { if (!isAnnotation()) { return null; } return Optional.ofNullable(getDeclaredAnnotation(Retention.class)) .map(annot -> annot.getAttribute("value")) .filter(value -> value instanceof SymEnum) .map(value -> ((SymEnum) value).toEnum(RetentionPolicy.class)) .orElse(RetentionPolicy.CLASS); } /** * Return whether annotations of this annotation type apply to the * given construct, as per the {@link Target} annotation. Return * false if this is not an annotation. */ default boolean annotationAppliesTo(ElementType elementType) { if (!isAnnotation()) { return false; } SymAnnot target = getDeclaredAnnotation(Target.class); if (target == null) { // If an @Target meta-annotation is not present on an annotation type T, // then an annotation of type T may be written as a modifier // for any declaration except a type parameter declaration. return elementType != ElementType.TYPE_PARAMETER; } return target.attributeContains("value", elementType).isTrue(); } // todo isSealed + getPermittedSubclasses // (isNonSealed is not so useful I think) /** * This returns true if this is not an interface, primitive or array. */ default boolean isClass() { return !isInterface() && !isArray() && !isPrimitive(); } /** * Returns the toplevel class containing this class. If this is a * toplevel class, returns this. */ default @NonNull JClassSymbol getNestRoot() { JClassSymbol e = this; while (e.getEnclosingClass() != null) { e = e.getEnclosingClass(); } return e; } @Override default <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) { return visitor.visitClass(this, param); } }
10,715
32.176471
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JTypeParameterOwnerSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.types.JTypeVar; import net.sourceforge.pmd.lang.java.types.LexicalScope; /** * Represents a declaration that can declare type parameters, * {@literal i.e.} {@link JClassSymbol} or {@link JMethodSymbol}. * * @since 7.0.0 */ public interface JTypeParameterOwnerSymbol extends JAccessibleElementSymbol { /** * Returns an unmodifiable list of the type variables declared by * this symbol. */ List<JTypeVar> getTypeParameters(); /** * Returns the lexical scope of this symbol. This is little more than * a map of all the type parameters that are in scope at the point * of this declaration, indexed by their name. For example, for a * method, this includes the type parameters of the method, the type * parameters of its enclosing class, and all the other enclosing * classes. */ default LexicalScope getLexicalScope() { JTypeParameterOwnerSymbol encl = getEnclosingTypeParameterOwner(); LexicalScope base = encl != null ? encl.getLexicalScope() : LexicalScope.EMPTY; return base.andThen(getTypeParameters()); } default int getTypeParameterCount() { return getTypeParameters().size(); } default boolean isGeneric() { return getTypeParameterCount() > 0; } /** * Returns the {@link JClassSymbol#getEnclosingMethod() enclosing method} or * the {@link #getEnclosingClass() enclosing class}, in that order * of priority. */ @Nullable default JTypeParameterOwnerSymbol getEnclosingTypeParameterOwner() { // may be overridden to add getEnclosingMethod return getEnclosingClass(); } }
1,925
27.746269
87
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/SymbolVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; /** * Visitor over symbols. */ public interface SymbolVisitor<R, P> { R visitSymbol(JElementSymbol sym, P p); default R visitTypeDecl(JTypeDeclSymbol sym, P param) { return visitSymbol(sym, param); } /** Delegates to {@link #visitTypeDecl(JTypeDeclSymbol, Object) visitTypeDecl}. */ default R visitClass(JClassSymbol sym, P param) { return visitTypeDecl(sym, param); } /** Delegates to {@link #visitClass(JClassSymbol, Object) visitClass}. */ default R visitArray(JClassSymbol sym, JTypeDeclSymbol component, P param) { return visitClass(sym, param); } /** Delegates to {@link #visitTypeDecl(JTypeDeclSymbol, Object) visitTypeDecl}. */ default R visitTypeParam(JTypeParameterSymbol sym, P param) { return visitTypeDecl(sym, param); } default R visitExecutable(JExecutableSymbol sym, P param) { return visitSymbol(sym, param); } /** Delegates to {@link #visitExecutable(JExecutableSymbol, Object) visitExecutable}. */ default R visitCtor(JConstructorSymbol sym, P param) { return visitExecutable(sym, param); } /** Delegates to {@link #visitExecutable(JExecutableSymbol, Object) visitExecutable}. */ default R visitMethod(JMethodSymbol sym, P param) { return visitExecutable(sym, param); } default R visitVariable(JVariableSymbol sym, P param) { return visitSymbol(sym, param); } /** Delegates to {@link #visitVariable(JVariableSymbol, Object) visitVariable}. */ default R visitField(JFieldSymbol sym, P param) { return visitVariable(sym, param); } /** Delegates to {@link #visitVariable(JVariableSymbol, Object) visitVariable}. */ default R visitLocal(JLocalVariableSymbol sym, P param) { return visitVariable(sym, param); } /** Delegates to {@link #visitLocal(JLocalVariableSymbol, Object) visitLocal}. */ default R visitFormal(JFormalParamSymbol sym, P param) { return visitLocal(sym, param); } }
2,165
29.942857
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/AnnotableSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.annotation.Annotation; import org.pcollections.HashTreePSet; import org.pcollections.PSet; import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot; /** * A symbol that can have annotations. */ public interface AnnotableSymbol extends JElementSymbol { /** * Return the valid symbolic annotations defined on this symbol. * Annotations that could not be converted, eg because * they are written with invalid code, are discarded, so * this might not match the annotations on a node one to one. */ default PSet<SymAnnot> getDeclaredAnnotations() { return HashTreePSet.empty(); } /** * Return an annotation of the given type, if it is present on this declaration. * This does not consider inherited annotations. */ default SymbolicValue.SymAnnot getDeclaredAnnotation(Class<? extends Annotation> type) { for (SymAnnot a : getDeclaredAnnotations()) { if (a.isOfType(type)) { return a; } } return null; } /** * Return true if an annotation of the given type is present on this declaration. */ default boolean isAnnotationPresent(Class<? extends Annotation> type) { return getDeclaredAnnotation(type) != null; } }
1,446
27.372549
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JVariableSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.Substitution; /** * Reference to a variable, ie {@linkplain JLocalVariableSymbol local variable}, * {@linkplain JFormalParamSymbol formal parameter}, or {@linkplain JFieldSymbol field}. * * @since 7.0.0 */ public interface JVariableSymbol extends BoundToNode<ASTVariableDeclaratorId>, AnnotableSymbol { /** * Returns true if this is a field symbol. * * @see JFieldSymbol */ default boolean isField() { return false; } /** * Returns true if this declaration is declared final. * This takes implicit modifiers into account. */ boolean isFinal(); /** Returns the type of this value, under the given substitution. */ JTypeMirror getTypeMirror(Substitution subst); }
1,046
25.175
96
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/JMethodSymbol.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.reflect.Modifier; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.Substitution; /** * Reference to a method. * * @since 7.0.0 */ public interface JMethodSymbol extends JExecutableSymbol, BoundToNode<ASTMethodDeclaration> { // note that for now, bridge methods are filtered out from the ASM // symbols, and bridge methods are not reflected by the AST symbols boolean isBridge(); @Override default boolean isStatic() { return Modifier.isStatic(getModifiers()); } /** Returns the return type under the given substitution. */ JTypeMirror getReturnType(Substitution subst); /** * Returns the default value, if this is a constant method. See * {@link SymbolicValue} for current limitations */ default @Nullable SymbolicValue getDefaultAnnotationValue() { return null; } /** * Return whether this method defines an attribute of the enclosing * annotation type. */ default boolean isAnnotationAttribute() { return !isStatic() && getEnclosingClass().isAnnotation() && getArity() == 0; } @Override default <R, P> R acceptVisitor(SymbolVisitor<R, P> visitor, P param) { return visitor.visitMethod(this, param); } }
1,580
24.918033
93
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValue.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; import java.lang.annotation.Annotation; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.AnnotationUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.reflect.MethodUtils; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.pcollections.PSet; import net.sourceforge.pmd.lang.java.symbols.internal.asm.ClassNamesUtil; import net.sourceforge.pmd.lang.java.types.TypeSystem; import net.sourceforge.pmd.util.OptionalBool; /** * Structure to represent constant values of annotations symbolically. * Annotations may contain: * <ul> * <li>Primitive or string values: {@link SymValue} * <li>Enum constants: {@link SymEnum} * <li>Class instances: {@link SymClass} * <li>Other annotations: {@link SymAnnot} * <li>Arrays of the above, of dimension 1: {@link SymArray} * </ul> * * <p>Any other values, including the null reference, are unsupported and * cannot be represented by this API. * * <p>Currently the public API allows comparing the values to an actual * java value that you compiled against ({@link #valueEquals(Object)}). * This may be improved later to allow comparing values without needing * them in the compile classpath. * * <p>This is a sealed interface and should not be implemented by clients. * * <p>Note: the point of this api is to enable comparisons between values, * not deep introspection into values. This is why there are very few getter * methods, except in {@link SymAnnot}, which is the API point used by * {@link AnnotableSymbol}. */ public interface SymbolicValue { /** * Returns true if this symbolic value represents the same value as * the given object. If the parameter is null, returns false. */ boolean valueEquals(Object o); /** * Returns true if this value is equal to the other one. The parameter * must be a {@link SymbolicValue} of the same type. Use {@link #valueEquals(Object)} * to compare to a java object. */ @Override boolean equals(Object o); /** * Returns a symbolic value for the given java object * Returns an annotation element for the given java value. Returns * null if the value cannot be an annotation element or cannot be * constructed. */ static @Nullable SymbolicValue of(TypeSystem ts, Object value) { Objects.requireNonNull(ts); if (value == null) { return null; } if (SymValue.isOkValue(value)) { return new SymValue(value); } if (value instanceof Enum<?>) { return SymEnum.fromEnum(ts, (Enum<?>) value); } if (value instanceof Annotation) { return AnnotWrapper.wrap(ts, (Annotation) value); } if (value instanceof Class<?>) { return SymClass.ofBinaryName(ts, ((Class<?>) value).getName()); } if (value.getClass().isArray()) { if (!SymArray.isOkComponentType(value.getClass().getComponentType())) { return null; } return SymArray.forArray(ts, value); } return null; } /** * Symbolic representation of an annotation. */ interface SymAnnot extends SymbolicValue { /** * Returns the value of the attribute, which may fall back to * the default value of the annotation element. Returns null if * the attribute does not exist, is unresolved, or has no default. * TODO do we need separate sentinels for that? */ @Nullable SymbolicValue getAttribute(String attrName); /** * Return the symbol for the declaring class of the annotation. */ @NonNull JClassSymbol getAnnotationSymbol(); /** * Return the simple names of all attributes, including those * defined in the annotation type but not explicitly set in this annotation. * Note that if the annotation is reflected from a class file, * we can't know which annotations used their default value, so it * returns a set of all attribute names. */ default PSet<String> getAttributeNames() { return getAnnotationSymbol().getAnnotationAttributeNames(); } /** Return the binary name of the annotation type. */ default String getBinaryName() { return getAnnotationSymbol().getBinaryName(); } /** Return the simple name of the annotation type. */ default String getSimpleName() { return getAnnotationSymbol().getSimpleName(); } @Override default boolean valueEquals(Object o) { if (!(o instanceof Annotation)) { return false; } Annotation annot = (Annotation) o; if (!this.isOfType(annot.annotationType())) { return false; } for (String attrName : getAttributeNames()) { // todo this is not symmetric... Object attr = null; try { attr = MethodUtils.invokeExactMethod(annot, attrName); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } if (attr == null || !AnnotationUtils.isValidAnnotationMemberType(attr.getClass())) { continue; } SymbolicValue myAttr = getAttribute(attrName); if (myAttr == null || !myAttr.valueEquals(attr)) { return false; } } return true; } /** * The retention policy. Note that naturally, members accessed * from class files cannot reflect annotations with {@link RetentionPolicy#SOURCE}. */ default RetentionPolicy getRetention() { return getAnnotationSymbol().getAnnotationRetention(); } /** * Return true if this annotation's binary name matches the given * binary name. */ default boolean isOfType(String binaryName) { return getBinaryName().equals(binaryName); } /** * Whether the annotation has the given type. Note that only * the name of the class is taken into account, because its * {@code Class} instance may be missing from the type system classpath. */ default boolean isOfType(Class<? extends Annotation> klass) { return isOfType(klass.getName()); } /** * Returns YES if the annotation has the attribute set to the * given value. Returns NO if it is set to another value. * Returns UNKNOWN if the attribute does not exist or is * unresolved. */ default OptionalBool attributeMatches(String attrName, Object attrValue) { SymbolicValue attr = getAttribute(attrName); if (attr == null) { return OptionalBool.UNKNOWN; } return OptionalBool.definitely(SymbolicValueHelper.equalsModuloWrapper(attr, attrValue)); } /** * Returns YES if the annotation has the attribute set to the * given value, or to an array containing the given value. Returns * NO if that's not the case. Returns UNKNOWN if the attribute * does not exist or is unresolved. */ default OptionalBool attributeContains(String attrName, Object attrValue) { SymbolicValue attr = getAttribute(attrName); if (attr == null) { return OptionalBool.UNKNOWN; } if (attr instanceof SymArray) { // todo what if the value is an array itself return OptionalBool.definitely(((SymArray) attr).containsValue(attrValue)); } return OptionalBool.definitely(SymbolicValueHelper.equalsModuloWrapper(attr, attrValue)); } } /** * An array of values. */ final class SymArray implements SymbolicValue { // exactly one of those is non-null private final @Nullable List<SymbolicValue> elements; private final @Nullable Object primArray; // for primitive arrays we keep this around private final int length; private SymArray(@Nullable List<SymbolicValue> elements, @Nullable Object primArray, int length) { this.elements = elements; this.primArray = primArray; this.length = length; assert elements == null ^ primArray == null : "Either elements or array must be mentioned"; assert primArray == null || primArray.getClass().isArray(); } /** * Returns a SymArray for a list of symbolic values. * * @param values The elements * * @throws NullPointerException if the parameter is null */ public static SymArray forElements(List<SymbolicValue> values) { return new SymArray(Collections.unmodifiableList(new ArrayList<>(values)), null, values.size()); } /** * Returns a SymArray for the parameter. * * @throws NullPointerException if the parameter is null * @throws IllegalArgumentException If the parameter is not an array, * or has an unsupported component type */ // package-private, people should use SymbolicValue#of static SymArray forArray(TypeSystem ts, @NonNull Object array) { if (!array.getClass().isArray()) { throw new IllegalArgumentException("Needs an array, got " + array); } if (array.getClass().getComponentType().isPrimitive()) { int len = Array.getLength(array); return new SymArray(null, array, len); } else { Object[] arr = (Object[]) array; if (!isOkComponentType(arr.getClass().getComponentType())) { throw new IllegalArgumentException( "Unsupported component type" + arr.getClass().getComponentType()); } List<SymbolicValue> lst = new ArrayList<>(arr.length); for (Object o : arr) { SymbolicValue elt = SymbolicValue.of(ts, o); if (elt == null) { throw new IllegalArgumentException("Unsupported array element" + o); } lst.add(elt); } return new SymArray(lst, null, arr.length); } } static boolean isOkComponentType(Class<?> compType) { return compType.isPrimitive() || compType == String.class || compType == Class.class || compType.isEnum() || compType.isAnnotation(); } public int length() { return length; } /** * Return true if this array contains the given object. If the * object is a {@link SymbolicValue}, it uses {@link #equals(Object)}, * otherwise it uses {@link #valueEquals(Object)} to compare elements. */ public boolean containsValue(Object value) { if (primArray != null) { // todo I don't know how to code that without switching on the type throw new NotImplementedException("not implemented: containsValue with a primitive array"); } else if (elements != null) { return elements.stream().anyMatch(it -> SymbolicValueHelper.equalsModuloWrapper(it, value)); } return false; } @Override public boolean valueEquals(Object o) { if (!o.getClass().isArray() || !isOkComponentType(o.getClass().getComponentType())) { return false; } if (primArray != null) { return Objects.deepEquals(primArray, o); } else if (!(o instanceof Object[])) { return false; } assert elements != null; Object[] arr = (Object[]) o; if (arr.length != length) { return false; } for (int i = 0; i < elements.size(); i++) { if (!elements.get(i).valueEquals(arr[i])) { return false; } } return true; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SymArray array = (SymArray) o; if (elements != null) { return Objects.equals(elements, array.elements); } else { return Objects.deepEquals(primArray, array.primArray); } } @Override public int hashCode() { if (elements != null) { return elements.hashCode(); } else { assert primArray != null; return primArray.hashCode(); } } @Override public String toString() { if (elements != null) { return "[list " + elements + ']'; } else { return "[array " + ArrayUtils.toString(primArray) + ']'; } } } /** * Symbolic representation of an enum constant. */ final class SymEnum implements SymbolicValue { private final String enumBinaryName; private final String enumName; private SymEnum(String enumBinaryName, String enumConstName) { this.enumBinaryName = Objects.requireNonNull(enumBinaryName); this.enumName = Objects.requireNonNull(enumConstName); } /** * If this enum constant is declared in the given enum class, * returns its value. Otherwise returns null. * * @param enumClass Class of an enum * @param <E> Return type */ public <E extends Enum<E>> @Nullable E toEnum(Class<E> enumClass) { return enumClass.getName().equals(enumBinaryName) ? EnumUtils.getEnum(enumClass, enumName) : null; } /** * Returns the symbolic value for the given enum constant. * * @param ts Type system * @param value An enum constant * * @throws NullPointerException if the parameter is null */ public static SymbolicValue fromEnum(TypeSystem ts, Enum<?> value) { return fromBinaryName(ts, value.getDeclaringClass().getName(), value.name()); } /** * @param ts Type system * @param enumBinaryName A binary name, eg {@code com.MyEnum} * @param enumConstName Simple name of the enum constant * * @throws NullPointerException if any parameter is null */ public static SymEnum fromBinaryName(TypeSystem ts, String enumBinaryName, String enumConstName) { return new SymEnum(enumBinaryName, enumConstName); } /** * @param ts Type system * @param enumTypeDescriptor The type descriptor, eg {@code Lcom/MyEnum;} * @param enumConstName Simple name of the enum constant */ public static SymEnum fromTypeDescriptor(TypeSystem ts, String enumTypeDescriptor, String enumConstName) { String enumBinaryName = ClassNamesUtil.classDescriptorToBinaryName(enumTypeDescriptor); return fromBinaryName(ts, enumBinaryName, enumConstName); } @Override public boolean valueEquals(Object o) { if (!(o instanceof Enum)) { return false; } Enum<?> value = (Enum<?>) o; return this.enumName.equals(value.name()) && enumBinaryName.equals(value.getDeclaringClass().getName()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SymEnum that = (SymEnum) o; return Objects.equals(enumBinaryName, that.enumBinaryName) && Objects.equals(enumName, that.enumName); } @Override public int hashCode() { return Objects.hash(enumBinaryName, enumName); } @Override public String toString() { return enumBinaryName + "#" + enumName; } } /** * Represents a primitive or string value. */ final class SymValue implements SymbolicValue { private final Object value; private SymValue(Object value) { // note that the value is always boxed assert value != null && isOkValue(value) : "Invalid value " + value; this.value = value; } private static boolean isOkValue(@NonNull Object value) { return ClassUtils.isPrimitiveWrapper(value.getClass()) || value instanceof String; } @Override public boolean valueEquals(Object o) { return Objects.equals(value, o); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SymValue symValue = (SymValue) o; return valueEquals(symValue.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return value.toString(); } } /** * Represents a class constant. */ final class SymClass implements SymbolicValue { private final String binaryName; private SymClass(String binaryName) { this.binaryName = binaryName; } public static SymClass ofBinaryName(TypeSystem ts, String binaryName) { return new SymClass(binaryName); } @Override public boolean valueEquals(Object o) { return o instanceof Class<?> && ((Class<?>) o).getName().equals(binaryName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SymClass symClass = (SymClass) o; return Objects.equals(binaryName, symClass.binaryName); } @Override public int hashCode() { return binaryName.hashCode(); } } }
19,717
33.532399
114
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValueHelper.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols; /** * Private helper for {@link SymbolicValue} and implementations. * * @author Clément Fournier */ final class SymbolicValueHelper { private SymbolicValueHelper() { // utility class } static boolean equalsModuloWrapper(SymbolicValue sv, Object other) { if (other instanceof SymbolicValue) { return sv.equals(other); } else { return sv.valueEquals(other); } } }
577
20.407407
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/JSymbolTable.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChain; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.JVariableSig; /** * A symbol table for a particular region of a Java program. Keeps track of the types, * values, and methods accessible from their simple name in their extent. * * <p>Instances of this interface just tie together a few {@link ShadowChain} * instances for each interesting namespace in the program. * * @since 7.0.0 */ @Experimental public interface JSymbolTable { /** * The chain of tables tracking variable names that are in scope here * (fields, locals, formals, etc). * * <p>The following special cases are not handled by variable symbol * tables: * <ul> * <li>The VariableAccess of case labels of a switch on an enum type. * For example, in {@code switch (someEnum) { case A: break; }}, {@code A} * may be out-of-scope in the outer expression. It is resolved relatively * to the type of the tested expression (eg {@code someEnum} here). * In other words, {@code variables().resolve("A")} will return a symbol * that is not necessarily the actual reference for the enum constant, * or no symbol at all. {@link ASTVariableAccess#getSignature()} * will be accurate though. * </ul> */ ShadowChain<JVariableSig, ScopeInfo> variables(); /** * The chain of tables tracking type names that are in scope here * (classes, type params, but not eg primitive types). * * <p>The following special cases are not handled by type symbol * tables: * <ul> * <li>The type reference of an inner class constructor call. For example, * in {@code new Outer().new Inner()}, {@code Inner} may be out-of-scope * in the outer expression. It depends on the type of the left hand expression, * which may be an arbitrary expression. {@code types().resolve("Inner")} will * return a symbol that is not necessarily the actual reference for {@code Outer.Inner}, * or no symbol at all. {@link ASTClassOrInterfaceType#getTypeMirror()} * will be accurate though. * </ul> */ ShadowChain<JTypeMirror, ScopeInfo> types(); /** * The chain of tables tracking method names that are in scope here. * Constructors are not tracked by this. */ ShadowChain<JMethodSig, ScopeInfo> methods(); }
2,823
37.162162
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/ScopeInfo.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainIterator; /** * A {@linkplain ShadowChainIterator#getScopeTag() scope tag} for java * shadow chains. This gives information about why a declaration is in * scope. */ public enum ScopeInfo { /** An enclosing class. */ ENCLOSING_TYPE, /** Member of an enclosing class, that is not inherited. */ ENCLOSING_TYPE_MEMBER, /** Inherited by some enclosing class. */ INHERITED, /** This merges {@link #ENCLOSING_TYPE_MEMBER} and {@link #INHERITED}. */ METHOD_MEMBER, /** A type parameter of some enclosing class. */ TYPE_PARAM, /** Local var, including lambda parameters and catch parameters. */ LOCAL, // import-likes IMPORT_ON_DEMAND, SAME_PACKAGE, JAVA_LANG, SINGLE_IMPORT, /** Sibling types in the same file, that are not nested into one another. */ SAME_FILE, /** Method or constructor formal parameter (lambdas are treated as locals). */ FORMAL_PARAM }
1,156
27.219512
82
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/CoreResolvers.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.util.List; import java.util.Map; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.NameResolver.SingleNameResolver; import net.sourceforge.pmd.util.OptionalBool; public final class CoreResolvers { private CoreResolvers() { // util class } public static <S> NameResolver<S> singleton(String name, S symbol) { final List<S> single = singletonList(symbol); return new SingleNameResolver<S>() { @Override public @NonNull List<S> resolveHere(String s) { return name.equals(s) ? single : emptyList(); } @Override public @Nullable S resolveFirst(String simpleName) { return name.equals(simpleName) ? symbol : null; } @Override public @NonNull OptionalBool knows(String simpleName) { return OptionalBool.definitely(name.equals(simpleName)); } @Override public String toString() { return "Single(" + symbol + ")"; } }; } static <S> NameResolver<S> multimapResolver(MostlySingularMultimap<String, S> symbols) { return new MultimapResolver<>(symbols); } public static <S> SingleNameResolver<S> singularMapResolver(Map<String, S> singular) { return new SingularMapResolver<>(singular); } private static final class SingularMapResolver<S> implements SingleNameResolver<S> { private final Map<String, S> map; private SingularMapResolver(Map<String, S> map) { this.map = map; } @Nullable @Override public S resolveFirst(String simpleName) { return map.get(simpleName); } @Override public boolean isDefinitelyEmpty() { return map.isEmpty(); } @Override public @NonNull OptionalBool knows(String simpleName) { return OptionalBool.definitely(map.containsKey(simpleName)); } @Override public String toString() { return "SingularMap(" + map.values() + ")"; } } private static class MultimapResolver<S> implements NameResolver<S> { private final MostlySingularMultimap<String, S> map; MultimapResolver(MostlySingularMultimap<String, S> map) { this.map = map; } @Override public @NonNull List<S> resolveHere(String s) { return map.get(s); } @Override public @NonNull OptionalBool knows(String simpleName) { return OptionalBool.definitely(map.containsKey(simpleName)); } @Override public boolean isDefinitelyEmpty() { return map.isEmpty(); } @Override public String toString() { return "Map(" + mapToString() + ")"; } private String mapToString() { if (map.isEmpty()) { return "{}"; } StringBuilder sb = new StringBuilder("{"); map.processValuesOneByOne((k, v) -> sb.append(v).append(", ")); return sb.substring(0, sb.length() - 2) + "}"; } } public static <S> EmptyResolver<S> emptyResolver() { return EmptyResolver.INSTANCE; } private static final class EmptyResolver<S> implements SingleNameResolver<S> { private static final EmptyResolver INSTANCE = new EmptyResolver<>(); @Nullable @Override public S resolveFirst(String simpleName) { return null; } @Override public @NonNull List<S> resolveHere(String simpleName) { return emptyList(); } @Override public @NonNull OptionalBool knows(String simpleName) { return OptionalBool.NO; } @Override public boolean isDefinitelyEmpty() { return true; } @Override public String toString() { return "Empty"; } } }
4,442
26.596273
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/ShadowChainIteratorImpl.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.util.IteratorUtil; import net.sourceforge.pmd.util.OptionalBool; class ShadowChainIteratorImpl<S, I> extends IteratorUtil.AbstractPausingIterator<ShadowChainNode<S, I>> implements ShadowChainIterator<S, I> { private ShadowChainNode<S, I> nextGroupToTest; private final String name; ShadowChainIteratorImpl(ShadowChainNode<S, I> firstInclusive, String name) { this.nextGroupToTest = firstInclusive; this.name = name; } // FIXME cross shadow barrier @Override protected void computeNext() { ShadowChainNode<S, I> next = nextGroupThatKnows(nextGroupToTest, name); if (next == null) { done(); return; } assert !next.resolveHere(name).isEmpty() : "Shadow iterator stopped on wrong node"; setNext(next); } @Override protected void prepareViewOn(ShadowChainNode<S, I> current) { if (current instanceof ShadowChainNodeBase) { nextGroupToTest = current.getParent(); } else { throw new IllegalStateException("Root group is empty " + current); } } @Override public I getScopeTag() { return ((ShadowChainNodeBase<S, I>) getCurrentValue()).getScopeTag(); } @Override public List<S> getResults() { return getCurrentValue().resolveHere(name); } // inclusive of the parameter // @Contract("null -> null") private @Nullable ShadowChainNode<S, I> nextGroupThatKnows(@Nullable ShadowChainNode<S, I> group, String name) { ShadowChainNode<S, I> parent = group; while (parent != null && !definitelyKnows(parent, name)) { parent = parent.getParent(); } return parent; } private static boolean definitelyKnows(@NonNull ShadowChainNode<?, ?> group, String name) { // It's not cool to depend on the implementation, but doing otherwise is publishing a lot of API OptionalBool opt = group.knowsSymbol(name); if (opt.isKnown()) { return opt.isTrue(); } // Note that we bypass the node to call directly the resolver // This is to bypass the cache of cached resolvers, which stores declarations // of enclosing groups return group.getResolver().resolveFirst(name) != null; } }
2,645
30.5
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/ShadowChainNodeBase.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.List; import java.util.function.BinaryOperator; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.util.CollectionUtil; import net.sourceforge.pmd.util.OptionalBool; class ShadowChainNodeBase<S, I> implements ShadowChain<S, I>, ShadowChainNode<S, I> { protected final NameResolver<S> resolver; private final BinaryOperator<List<S>> merger; protected final @NonNull ShadowChainNode<S, I> parent; private final boolean shadowBarrier; private final I scopeTag; @SuppressWarnings("unchecked") // NameResolver is covariant in S ShadowChainNodeBase(@NonNull ShadowChainNode<S, I> parent, boolean shadowBarrier, I scopeTag, NameResolver<? extends S> resolver, BinaryOperator<List<S>> merger) { this.parent = parent; this.scopeTag = scopeTag; this.shadowBarrier = shadowBarrier; this.resolver = (NameResolver<S>) resolver; this.merger = merger; } ShadowChainNodeBase(ShadowChainNode<S, I> parent, boolean shadowBarrier, I scopeTag, NameResolver<? extends S> resolver) { this(parent, shadowBarrier, scopeTag, resolver, defaultMerger()); } @Override public ShadowChainNode<S, I> asNode() { return this; } @Override public ShadowChain<S, I> asChain() { return this; } @Override public NameResolver<S> getResolver() { return resolver; } @Override public final boolean isShadowBarrier() { return shadowBarrier; } @Override public @NonNull ShadowChainNode<S, I> getParent() { return parent; } /** * This is package protected, because it would be impossible to find * a value for this on the root node. Instead, the scope tag * is only accessible from a {@link ShadowChainIterator}, if we found * results (which naturally excludes the root group, being empty) */ I getScopeTag() { return scopeTag; } /** Doesn't ask the parents. */ @Override public OptionalBool knowsSymbol(String simpleName) { return resolver.knows(simpleName); } @Override public @NonNull List<S> resolve(String name) { List<S> res = this.resolveHere(name); if (res.isEmpty()) { // failed, continue return getParent().asChain().resolve(name); } else { // successful search: fetch all non-shadowed names // note: we can't call ShadowChain::resolve on the parent // as it would ignore the shadow barriers if the parent // does not know the name. ShadowChainNode<S, I> node = this; while (!node.isShadowBarrier() && node.getParent() != null) { // The search ends on the first node that is a // shadow barrier, inclusive. node = node.getParent(); res = merger.apply(res, node.resolveHere(name)); } } return res; } @Override public List<S> resolveHere(String simpleName) { List<S> res = resolver.resolveHere(simpleName); handleResolverKnows(simpleName, !res.isEmpty()); return res; } protected void handleResolverKnows(String name, boolean resolverKnows) { // to be overridden } @Override public S resolveFirst(String name) { S sym = resolver.resolveFirst(name); handleResolverKnows(name, sym != null); return sym != null ? sym : getParent().asChain().resolveFirst(name); } @Override public String toString() { return scopeTag + " " + resolver.toString(); } static <S> BinaryOperator<List<S>> defaultMerger() { return CollectionUtil::concatView; } }
4,024
29.725191
126
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/ShadowChainNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.util.OptionalBool; /** * A {@link ShadowChain} viewed as individual nodes. This offers a lower * level API as {@link ShadowChain}. */ public interface ShadowChainNode<S, I> { /** * Returns true if this group shadows the next groups in the chain. * This means, that if this group knows about a name, it won't delegate * resolve to the next group in the chain. If it doesn't know about it * then resolve proceeds anyway. */ boolean isShadowBarrier(); /** * Returns the next node in the chain. Returns null if this is the * root. */ @Nullable ShadowChainNode<S, I> getParent(); /** * Returns the resolver for this node. */ NameResolver<S> getResolver(); /** * Wraps {@link #getResolver()}{@code .resolveHere()}, may do * additional stuff like caching. */ default List<S> resolveHere(String simpleName) { return getResolver().resolveHere(simpleName); } /** * Returns whether this node knows the given symbol (without asking * the parents). */ OptionalBool knowsSymbol(String name); ShadowChain<S, I> asChain(); }
1,423
23.135593
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/ShadowChainBuilder.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import static net.sourceforge.pmd.lang.java.symbols.table.coreimpl.CoreResolvers.multimapResolver; import static net.sourceforge.pmd.lang.java.symbols.table.coreimpl.CoreResolvers.singleton; import static net.sourceforge.pmd.lang.java.symbols.table.coreimpl.CoreResolvers.singularMapResolver; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.BinaryOperator; import java.util.function.Function; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.MostlySingularMultimap.Builder; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.MostlySingularMultimap.MapMaker; import net.sourceforge.pmd.util.CollectionUtil; /** * Build a shadow chain for some type. * * <p>Implementing this framework means implementing {@link NameResolver}s for * each relevant way that a declaration may be brought in scope, then figuring * out the correct way these resolvers should be linked into a ShadowChain. * Shadow chain builders just give some utility methods to make the linking * process more straightforward. * * @param <S> Type of symbols * @param <I> Type of scope tags */ public abstract class ShadowChainBuilder<S, I> { private final MapMaker<String> mapMaker = this::copyToMutable; MostlySingularMultimap.Builder<String, S> newMapBuilder() { return MostlySingularMultimap.newBuilder(mapMaker); } /** * Copy the given map into a new mutable map. This is provided * as a hook to experiment with alternative map implementations * easily, eg tries, or specialized maps. */ protected <V> Map<String, V> copyToMutable(Map<String, V> m) { return new LinkedHashMap<>(m); } /** Returns the name with which the given symbol should be indexed. */ public abstract String getSimpleName(S sym); /** Returns the singleton for the chain root. */ public static <S, I> ShadowChainNode<S, I> rootGroup() { return ShadowChainRoot.empty(); } // #augment overloads wrap a resolver into a new chain node public ShadowChainNode<S, I> augment(ShadowChainNode<S, I> parent, boolean shadowBarrier, I scopeTag, ResolverBuilder symbols) { if (isPrunable(parent, shadowBarrier, symbols.isEmpty())) { return parent; } return new ShadowChainNodeBase<>(parent, shadowBarrier, scopeTag, symbols.build()); } public ShadowChainNode<S, I> augment(ShadowChainNode<S, I> parent, boolean shadowBarrier, I scopeTag, NameResolver<? extends S> resolver) { if (isPrunable(parent, shadowBarrier, resolver.isDefinitelyEmpty())) { return parent; } return new ShadowChainNodeBase<>(parent, shadowBarrier, scopeTag, resolver); } // prunes empty nodes if doing so will not alter results private boolean isPrunable(ShadowChainNode<S, I> parent, boolean shadowBarrier, boolean definitelyEmpty) { return definitelyEmpty && (!shadowBarrier || parent.getResolver().isDefinitelyEmpty() && parent.isShadowBarrier()); } public ShadowChainNode<S, I> augment(ShadowChainNode<S, I> parent, boolean shadowBarrier, I scopeTag, S symbol) { return new ShadowChainNodeBase<>(parent, shadowBarrier, scopeTag, singleton(getSimpleName(symbol), symbol)); } // #__WithCache use a cache for resolved symbols // Use this for expensive resolvers, instead of caching in the // resolver itself (the chain node will cache the results of the // parents too) public ShadowChainNode<S, I> augmentWithCache(ShadowChainNode<S, I> parent, boolean shadowBarrier, I scopeTag, NameResolver<? extends S> resolver) { return augmentWithCache(parent, shadowBarrier, scopeTag, resolver, ShadowChainNodeBase.defaultMerger()); } public ShadowChainNode<S, I> augmentWithCache(ShadowChainNode<S, I> parent, boolean shadowBarrier, I scopeTag, NameResolver<? extends S> resolver, BinaryOperator<List<S>> merger) { return new CachingShadowChainNode<>(parent, new HashMap<>(), resolver, shadowBarrier, scopeTag, merger); } public ShadowChainNode<S, I> shadowWithCache(ShadowChainNode<S, I> parent, I scopeTag, // this map will be used as the cache without copy, // it may contain initial bindings, which is only // valid if the built group is a shadow barrier, which // is why this parameter is defaulted. Map<String, List<S>> cacheMap, NameResolver<S> resolver) { return new CachingShadowChainNode<>(parent, cacheMap, resolver, true, scopeTag, ShadowChainNodeBase.defaultMerger()); } // #shadow overloads default the shadowBarrier param to true public ShadowChainNode<S, I> shadow(ShadowChainNode<S, I> parent, I scopeTag, ResolverBuilder resolver) { return augment(parent, true, scopeTag, resolver); } public ShadowChainNode<S, I> shadow(ShadowChainNode<S, I> parent, I scopeTag, NameResolver<S> resolver) { return augment(parent, true, scopeTag, resolver); } public ShadowChainNode<S, I> shadow(ShadowChainNode<S, I> parent, I scopeTag, S symbol) { return augment(parent, true, scopeTag, symbol); } // convenience to build name resolvers public <N> ResolverBuilder groupByName(Iterable<? extends N> input, Function<? super N, ? extends S> symbolFetcher) { return new ResolverBuilder(newMapBuilder().groupBy(CollectionUtil.map(input, symbolFetcher), this::getSimpleName)); } public ResolverBuilder groupByName(Iterable<? extends S> tparams) { return new ResolverBuilder(newMapBuilder().groupBy(tparams, this::getSimpleName)); } public NameResolver<S> groupByName(S sym) { return singleton(getSimpleName(sym), sym); } /** * Helper to build a new name resolver. The internal data structure * optimises for the case where there are no name collisions, which * is a good trade for Java. */ public class ResolverBuilder { private final MostlySingularMultimap.Builder<String, S> myBuilder; public ResolverBuilder(Builder<String, S> myBuilder) { this.myBuilder = myBuilder; } public ResolverBuilder() { this.myBuilder = newMapBuilder(); } public String getSimpleName(S sym) { return ShadowChainBuilder.this.getSimpleName(sym); } public ResolverBuilder append(S sym) { myBuilder.appendValue(getSimpleName(sym), sym); return this; } public ResolverBuilder appendWithoutDuplicate(S sym) { myBuilder.appendValue(getSimpleName(sym), sym, true); return this; } public ResolverBuilder overwrite(S sym) { myBuilder.replaceValue(getSimpleName(sym), sym); return this; } public ResolverBuilder absorb(ShadowChainBuilder<S, ?>.ResolverBuilder other) { myBuilder.absorb(other.myBuilder); return this; } public Map<String, List<S>> getMutableMap() { return myBuilder.getMutableMap(); } public NameResolver<S> build() { if (isEmpty()) { return CoreResolvers.emptyResolver(); } else if (myBuilder.isSingular()) { Map<String, S> singular = myBuilder.buildAsSingular(); assert singular != null; if (singular.size() == 1) { Entry<String, S> pair = singular.entrySet().iterator().next(); return singleton(pair.getKey(), pair.getValue()); } else { return singularMapResolver(singular); } } return multimapResolver(myBuilder.build()); } public boolean isEmpty() { return myBuilder.isEmpty(); } } }
8,387
39.521739
184
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/MostlySingularMultimap.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; import org.apache.commons.lang3.Validate; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.util.AssertionUtil; /** * An unmodifiable multimap type, efficient if the single-value case is the * most common. */ final class MostlySingularMultimap<K, V> { @SuppressWarnings("rawtypes") private static final MostlySingularMultimap EMPTY = new MostlySingularMultimap<>(Collections.emptyMap()); private final Map<K, Object> map; private MostlySingularMultimap(Map<K, Object> map) { this.map = map; } @FunctionalInterface public interface MapMaker<K> { /** Produce a new mutable map with the contents of the given map. */ <V> Map<K, V> copy(Map<K, V> m); } public @NonNull List<V> get(K k) { Object vs = map.get(k); return interpretValue(vs); } public boolean isEmpty() { return map.isEmpty(); } public Set<K> keySet() { return map.keySet(); } public boolean containsKey(Object v) { return map.containsKey(v); } @Override public String toString() { return map.toString(); } public void processValuesOneByOne(BiConsumer<K, V> consumer) { for (Entry<K, Object> entry : map.entrySet()) { K k = entry.getKey(); Object vs = entry.getValue(); if (vs instanceof VList) { for (V v : (VList<V>) vs) { consumer.accept(k, v); } } else { consumer.accept(k, (V) vs); } } } @NonNull @SuppressWarnings("unchecked") private static <V> List<V> interpretValue(Object vs) { if (vs == null) { return Collections.emptyList(); } else if (vs instanceof VList) { return (VList<V>) vs; } else { return Collections.singletonList((V) vs); } } @SuppressWarnings("unchecked") public static <K, V> MostlySingularMultimap<K, V> empty() { return EMPTY; } public static <K, V> Builder<K, V> newBuilder(MapMaker<K> mapMaker) { return new Builder<>(mapMaker); } // In case the value type V is an array list private static class VList<V> extends ArrayList<V> { VList(int size) { super(size); } } /** * Builder for a multimap. Can only be used once. */ public static final class Builder<K, V> { private final MapMaker<K> mapMaker; private @Nullable Map<K, Object> map; private boolean consumed; /** True unless some entry has a list of values. */ private boolean isSingular = true; private Builder(MapMaker<K> mapMaker) { this.mapMaker = mapMaker; } private Map<K, Object> getMapInternal() { if (map == null) { map = mapMaker.copy(Collections.emptyMap()); Validate.isTrue(map.isEmpty(), "Map should be empty"); } return map; } public void replaceValue(K key, V v) { checkKeyValue(key, v); getMapInternal().put(key, v); } public void addUnlessKeyExists(K key, V v) { checkKeyValue(key, v); getMapInternal().putIfAbsent(key, v); } public void appendValue(K key, V v) { appendValue(key, v, false); } public void appendValue(K key, V v, boolean noDuplicate) { checkKeyValue(key, v); getMapInternal().compute(key, (k, oldV) -> { return appendSingle(oldV, v, noDuplicate); }); } private void checkKeyValue(K key, V v) { ensureOpen(); AssertionUtil.requireParamNotNull("value", v); AssertionUtil.requireParamNotNull("key", key); } public Builder<K, V> groupBy(Iterable<? extends V> values, Function<? super V, ? extends K> keyExtractor) { ensureOpen(); return groupBy(values, keyExtractor, Function.identity()); } public <I> Builder<K, V> groupBy(Iterable<? extends I> values, Function<? super I, ? extends K> keyExtractor, Function<? super I, ? extends V> valueExtractor) { ensureOpen(); for (I i : values) { appendValue(keyExtractor.apply(i), valueExtractor.apply(i)); } return this; } // no duplicates public Builder<K, V> absorb(Builder<K, V> other) { ensureOpen(); other.ensureOpen(); if (this.map == null) { this.map = other.map; this.isSingular = other.isSingular; } else { // isSingular may be changed in the loop by appendSingle this.isSingular &= other.isSingular; for (Entry<K, Object> otherEntry : other.getMapInternal().entrySet()) { K key = otherEntry.getKey(); Object otherV = otherEntry.getValue(); map.compute(key, (k, myV) -> { if (myV == null) { return otherV; } else if (otherV instanceof VList) { Object newV = myV; for (V v : (VList<V>) otherV) { newV = appendSingle(newV, v, true); } return newV; } else { return appendSingle(myV, (V) otherV, true); } }); } } other.consume(); return this; } private Object appendSingle(@Nullable Object vs, V v, boolean noDuplicate) { if (vs == null) { return v; } else if (vs instanceof VList) { if (noDuplicate && ((VList) vs).contains(v)) { return vs; } ((VList) vs).add(v); return vs; } else { if (noDuplicate && vs.equals(v)) { return vs; } List<V> vs2 = new VList<>(2); isSingular = false; vs2.add((V) vs); vs2.add(v); return vs2; } } public MostlySingularMultimap<K, V> build() { consume(); return isEmpty() ? empty() : new MostlySingularMultimap<>(getMapInternal()); } public @Nullable Map<K, V> buildAsSingular() { consume(); if (!isSingular) { return null; // NOPMD: returning null as in the spec (Nullable) } return (Map<K, V>) map; } private void consume() { ensureOpen(); consumed = true; } private void ensureOpen() { Validate.isTrue(!consumed, "Builder was already consumed"); } public boolean isSingular() { return isSingular; } public Map<K, List<V>> getMutableMap() { Map<K, List<V>> mutable = mapMaker.copy(Collections.emptyMap()); for (Entry<K, Object> entry : getMapInternal().entrySet()) { mutable.put(entry.getKey(), interpretValue(entry.getValue())); } return mutable; } public boolean isEmpty() { return map == null || map.isEmpty(); } } }
8,198
28.492806
109
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/NameResolver.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.Collections; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.util.CollectionUtil; import net.sourceforge.pmd.util.OptionalBool; /** * Name resolvers are strategies backing {@link ShadowChain}s. They have * no information about outer context, instead the structure of the shadow * group chain handles that. * * @param <S> Type of symbols */ public interface NameResolver<S> { /** * Returns all symbols known by this resolver that have the given * simple name. Depending on language semantics, finding several * symbols may mean there is ambiguity. If no such symbol is known, * returns an empty list. * * @param simpleName Simple name */ @NonNull List<S> resolveHere(String simpleName); /** * Resolves the first symbol that would be part of the list yielded * by {@link #resolveHere(String)} for the given name. If the list * would be empty (no such symbol is known), returns null. */ default @Nullable S resolveFirst(String simpleName) { List<S> result = resolveHere(simpleName); return result.isEmpty() ? null : result.get(0); } /** * Returns whether this resolver knows if it has a declaration for * the given name. If the result is NO, then resolveFirst MUST be null, * if the result is YES, then resolveFirst MUST be non-null. Otherwise * we don't know. */ default @NonNull OptionalBool knows(String simpleName) { return OptionalBool.UNKNOWN; } /** Returns true if this resolver knows it cannot resolve anything. */ default boolean isDefinitelyEmpty() { return false; } /** Please implement toString to ease debugging. */ @Override String toString(); /** * Returns a resolver that concatenates the results of every resolver * in the given list. * * @param resolvers Resolvers * @param <T> Type of symbol */ static <T> NameResolver<T> composite(List<? extends NameResolver<? extends T>> resolvers) { if (resolvers.isEmpty()) { return CoreResolvers.emptyResolver(); } return new NameResolver<T>() { @Override public @NonNull List<T> resolveHere(String simpleName) { List<T> result = Collections.emptyList(); for (NameResolver<? extends T> r : resolvers) { List<? extends T> ts = r.resolveHere(simpleName); if (!ts.isEmpty()) { result = CollectionUtil.concatView(result, ts); } } return result; } @Override public @Nullable T resolveFirst(String simpleName) { for (NameResolver<? extends T> r : resolvers) { T t = r.resolveFirst(simpleName); if (t != null) { return t; } } return null; } @Override public String toString() { return "Composite[" + resolvers + "]"; } }; } /** * A base class for resolvers that know at most one symbol for any * given name. This means {@link #resolveHere(String)} may delegate * to {@link #resolveFirst(String)}, for implementation simplicity. * This is also a marker interface used to optimise some things * internally. */ interface SingleNameResolver<S> extends NameResolver<S> { @Override default @NonNull List<S> resolveHere(String simpleName) { return CollectionUtil.listOfNotNull(resolveFirst(simpleName)); } // make it abstract @Override @Nullable S resolveFirst(String simpleName); } }
4,110
30.381679
95
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/ShadowChainIterator.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.Iterator; import java.util.List; /** * Iterates up a {@link ShadowChain} chain to find a given name. This * can be used to find all shadowed declarations for a given name, or to * find the reason why a declaration is in scope {@link #getScopeTag()}. */ public interface ShadowChainIterator<S, I> extends Iterator<ShadowChainNode<S, I>> { @Override boolean hasNext(); /** * Returns the next node in the chain that contains a declaration for * the name this iterator searches. If that group exists ({@link #hasNext()}) * then the symbols yielded by {@link #getResults()} are shadowed * in the previous groups that were yielded (unless they are the same * symbols, in which case there could be eg duplicate imports). */ @Override ShadowChainNode<S, I> next(); /** * Returns the scope tag of the shadow group that was last yielded. * * @throws IllegalStateException If {@link #next()} has not been called */ I getScopeTag(); /** * Returns the results of the search at the point the iterator is stopped. * This list is nonempty.Note that a shadow chain iterator considers * results node by node, it won't ask the next nodes in the tree. * * @throws IllegalStateException If {@link #next()} has not been called */ List<S> getResults(); }
1,529
29.6
84
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/CachingShadowChainNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BinaryOperator; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.util.OptionalBool; class CachingShadowChainNode<S, I> extends ShadowChainNodeBase<S, I> { private final Map<String, List<S>> cache; // contains YES/NO depending on whether *this* name resolver knew a // result when asked for it. The cache also contains entries for parents // that knew results private final Map<String, OptionalBool> keysThatIKnow = new HashMap<>(); protected CachingShadowChainNode(@NonNull ShadowChainNode<S, I> parent, Map<String, List<S>> known, NameResolver<? extends S> resolver, boolean shadowBarrier, I scopeTag, BinaryOperator<List<S>> merger) { super(parent, shadowBarrier, scopeTag, resolver, merger); this.cache = known; } @Override public @NonNull List<S> resolve(String name) { List<S> result = cache.get(name); if (result != null) { return result; } result = super.resolve(name); cache.put(name, result); return result; } @Override protected void handleResolverKnows(String name, boolean resolverKnows) { keysThatIKnow.putIfAbsent(name, OptionalBool.definitely(resolverKnows)); } @Override public S resolveFirst(String name) { List<S> result = cache.get(name); if (result != null && !result.isEmpty()) { return result.get(0); } S first = super.resolveFirst(name); if (first == null) { cache.put(name, Collections.emptyList()); } else if (resolver instanceof NameResolver.SingleNameResolver && isShadowBarrier()) { // the search is complete cache.put(name, Collections.singletonList(first)); } return first; } @Override public OptionalBool knowsSymbol(String simpleName) { OptionalBool resolverKnows = resolver.knows(simpleName); if (resolverKnows.isKnown()) { return resolverKnows; } else { return keysThatIKnow.getOrDefault(simpleName, OptionalBool.UNKNOWN); } } @Override public String toString() { return "Cached(" + "cache size=" + cache.size() + ", " + "resolver=" + super.toString() + ')'; } }
2,792
31.476744
94
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/ShadowChainRoot.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import static java.util.Collections.emptyList; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.util.OptionalBool; /** * An empty group, bottom of the linked lists, for implementation simplicity. */ final class ShadowChainRoot<S, I> implements ShadowChain<S, I>, ShadowChainNode<S, I> { @SuppressWarnings("rawtypes") private static final ShadowChainRoot EMPTY = new ShadowChainRoot<>(); private ShadowChainRoot() { } @Override public ShadowChain<S, I> asChain() { return this; } @Override public ShadowChainNode<S, I> asNode() { return this; } @Override public NameResolver<S> getResolver() { return CoreResolvers.emptyResolver(); } @Override public OptionalBool knowsSymbol(String name) { return OptionalBool.NO; } @Override public @Nullable ShadowChainNode<S, I> getParent() { return null; } @Override public boolean isShadowBarrier() { return true; } @Override public @NonNull List<S> resolve(String name) { return emptyList(); } @Override public S resolveFirst(String name) { return null; } @Override public String toString() { return "Root"; } @SuppressWarnings("unchecked") static <S, I> ShadowChainNode<S, I> empty() { return EMPTY; } }
1,650
20.166667
87
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/ShadowChain.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.coreimpl; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; /** * A shadow chain is a linked list of {@link NameResolver}s, which handles * shadowing relations between declarations. Chains track the scope of * declarations of a single kind, corresponding to a namespace (eg types * or methods). * * <p>Basic usage: * <pre>{@code * List<JVariableSymbol> foo = chain.resolve("foo"); * if (foo.isEmpty()) { * // failed * } else if (foo.size() > 1) { * // ambiguity between all the members of the list * } else { * JVariableSymbol varFoo = foo.get(0); // it's this symbol * } * }</pre> * * <p>More advanced functionality is provided by {@link ShadowChainIterator}. * ShadowChain instances can be viewed as both a node in the * chain or as the entire chain. The former interpretation is rendered * by the lower-level API of {@link ShadowChainNode}. * * @param <S> Type of symbols this chain tracks * @param <I> Type of the "scope tag", some data used to help identify * the reason why a declaration is in scope. This can be retrieved * with {@link ShadowChainIterator#getScopeTag()}. */ public interface ShadowChain<S, I> { /** * Returns the list of symbols accessible by simple name in the scope * of this group. No name in this list shadows another. An empty list * means no such symbol exist. A list with more than one element may * mean there is ambiguity. For methods, ambiguity may be resolved through * overload resolution, for other kinds of symbols, it causes an error. * * <p>The ordering in the list is defined to be innermost first. * * @param name Simple name of the symbols to find * * @return A list of symbols */ @NonNull List<S> resolve(String name); /** * Returns the first symbol that would be yielded by {@link #resolve(String)}, * if it would return a non-empty list. Otherwise returns null. * * @param name Simple name of the symbol to find * * @return An optional symbol */ S resolveFirst(String name); /** * Returns an iterator that iterates over sets of shadowed declarations * with the given name. * * @param name Simple name of the symbols to find */ default ShadowChainIterator<S, I> iterateResults(String name) { return new ShadowChainIteratorImpl<>(asNode(), name); } /** * Returns the API of this instance that views the chain as individual nodes. */ ShadowChainNode<S, I> asNode(); }
2,743
30.906977
82
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/JavaResolvers.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.internal; import static net.sourceforge.pmd.lang.java.symbols.table.internal.SuperTypesEnumerator.DIRECT_STRICT_SUPERTYPES; import static net.sourceforge.pmd.lang.java.symbols.table.internal.SuperTypesEnumerator.JUST_SELF; import static net.sourceforge.pmd.util.CollectionUtil.listOfNotNull; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Predicate; import org.apache.commons.lang3.tuple.Pair; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.pcollections.HashTreePSet; import org.pcollections.PSet; import net.sourceforge.pmd.lang.java.symbols.JAccessibleElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; import net.sourceforge.pmd.lang.java.symbols.SymbolResolver; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.CoreResolvers; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.NameResolver; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.NameResolver.SingleNameResolver; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainBuilder; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.JVariableSig; import net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig; import net.sourceforge.pmd.lang.java.types.TypeOps; import net.sourceforge.pmd.lang.java.types.internal.infer.OverloadSet; import net.sourceforge.pmd.util.AssertionUtil; import net.sourceforge.pmd.util.CollectionUtil; public final class JavaResolvers { private JavaResolvers() { // utility class } /** Prepend the package name, handling empty package. */ static String prependPackageName(String pack, String name) { return pack.isEmpty() ? name : pack + "." + name; } /** * Returns true if the given element can be imported in the current file * (it's visible & accessible). This is not a general purpose accessibility * check and is only appropriate for imports. * * * <p>We consider protected members inaccessible outside of the package they were declared in, * which is an approximation but won't cause problems in practice. * In an ACU in another package, the name is accessible only inside classes that inherit * from the declaring class. But inheriting from a class makes its static members * accessible via simple name too. So this will actually be picked up by some other symbol table * when in the subclass. Usages outside of the subclass would have made the compilation fail. */ static boolean canBeImportedIn(String thisPackage, JAccessibleElementSymbol member) { return isAccessibleIn(null, thisPackage, member, false); } @NonNull static NameResolver<JTypeMirror> importedOnDemand(Set<String> lazyImportedPackagesAndTypes, final SymbolResolver symResolver, final String thisPackage) { return new SingleNameResolver<JTypeMirror>() { @Nullable @Override public JTypeMirror resolveFirst(String simpleName) { for (String pack : lazyImportedPackagesAndTypes) { // here 'pack' may be a package or a type name, so we must resolve by canonical name String name = prependPackageName(pack, simpleName); JClassSymbol sym = symResolver.resolveClassFromCanonicalName(name); if (sym != null && canBeImportedIn(thisPackage, sym)) { return sym.getTypeSystem().typeOf(sym, false); } } return null; } @Override public String toString() { return "ImportOnDemandResolver(" + lazyImportedPackagesAndTypes + ")"; } }; } @NonNull static NameResolver<JTypeMirror> packageResolver(SymbolResolver symResolver, String packageName) { return new SingleNameResolver<JTypeMirror>() { @Nullable @Override public JTypeMirror resolveFirst(String simpleName) { JClassSymbol sym = symResolver.resolveClassFromBinaryName(prependPackageName(packageName, simpleName)); if (sym != null) { return sym.getTypeSystem().typeOf(sym, false); } return null; } @Override public String toString() { return "PackageResolver(" + packageName + ")"; } }; } /** All methods in a type, taking care of hiding/overriding. */ static NameResolver<JMethodSig> subtypeMethodResolver(JClassType t) { JClassSymbol nestRoot = t.getSymbol().getNestRoot(); return new NameResolver<JMethodSig>() { @Override public @NonNull List<JMethodSig> resolveHere(String simpleName) { return t.streamMethods( it -> it.nameEquals(simpleName) && isAccessibleIn(nestRoot, it, true) // fetch protected methods && isNotStaticInterfaceMethod(it) ).collect(OverloadSet.collectMostSpecific(t)); // remove overridden, hidden methods } // Static interface methods are not inherited and are in fact not in scope in the subtypes. // They must be explicitly qualified or imported. private boolean isNotStaticInterfaceMethod(JMethodSymbol it) { return !it.isStatic() || it.getEnclosingClass().equals(t.getSymbol()) || !it.getEnclosingClass().isInterface(); } @Override public String toString() { return "methods of " + t; } }; } /** Static methods with a given name. */ static NameResolver<JMethodSig> staticImportMethodResolver(JClassType container, @NonNull String accessPackageName, String importedSimpleName) { assert importedSimpleName != null; assert accessPackageName != null; return new NameResolver<JMethodSig>() { @Override public @NonNull List<JMethodSig> resolveHere(String simpleName) { if (!simpleName.equals(importedSimpleName)) { return Collections.emptyList(); } return container.streamMethods( it -> Modifier.isStatic(it.getModifiers()) && it.nameEquals(simpleName) // Technically, importing a static protected method may be valid // inside some of the classes in the compilation unit. This test // makes it not in scope in those classes. But it's also visible // from the subclass as an "inherited" member, so is in scope in // the relevant contexts. && canBeImportedIn(accessPackageName, it) ).collect(OverloadSet.collectMostSpecific(container)); // remove overridden, hidden methods } @Override public String toString() { return "static methods w/ name " + importedSimpleName + " of " + container; } }; } /** Static fields with a given name. */ static NameResolver<FieldSig> staticImportFieldResolver(JClassType containerType, @NonNull String accessPackageName, String importedSimpleName) { return new NameResolver<FieldSig>() { List<FieldSig> result; @Override public @NonNull List<FieldSig> resolveHere(String simpleName) { if (!simpleName.equals(importedSimpleName)) { return Collections.emptyList(); } if (result == null) { result = JavaResolvers.getMemberFieldResolver(containerType, accessPackageName, null, simpleName) .resolveHere(simpleName); } return result; } @Override public String toString() { return "static methods w/ name " + importedSimpleName + " of " + containerType; } }; } /** Static classes with a given name. */ static NameResolver<JClassType> staticImportClassResolver(JClassType containerType, @NonNull String accessPackageName, String importedSimpleName) { return new NameResolver<JClassType>() { List<JClassType> result; @Override public @NonNull List<JClassType> resolveHere(String simpleName) { if (!simpleName.equals(importedSimpleName)) { return Collections.emptyList(); } if (result == null) { result = JavaResolvers.getMemberClassResolver(containerType, accessPackageName, null, simpleName) .resolveHere(simpleName); } return result; } @Override public String toString() { return "static classes w/ name " + importedSimpleName + " of " + containerType; } }; } static NameResolver<JMethodSig> staticImportOnDemandMethodResolver(JClassType container, @NonNull String accessPackageName) { assert accessPackageName != null; return new NameResolver<JMethodSig>() { @Override public @NonNull List<JMethodSig> resolveHere(String simpleName) { return container.streamMethods( it -> Modifier.isStatic(it.getModifiers()) && it.nameEquals(simpleName) && canBeImportedIn(accessPackageName, it) ).collect(OverloadSet.collectMostSpecific(container)); // remove overridden, hidden methods } @Override public String toString() { return "all static methods of " + container; } }; } private static final BinaryOperator<List<JMethodSig>> STATIC_MERGER = (as, bs) -> methodMerger(true, as, bs); private static final BinaryOperator<List<JMethodSig>> NON_STATIC_MERGER = (as, bs) -> methodMerger(false, as, bs); static BinaryOperator<List<JMethodSig>> methodMerger(boolean inStaticType) { return inStaticType ? STATIC_MERGER : NON_STATIC_MERGER; } /** * Merges two method scopes, the otherResult is the one of an enclosing class, * the inner result is the one inherited from supertypes (which take precedence * in case of override equivalence). * * <p>Non-static methods of the outer result are excluded if the inner scope is static. */ private static List<JMethodSig> methodMerger(boolean inStaticType, List<JMethodSig> myResult, List<JMethodSig> otherResult) { if (otherResult.isEmpty()) { return myResult; } // don't check myResult for emptyness, we might need to remove static methods // For both the input lists, their elements are pairwise non-equivalent. // If any element of myResult is override-equivalent to // another in otherResult, then we must exclude the otherResult BitSet isShadowed = new BitSet(otherResult.size()); for (JMethodSig m1 : myResult) { int i = 0; for (JMethodSig m2 : otherResult) { boolean isAlreadyShadowed = isShadowed.get(i); if (!isAlreadyShadowed && TypeOps.areOverrideEquivalent(m1, m2) || inStaticType && !m2.isStatic()) { isShadowed.set(i); // we'll remove it later } i++; } } if (isShadowed.isEmpty()) { return CollectionUtil.concatView(myResult, otherResult); } else { List<JMethodSig> result = new ArrayList<>(myResult.size() + otherResult.size() - 1); result.addAll(myResult); copyIntoWithMask(otherResult, isShadowed, result); return Collections.unmodifiableList(result); } } /** * Copy the elements of the input list into the result list, excluding * all elements marked by the bitset. */ private static <T> void copyIntoWithMask(List<? extends T> input, BitSet denyList, List<? super T> result) { int last = 0; for (int i = denyList.nextSetBit(0); i >= 0; i = denyList.nextSetBit(i + 1)) { if (last != i) { result.addAll(input.subList(last, i)); } last = i + 1; } if (last != input.size()) { result.addAll(input.subList(last, input.size())); } } /** * Resolvers for inherited member types and fields. We can't process * methods that way, because there may be duplicates and the equals * of {@link JMethodSymbol} is not reliable for now (cannot differentiate * overloads). But also, usually a subset of methods is used in a subclass, * and it's ok performance-wise to process them on-demand. */ static Pair<NameResolver<JTypeMirror>, NameResolver<JVariableSig>> inheritedMembersResolvers(JClassType t) { Pair<ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder, ShadowChainBuilder<JVariableSig, ?>.ResolverBuilder> builders = hidingWalkResolvers(t, t, t.getSymbol().getPackageName(), true, /* onlyStatic: */false, DIRECT_STRICT_SUPERTYPES); return Pair.of(builders.getLeft().build(), builders.getRight().build()); } static Pair<ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder, ShadowChainBuilder<JVariableSig, ?>.ResolverBuilder> importOnDemandMembersResolvers(JClassType t, @NonNull String accessPackageName) { return hidingWalkResolvers(t, null, accessPackageName, false, /* onlyStatic: */ true, JUST_SELF /* include self members */); } private static Pair<ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder, ShadowChainBuilder<JVariableSig, ?>.ResolverBuilder> hidingWalkResolvers(JClassType t, @Nullable JClassType accessType, @NonNull String accessPackageName, boolean accessIsSubtypeOfOwner, boolean onlyStatic, SuperTypesEnumerator enumerator) { JClassSymbol nestRoot = accessType == null ? null : accessType.getSymbol().getNestRoot(); ShadowChainBuilder<JVariableSig, ?>.ResolverBuilder fields = SymTableFactory.VARS.new ResolverBuilder(); ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder types = SymTableFactory.TYPES.new ResolverBuilder(); Predicate<JVariableSig> isFieldAccessible = s -> filterStatic(onlyStatic, s.getSymbol()) && isAccessibleIn(nestRoot, accessPackageName, (JFieldSymbol) s.getSymbol(), accessIsSubtypeOfOwner); Predicate<JClassType> isTypeAccessible = s -> filterStatic(onlyStatic, s.getSymbol()) && isAccessibleIn(nestRoot, accessPackageName, s.getSymbol(), accessIsSubtypeOfOwner); for (JClassType next : enumerator.iterable(t)) { walkSelf(next, isFieldAccessible, isTypeAccessible, fields, types, HashTreePSet.empty(), HashTreePSet.empty()); } return Pair.of(types, fields); } private static boolean filterStatic(boolean onlyStatic, JElementSymbol symbol) { return !onlyStatic || Modifier.isStatic(((JAccessibleElementSymbol) symbol).getModifiers()); } private static void walkSelf(JClassType t, Predicate<? super JVariableSig> isFieldAccessible, Predicate<? super JClassType> isTypeAccessible, ShadowChainBuilder<JVariableSig, ?>.ResolverBuilder fields, ShadowChainBuilder<JTypeMirror, ?>.ResolverBuilder types, // persistent because may change in every path of the recursion final PSet<String> hiddenFields, final PSet<String> hiddenTypes) { // Note that it is possible that this process recurses several // times into the same interface (if it is reachable from several paths) // This is because the set of hidden declarations depends on the // full path, and may be different each time. // Profiling shows that this doesn't occur very often, and adding // a recursion guard is counter-productive performance-wise PSet<String> hiddenTypesInSup = processDeclarations(types, hiddenTypes, isTypeAccessible, t.getDeclaredClasses()); PSet<String> hiddenFieldsInSup = processDeclarations(fields, hiddenFields, isFieldAccessible, t.getDeclaredFields()); // depth first for (JClassType next : DIRECT_STRICT_SUPERTYPES.iterable(t)) { walkSelf(next, isFieldAccessible, isTypeAccessible, fields, types, hiddenFieldsInSup, hiddenTypesInSup); } } private static <S> PSet<String> processDeclarations( ShadowChainBuilder<? super S, ?>.ResolverBuilder builder, PSet<String> hidden, Predicate<? super S> isAccessible, List<? extends S> syms ) { for (S inner : syms) { String simpleName = builder.getSimpleName(inner); if (hidden.contains(simpleName)) { continue; } hidden = hidden.plus(simpleName); if (isAccessible.test(inner)) { builder.appendWithoutDuplicate(inner); } } return hidden; } /** * A general-purpose accessibility check, which can be used if you * know in advance whether the context is a supertype of the class * (ie, whether the sym is accessible if "protected"). * * @param nestRoot Root enclosing type for the context of the reference * @param sym Symbol to test */ public static boolean isAccessibleIn(@NonNull JClassSymbol nestRoot, JAccessibleElementSymbol sym, boolean isOwnerASupertypeOfContext) { return isAccessibleIn(nestRoot, nestRoot.getPackageName(), sym, isOwnerASupertypeOfContext); } /** * Whether the given sym is accessible in some type T, given * the 'nestRoot' of T, and whether T is a subtype of the class * declaring 'sym'. This is a general purpose accessibility check, * albeit a bit low-level (but only needs subtyping to be computed once). */ private static boolean isAccessibleIn(@Nullable JClassSymbol nestRoot, @NonNull String packageName, JAccessibleElementSymbol sym, boolean isOwnerASupertypeOfContext) { int modifiers = sym.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE); switch (modifiers) { case Modifier.PUBLIC: return true; case Modifier.PRIVATE: return nestRoot != null && nestRoot.equals(sym.getEnclosingClass().getNestRoot()); case Modifier.PROTECTED: if (isOwnerASupertypeOfContext) { return true; } // fallthrough case 0: return sym.getPackageName().equals(packageName); default: // fixme this is reachable for invalid declarations, like a private field of an interface throw AssertionUtil.shouldNotReachHere(Modifier.toString(sym.getModifiers())); } } /** * Produce a name resolver that resolves member classes with the * given name declared or inherited by the given type. Each access * may perform a hierarchy traversal, but this handles hidden and * ambiguous declarations nicely. * * @param c Class to search * @param access Context of where the declaration is referenced * @param name Name of the class to find */ public static NameResolver<JClassType> getMemberClassResolver(JClassType c, @NonNull String accessPackageName, @Nullable JClassSymbol access, String name) { return getNamedMemberResolver(c, access, accessPackageName, JClassType::getDeclaredClass, name, JClassType::getSymbol, SymTableFactory.TYPES); } public static NameResolver<FieldSig> getMemberFieldResolver(JClassType c, @NonNull String accessPackageName, @Nullable JClassSymbol access, String name) { return getNamedMemberResolver(c, access, accessPackageName, JClassType::getDeclaredField, name, FieldSig::getSymbol, SymTableFactory.VARS); } private static <S> NameResolver<S> getNamedMemberResolver(JClassType c, @Nullable JClassSymbol access, @NonNull String accessPackageName, BiFunction<? super JClassType, String, ? extends S> getter, String name, Function<? super S, ? extends JAccessibleElementSymbol> symbolGetter, ShadowChainBuilder<? super S, ?> classes) { S found = getter.apply(c, name); if (found != null) { // fast path, doesn't need to check accessibility, etc return CoreResolvers.singleton(name, found); } JClassSymbol nestRoot = access == null ? null : access.getNestRoot(); Predicate<S> isAccessible = s -> { JAccessibleElementSymbol sym = symbolGetter.apply(s); return isAccessibleIn(nestRoot, accessPackageName, sym, isSubtype(access, sym.getEnclosingClass())); }; @SuppressWarnings("unchecked") ShadowChainBuilder<S, ?>.ResolverBuilder builder = (ShadowChainBuilder<S, ?>.ResolverBuilder) classes.new ResolverBuilder(); for (JClassType next : DIRECT_STRICT_SUPERTYPES.iterable(c)) { walkForSingleName(next, isAccessible, name, getter, builder, HashTreePSet.empty()); } return builder.build(); } private static boolean isSubtype(JClassSymbol sub, JClassSymbol sup) { return sub != null && sub.getTypeSystem().typeOf(sub, true).getAsSuper(sup) != null; } private static <S> void walkForSingleName(JClassType t, Predicate<? super S> isAccessible, String name, BiFunction<? super JClassType, String, ? extends S> getter, ShadowChainBuilder<? super S, ?>.ResolverBuilder builder, final PSet<String> hidden) { PSet<String> hiddenInSup = processDeclarations(builder, hidden, isAccessible, listOfNotNull(getter.apply(t, name))); if (!hiddenInSup.isEmpty()) { // found it in this branch // in this method the hidden set is either empty or one element only return; } // depth first for (JClassType next : DIRECT_STRICT_SUPERTYPES.iterable(t)) { walkForSingleName(next, isAccessible, name, getter, builder, hiddenInSup); } } }
25,068
46.659696
183
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/ReferenceCtx.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.internal; import static net.sourceforge.pmd.lang.java.symbols.table.internal.JavaSemanticErrors.AMBIGUOUS_NAME_REFERENCE; import static net.sourceforge.pmd.lang.java.symbols.table.internal.JavaSemanticErrors.CANNOT_RESOLVE_MEMBER; import java.util.HashSet; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.SemanticErrorReporter; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeParameterSymbol; import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.JVariableSig.FieldSig; /** * Context of a usage reference ("in which class does the name occur?"), * which determines accessibility of referenced symbols. The context may * have no enclosing class, eg in the "extends" clause of a toplevel type. * * <p>This is an internal helper class for disambiguation pass */ public final class ReferenceCtx { final JavaAstProcessor processor; final String packageName; final @Nullable JClassSymbol enclosingClass; private ReferenceCtx(JavaAstProcessor processor, String packageName, @Nullable JClassSymbol enclosingClass) { this.processor = processor; this.packageName = packageName; this.enclosingClass = enclosingClass; } public void reportCannotResolveSymbol(JavaNode location, String simpleName) { processor.reportCannotResolveSymbol(location, simpleName); } public static ReferenceCtx root(JavaAstProcessor processor, ASTCompilationUnit root) { return new ReferenceCtx(processor, root.getPackageName(), null); } public ReferenceCtx scopeDownToNested(JClassSymbol newEnclosing) { assert enclosingClass == null || enclosingClass.equals(newEnclosing.getEnclosingClass()) : "Not a child class of the current context (" + this + "): " + newEnclosing; assert newEnclosing.getPackageName().equals(packageName) : "Mismatched package name"; return new ReferenceCtx(processor, packageName, newEnclosing); } public @Nullable FieldSig findStaticField(JTypeDeclSymbol classSym, String name) { if (classSym instanceof JClassSymbol) { JClassType t = (JClassType) classSym.getTypeSystem().typeOf(classSym, false); return JavaResolvers.getMemberFieldResolver(t, packageName, enclosingClass, name).resolveFirst(name); } return null; } public @Nullable JClassSymbol findTypeMember(JTypeDeclSymbol classSym, String name, JavaNode errorLocation) { if (classSym instanceof JClassSymbol) { JClassType c = (JClassType) classSym.getTypeSystem().typeOf(classSym, false); @NonNull List<JClassType> found = JavaResolvers.getMemberClassResolver(c, packageName, enclosingClass, name).resolveHere(name); JClassType result = maybeAmbiguityError(name, errorLocation, found); return result == null ? null : result.getSymbol(); } return null; } <T extends JTypeMirror> T maybeAmbiguityError(String name, JavaNode errorLocation, @NonNull List<? extends T> found) { if (found.isEmpty()) { return null; } else if (found.size() > 1) { // FIXME when type is reachable through several paths, there may be duplicates! Set<? extends T> distinct = new HashSet<>(found); if (distinct.size() == 1) { return distinct.iterator().next(); } processor.getLogger().warning( errorLocation, AMBIGUOUS_NAME_REFERENCE, name, canonicalNameOf(found.get(0).getSymbol()), canonicalNameOf(found.get(1).getSymbol()) ); // fallthrough and use the first one anyway } return found.get(0); } private String canonicalNameOf(JTypeDeclSymbol sym) { if (sym instanceof JClassSymbol) { return ((JClassSymbol) sym).getCanonicalName(); } else { assert sym instanceof JTypeParameterSymbol; return sym.getEnclosingClass().getCanonicalName() + "#" + sym.getSimpleName(); } } public JClassSymbol resolveClassFromBinaryName(String binary) { // we may report inaccessible members too return processor.getSymResolver().resolveClassFromBinaryName(binary); } public static ReferenceCtx ctxOf(ASTAnyTypeDeclaration node, JavaAstProcessor processor, boolean outsideContext) { assert node != null; if (outsideContext) { // then the context is the enclosing of the given type decl JClassSymbol enclosing = node.isTopLevel() ? null : node.getEnclosingType().getSymbol(); return new ReferenceCtx(processor, node.getPackageName(), enclosing); } else { return new ReferenceCtx(processor, node.getPackageName(), node.getSymbol()); } } public void reportUnresolvedMember(JavaNode location, Fallback fallbackStrategy, String memberName, JTypeDeclSymbol owner) { if (owner.isUnresolved()) { // would already have been reported on owner return; } String ownerName = owner instanceof JClassSymbol ? ((JClassSymbol) owner).getCanonicalName() : "type variable " + owner.getSimpleName(); this.processor.getLogger().warning(location, CANNOT_RESOLVE_MEMBER, memberName, ownerName, fallbackStrategy); } public SemanticErrorReporter getLogger() { return processor.getLogger(); } @Override public String toString() { return "ReferenceCtx{" + "packageName='" + packageName + '\'' + ", enclosingClass=" + enclosingClass + '}'; } public JTypeMirror resolveSingleTypeName(JSymbolTable symTable, String image, JavaNode errorLoc) { return maybeAmbiguityError(image, errorLoc, symTable.types().resolve(image)); } public JClassSymbol makeUnresolvedReference(String canonicalName, int typeArity) { return processor.makeUnresolvedReference(canonicalName, typeArity); } public JClassSymbol makeUnresolvedReference(JTypeDeclSymbol outer, String simpleName, int typeArity) { return processor.makeUnresolvedReference(outer, simpleName, typeArity); } /** * Fallback strategy for unresolved stuff. */ public enum Fallback { AMBIGUOUS("ambiguous"), FIELD_ACCESS("a field access"), PACKAGE_NAME("a package name"), TYPE("an unresolved type"); private final String displayName; Fallback(String displayName) { this.displayName = displayName; } @Override public String toString() { return displayName; } } }
7,576
38.878947
139
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/JavaSemanticErrors.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.internal; /** * */ public final class JavaSemanticErrors { // TODO how strict do we need to be here? // many rules don't absolutely need correctness to work // maybe we need to identify separate "levels" of the tree // eg level 0: lexable (CPD) // level 1: parsable (many syntax-only rules, eg UnnecessaryParentheses) // level 2: type-resolved (more complicated rules) /* TODO Checks that are essential for typeres/symtable - no self-reference in initializer - else infinite loop - class or type param doesn't extend/implement itself - else infinite loop - types are well-formed, ie if they are parameterized, then the number of type arguments is the number of formal type params - note that this will be tricky when dealing with unresolved types: for now we give them zero type params, but we must infer that from looking through the file. - else failure when doing type substitution - method reference is well formed, ie a constructor reference has a type as LHS (currently the parser throws, it would need to be more lenient) */ /** * Warning, classpath is misconfigured (or not configured). */ public static final String CANNOT_RESOLVE_SYMBOL = "Cannot resolve symbol {0}"; public static final String INACCESSIBLE_SYMBOL = "Symbol {0} is inaccessible"; /** * We had resolved a prefix, and a suffix is not resolved. This may * mean that the classpath is out-of-date, or the code is incorrect. * Eg {@code System.oute}: {@code System} is resolved, {@code oute} * is not a member of that type. * * <p>This differs from {@link #CANNOT_RESOLVE_SYMBOL} in that for * the latter, it's more probable that the classpath is incorrect. * It is emitted eg when we see an import, so a fully qualified * name, and yet we can't resolve it. * TODO whether it's incorrect code or incorrect classpath is only * a guess, probably we need an option to differentiate the two * (eg in an IDE plugin, it may well be incorrect code, but in a * CLI run, it's more likely to be incorrect classpath). */ public static final String CANNOT_RESOLVE_MEMBER = "Cannot resolve ''{0}'' in {1}, treating it as {2}"; // javac gives a simple "cannot resolve symbol {0}" /** * TODO Should be an error. */ public static final String MALFORMED_GENERIC_TYPE = "Malformed generic type: expected {0} type arguments, got {1}"; // this is an error public static final String EXPECTED_ANNOTATION_TYPE = "Expected an annotation type"; /** * An ambiguous name is completely ambiguous. We don't have info * about it at all, classpath is incomplete or code is incorrect. * Eg {@code package.that.doesnt.exist.Type} */ public static final String CANNOT_RESOLVE_AMBIGUOUS_NAME = "Cannot resolve ambiguous name {0}, treating it as {1}"; public static final String AMBIGUOUS_NAME_REFERENCE = "Reference ''{0}'' is ambiguous, both {1} and {2} match"; private JavaSemanticErrors() { // utility class } }
3,359
43.210526
159
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/internal/SymbolChainBuilder.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.symbols.table.internal; import net.sourceforge.pmd.lang.java.symbols.JElementSymbol; import net.sourceforge.pmd.lang.java.symbols.table.ScopeInfo; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainBuilder; class SymbolChainBuilder<S extends JElementSymbol> extends ShadowChainBuilder<S, ScopeInfo> { @Override public String getSimpleName(S sym) { return sym.getSimpleName(); } }
549
29.555556
93
java