[java] Fix grammar for <> in Java 1.8

- Fixes #888
 - Allow the contents of an anonymous class to use diamong notation, but
the anonymous class itself can't use it
This commit is contained in:
Juan Martín Sotuyo Dodero
2018-01-29 14:10:40 -03:00
parent 53fa98a672
commit f9df6ed01e
2 changed files with 33 additions and 3 deletions

View File

@ -1,4 +1,7 @@
/**
* Fixes #888 [java] ParseException occurs with valid '<>' in Java 1.8 mode
* Juan Martin Sotuyo Dodero 01/2018
*====================================================================
* Fixes #793 [java] Parser error with private method in nested classes in interfaces
* Andreas Dangel 12/2017
*====================================================================
@ -333,9 +336,9 @@ public class JavaParser {
private void checkForBadAnonymousDiamondUsage() {
if (jdkVersion < 9) {
ASTAllocationExpression node = (ASTAllocationExpression)jjtree.peekNode();
ASTTypeArguments types = node.getFirstDescendantOfType(ASTTypeArguments.class);
ASTTypeArguments types = node.getFirstChildOfType(ASTClassOrInterfaceType.class).getFirstChildOfType(ASTTypeArguments.class);
if (node.isAnonymousClass() && types != null && types.isDiamond()) {
throwParseException("Cannot use '<>' with anonymous inner classes when running in JDK inferior to 9 mode!");
throwParseException("Cannot use '<>' with anonymous inner classes when running in JDK inferior to 9 mode!");
}
}
}
@ -2026,8 +2029,8 @@ void AllocationExpression():
{ inInterface = inInterfaceOld; } // always restore the flag after leaving the node
]
)
{ checkForBadAnonymousDiamondUsage(); }
)
{ checkForBadAnonymousDiamondUsage(); }
}
/*

View File

@ -35,6 +35,33 @@ public class ParserCornersTest {
+ " TestInnerClassCallsOuterParent.super.toString();\n" + " }\n"
+ " };\n" + " }\n" + "}\n");
}
/**
* #888 PMD 6.0.0 can't parse valid <> under 1.8.
*/
@Test
public void testDiamondUsageJava8() {
parseJava18("public class PMDExceptionTest {\n" +
" private Component makeUI() {\n" +
" String[] model = {\"123456\", \"7890\"};\n" +
" JComboBox<String> comboBox = new JComboBox<>(model);\n" +
" comboBox.setEditable(true);\n" +
" comboBox.setEditor(new BasicComboBoxEditor() {\n" +
" private Component editorComponent;\n" +
" @Override public Component getEditorComponent() {\n" +
" if (editorComponent == null) {\n" +
" JTextField tc = (JTextField) super.getEditorComponent();\n" +
" editorComponent = new JLayer<>(tc, new ValidationLayerUI<>());\n" +
" }\n" +
" return editorComponent;\n" +
" }\n" +
" });\n" +
" JPanel p = new JPanel();\n" +
" p.add(comboBox);\n" +
" return p;\n" +
" }\n" +
"}");
}
@Test
public final void testGetFirstASTNameImageNull() {