j3.27.0.0 working

This commit is contained in:
Mann Patel
2025-10-11 02:02:27 -06:00
parent 6c591bbf37
commit d80c25c5d7
2973 changed files with 383519 additions and 51603 deletions

View File

@@ -0,0 +1,89 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>javaparser-parent</artifactId>
<groupId>com.github.javaparser</groupId>
<version>3.27.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>javaparser-core-testing</artifactId>
<description>The test suite for javaparser-core</description>
<licenses>
<license>
<name>GNU Lesser General Public License</name>
<url>http://www.gnu.org/licenses/lgpl-3.0.html</url>
<distribution>repo</distribution>
</license>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
<comments>A business-friendly OSS license</comments>
</license>
</licenses>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<!-- no need to release this module -->
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<reportFormat>plain</reportFormat>
<failIfNoTests>true</failIfNoTests>
<argLine>@{jacoco.javaagent}</argLine>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.27.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.TestUtils.assertEqualToTextResourceNoEol;
import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.comments.CommentsCollection;
import com.github.javaparser.utils.LineSeparator;
import com.github.javaparser.utils.TestParser;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class CommentsInserterTest {
private String makeFilename(String sampleName) {
return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt";
}
private String makeExpectedFilename(String sampleName) {
return "/com/github/javaparser/issue_samples/" + sampleName + ".java.expected.txt";
}
private ParseResult<CompilationUnit> parseSample(String sampleName) throws IOException {
Provider p = Providers.resourceProvider(makeFilename(sampleName));
return new JavaParser().parse(ParseStart.COMPILATION_UNIT, p);
}
/**
* Issue: "When there is a String constant "\\" compilationUnit ignores all further comments"
*/
@Test
void issue290() throws IOException {
ParseResult<CompilationUnit> result = this.parseSample("Issue290");
CommentsCollection cc = result.getCommentsCollection().get();
assertEquals(1, cc.getLineComments().size());
assertEquals(1, cc.getJavadocComments().size());
}
@Test
void issue624() throws IOException {
this.parseSample("Issue624");
// Should not fail
}
@Test
void issue200EnumConstantsWithCommentsForceVerticalAlignment() {
CompilationUnit cu =
TestParser.parseCompilationUnit("public enum X {" + LineSeparator.SYSTEM + " /** const1 javadoc */"
+ LineSeparator.SYSTEM + " BORDER_CONSTANT,"
+ LineSeparator.SYSTEM + " /** const2 javadoc */"
+ LineSeparator.SYSTEM + " ANOTHER_CONSTANT"
+ LineSeparator.SYSTEM + "}");
assertEqualsStringIgnoringEol(
"public enum X {\n" + "\n"
+ " /**\n"
+ " * const1 javadoc\n"
+ " */\n"
+ " BORDER_CONSTANT,\n"
+ " /**\n"
+ " * const2 javadoc\n"
+ " */\n"
+ " ANOTHER_CONSTANT\n"
+ "}\n",
cu.toString());
}
@Test
void issue234LosingCommentsInArrayInitializerExpr() {
CompilationUnit cu = TestParser.parseCompilationUnit("@Anno(stuff={" + LineSeparator.SYSTEM + " // Just,"
+ LineSeparator.SYSTEM + " // an,"
+ LineSeparator.SYSTEM + " // example"
+ LineSeparator.SYSTEM + "})"
+ LineSeparator.SYSTEM + "class ABC {"
+ LineSeparator.SYSTEM + ""
+ LineSeparator.SYSTEM + "}");
assertEqualsStringIgnoringEol(
"@Anno(stuff = {// Just,\n" + "// an,\n" + "// example\n" + "})\n" + "class ABC {\n" + "}\n",
cu.toString());
}
@Test
void issue412() throws IOException {
CompilationUnit cu = parseSample("Issue412").getResult().get();
assertEqualToTextResourceNoEol(makeExpectedFilename("Issue412"), cu.toString());
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.TestUtils.getNodeStartingAtPosition;
import static com.github.javaparser.utils.TestUtils.parseFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.CharLiteralExpr;
import com.github.javaparser.utils.ExtractingVisitors;
import java.util.List;
import org.junit.jupiter.api.Test;
class ExpectedTokensTest {
@Test
void testCharEscapeSequences() {
CompilationUnit compilationUnit = parseFile("/com/github/javaparser/EscapeSequences.java");
List<CharLiteralExpr> chars = ExtractingVisitors.extractCharLiteralExprs(compilationUnit);
assertEquals(23, chars.size());
assertTokenValue(chars, 7, 17, "\\\\");
assertTokenValue(chars, 7, 23, "\\u005C\\u005C");
assertTokenValue(chars, 7, 39, "\\u005c\\u005c");
assertTokenValue(chars, 9, 17, "\\n");
assertTokenValue(chars, 9, 23, "\\u005cn");
assertTokenValue(chars, 9, 34, "\\u005Cn");
assertTokenValue(chars, 11, 17, "\\r");
assertTokenValue(chars, 11, 23, "\\u005cr");
assertTokenValue(chars, 11, 34, "\\u005Cr");
assertTokenValue(chars, 13, 17, "\\t");
assertTokenValue(chars, 13, 23, "\\u005ct");
assertTokenValue(chars, 13, 34, "\\u005Ct");
assertTokenValue(chars, 15, 17, "\\b");
assertTokenValue(chars, 15, 23, "\\u005cb");
assertTokenValue(chars, 15, 34, "\\u005Cb");
assertTokenValue(chars, 17, 17, "\\f");
assertTokenValue(chars, 17, 23, "\\u005cf");
assertTokenValue(chars, 17, 34, "\\u005Cf");
assertTokenValue(chars, 19, 17, "\\'");
assertTokenValue(chars, 19, 23, "\\u005c'");
assertTokenValue(chars, 21, 17, "\\\"");
assertTokenValue(chars, 21, 23, "\\u005c\"");
assertTokenValue(chars, 21, 34, "\\u005C\"");
}
private void assertTokenValue(List<CharLiteralExpr> chars, int line, int col, String expectedTokenValue) {
CharLiteralExpr expr = getNodeStartingAtPosition(chars, line, col);
assertEquals(expectedTokenValue, expr.getValue(), "Node at " + line + "," + col);
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.StaticJavaParser.parseResource;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class GeneratedJavaParserTokenManagerTest {
private String makeFilename(String sampleName) {
return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt";
}
@Test
void issue1003() throws IOException {
parseResource(makeFilename("issue1003"));
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.ast.CompilationUnit;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Issue1017Test {
@Test()
void test() {
String code = "class X{int x(){ a(1+1 -> 10);}}";
Assertions.assertThrows(ParseProblemException.class, () -> {
CompilationUnit cu = StaticJavaParser.parse(code);
});
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.expr.LambdaExpr;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
/**
* Tests related to https://github.com/javaparser/javaparser/issues/2482.
*/
public class Issue2482Test {
@Test
public void commentBeforeLambda() {
LambdaExpr le = StaticJavaParser.parseExpression(
"// a comment before parent" + System.lineSeparator() + "()->{return 1;}");
assertTrue(le.getComment().isPresent());
assertTrue(le.getOrphanComments().isEmpty());
assertEquals(0, le.getAllContainedComments().size());
}
@Test
public void commentBeforeBlock() {
Statement st = StaticJavaParser.parseBlock(
"// a comment before parent" + System.lineSeparator() + "{ if (file != null) {} }");
assertTrue(st.getComment().isPresent());
assertTrue(st.getOrphanComments().isEmpty());
assertEquals(0, st.getAllContainedComments().size());
}
@Test
public void commentBeforeIfStatement() {
Statement st = StaticJavaParser.parseStatement(
"// a comment before parent" + System.lineSeparator() + "if (file != null) {}");
assertTrue(st.getComment().isPresent());
assertTrue(st.getOrphanComments().isEmpty());
assertEquals(0, st.getAllContainedComments().size());
}
@Test
public void commentBeforeAssignment() {
Statement st = StaticJavaParser.parseStatement("// a comment" + System.lineSeparator() + "int x = 3;");
assertTrue(st.getComment().isPresent());
assertTrue(st.getOrphanComments().isEmpty());
assertEquals(0, st.getAllContainedComments().size());
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.CompilationUnit;
import java.io.StringReader;
import org.junit.jupiter.api.Test;
public class Issue3064Test {
@Test
public void test0() {
String str = "import java.util.function.Supplier;\n" + "\n"
+ "public class MyClass {\n"
+ "\n"
+ " public MyClass() {\n"
+ " Supplier<String> aStringSupplier = false ? () -> \"\" : true ? () -> \"\" : () -> \"path\";\n"
+ " }\n"
+ "}\n";
JavaParser parser = new JavaParser();
ParseResult<CompilationUnit> unitOpt = parser.parse(new StringReader(str));
unitOpt.getProblems().stream().forEach(p -> System.err.println(p.toString()));
CompilationUnit unit = unitOpt.getResult().orElseThrow(() -> new IllegalStateException("Could not parse file"));
assertEquals(str, unit.toString());
}
@Test
public void test1() {
String str = "public class MyClass {\n" + " {\n"
+ " Supplier<String> aStringSupplier = false ? () -> \"F\" : true ? () -> \"T\" : () -> \"path\";\n"
+ " }\n"
+ "}";
CompilationUnit unit = StaticJavaParser.parse(str);
assertEquals(str.replace("\n", ""), unit.toString().replace("\n", ""));
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import com.github.javaparser.ParserConfiguration.LanguageLevel;
import org.junit.jupiter.api.Test;
public class Issue3577Test {
@Test
public void test() {
String str = "public class MyClass {\n"
+ " public static void main(String args[]) {\n"
+ " System.out.println(\"Hello\\sWorld\");\n"
+ " }\n"
+ "}";
ParserConfiguration config = new ParserConfiguration().setLanguageLevel(LanguageLevel.JAVA_15);
StaticJavaParser.setConfiguration(config);
assertDoesNotThrow(() -> StaticJavaParser.parse(str));
// unitOpt.getProblems().stream().forEach(p -> System.err.println(p.toString()));
}
}

View File

@@ -0,0 +1,284 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.modules.ModuleDeclaration;
import com.github.javaparser.ast.modules.ModuleDirective;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class JavaParserAdapterTest {
private final JavaParser javaParser = Mockito.spy(JavaParser.class);
private final JavaParserAdapter adapter = new JavaParserAdapter(javaParser);
@Test
void of_withValidParser() {
JavaParserAdapter actualAdapter = JavaParserAdapter.of(javaParser);
assertSame(javaParser, actualAdapter.getParser());
assertSame(javaParser.getParserConfiguration(), adapter.getParserConfiguration());
}
@Test
void parse_withSourceCode() {
CompilationUnit cu = adapter.parse("class A {}");
Optional<ClassOrInterfaceDeclaration> classA = cu.findFirst(ClassOrInterfaceDeclaration.class);
assertTrue(classA.isPresent());
assertEquals("A", classA.get().getNameAsString());
Mockito.verify(javaParser).parse("class A {}");
}
@Test
void parse_withInvalidSourceCode() {
assertThrows(ParseProblemException.class, () -> adapter.parse("class A"));
}
@Test
void parse_withSourceCodeFromInputStream() {
InputStream is = new ByteArrayInputStream("class A {}".getBytes(StandardCharsets.UTF_8));
CompilationUnit cu = adapter.parse(is);
Optional<ClassOrInterfaceDeclaration> classA = cu.findFirst(ClassOrInterfaceDeclaration.class);
assertTrue(classA.isPresent());
assertEquals("A", classA.get().getNameAsString());
Mockito.verify(javaParser).parse(is);
}
@Test
void parse_withSourceCodeFromReader() {
Reader reader = new CharArrayReader("class A {}".toCharArray());
CompilationUnit cu = adapter.parse(reader);
Optional<ClassOrInterfaceDeclaration> classA = cu.findFirst(ClassOrInterfaceDeclaration.class);
assertTrue(classA.isPresent());
assertEquals("A", classA.get().getNameAsString());
Mockito.verify(javaParser).parse(reader);
}
@Test
void parseBlock_withValidSource() {
BlockStmt block = adapter.parseBlock("{ System.out.println(\"Hello world!\"); }");
assertEquals(1, block.getStatements().size());
Mockito.verify(javaParser).parseBlock("{ System.out.println(\"Hello world!\"); }");
}
@Test
void parseStatement_withValidSource() {
Statement statement = adapter.parseStatement("break;");
assertTrue(statement.isBreakStmt());
Mockito.verify(javaParser).parseStatement("break;");
}
@Test
void parseImport_withValidSource() {
ImportDeclaration importDecl = adapter.parseImport("import java.util.Optional;");
assertEquals("Optional", importDecl.getName().getIdentifier());
Mockito.verify(javaParser).parseImport("import java.util.Optional;");
}
@Test
void parseExpression_withValidSource() {
Expression expression = adapter.parseExpression("System.out.println(\"Hello world!\")");
assertTrue(expression.isMethodCallExpr());
Mockito.verify(javaParser).parseExpression("System.out.println(\"Hello world!\")");
}
@Test
void parseAnnotation_withValidSource() {
AnnotationExpr annotation = adapter.parseAnnotation("@Test");
assertEquals("Test", annotation.getNameAsString());
Mockito.verify(javaParser).parseAnnotation("@Test");
}
@Test
void parseAnnotationBodyDeclaration_withValidSource() {
BodyDeclaration<?> annotationBody = adapter.parseAnnotationBodyDeclaration("@interface Test{}");
assertTrue(annotationBody.isAnnotationDeclaration());
Mockito.verify(javaParser).parseAnnotationBodyDeclaration("@interface Test{}");
}
@Test
void parseBodyDeclaration_withValidSource() {
BodyDeclaration<?> interfaceBody = adapter.parseBodyDeclaration("interface CustomInterface {}");
assertTrue(interfaceBody.isClassOrInterfaceDeclaration());
Mockito.verify(javaParser).parseBodyDeclaration("interface CustomInterface {}");
}
@Test
void parseClassOrInterfaceType_withValidSource() {
ClassOrInterfaceType customType = adapter.parseClassOrInterfaceType("CustomInterface");
assertTrue(customType.isClassOrInterfaceType());
Mockito.verify(javaParser).parseClassOrInterfaceType("CustomInterface");
}
@Test
void parseType_withValidSource() {
Type customType = adapter.parseType("int");
assertTrue(customType.isPrimitiveType());
Mockito.verify(javaParser).parseType("int");
}
@Test
void parseVariableDeclarationExpr_withValidSource() {
VariableDeclarationExpr variable = adapter.parseVariableDeclarationExpr("final int x = 0");
assertTrue(variable.isFinal());
Mockito.verify(javaParser).parseVariableDeclarationExpr("final int x = 0");
}
@Test
void parseExplicitConstructorInvocationStmt_withValidSource() {
ExplicitConstructorInvocationStmt statement = adapter.parseExplicitConstructorInvocationStmt("super();");
assertTrue(statement.getArguments().isEmpty());
Mockito.verify(javaParser).parseExplicitConstructorInvocationStmt("super();");
}
@Test
void parseName_withValidSource() {
Name name = adapter.parseName("com.github.javaparser.JavaParser");
assertEquals("JavaParser", name.getIdentifier());
Mockito.verify(javaParser).parseName("com.github.javaparser.JavaParser");
}
@Test
void parseSimpleName_withValidSource() {
SimpleName name = adapter.parseSimpleName("JavaParser");
assertEquals("JavaParser", name.getIdentifier());
Mockito.verify(javaParser).parseSimpleName("JavaParser");
}
@Test
void parseParameter_withValidSource() {
Parameter parameter = adapter.parseParameter("String foo");
assertEquals("foo", parameter.getNameAsString());
Mockito.verify(javaParser).parseParameter("String foo");
}
@Test
void parsePackageDeclaration_withValidSource() {
PackageDeclaration packageDeclaration = adapter.parsePackageDeclaration("package com.github.javaparser;");
assertEquals("com.github.javaparser", packageDeclaration.getNameAsString());
Mockito.verify(javaParser).parsePackageDeclaration("package com.github.javaparser;");
}
@Test
void parseTypeDeclaration_withValidSource() {
TypeDeclaration<?> typeDeclaration = adapter.parseTypeDeclaration("class A {}");
assertEquals("A", typeDeclaration.getNameAsString());
Mockito.verify(javaParser).parseTypeDeclaration("class A {}");
}
@Test
void parseModuleDeclaration_withValidSource() {
ModuleDeclaration moduleDeclaration = adapter.parseModuleDeclaration("module X {}");
assertEquals("X", moduleDeclaration.getNameAsString());
Mockito.verify(javaParser).parseModuleDeclaration("module X {}");
}
@Test
void parseModuleDirective_withValidSource() {
ModuleDirective moduleDirective = adapter.parseModuleDirective("opens X;");
assertTrue(moduleDirective.isModuleOpensDirective());
Mockito.verify(javaParser).parseModuleDirective("opens X;");
}
@Test
void parseTypeParameter_withValidSource() {
TypeParameter typeParameter = adapter.parseTypeParameter("T extends Object");
assertEquals("T", typeParameter.getNameAsString());
Mockito.verify(javaParser).parseTypeParameter("T extends Object");
}
@Test
void parseMethodDeclaration_withValidSource() {
MethodDeclaration methodDeclaration = adapter.parseMethodDeclaration("void test() {}");
assertEquals("test", methodDeclaration.getNameAsString());
Mockito.verify(javaParser).parseMethodDeclaration("void test() {}");
}
}

View File

@@ -0,0 +1,426 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.BLEEDING_EDGE;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.CURRENT;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.Range.range;
import static com.github.javaparser.StaticJavaParser.*;
import static com.github.javaparser.utils.TestUtils.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.AnnotationMemberDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ForStmt;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.IntersectionType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.printer.YamlPrinter;
import com.github.javaparser.utils.LineSeparator;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JavaParserTest {
@BeforeEach
void setToLatestJava() {
StaticJavaParser.getConfiguration().setLanguageLevel(BLEEDING_EDGE);
}
@AfterEach
void resetJavaLevel() {
StaticJavaParser.getConfiguration().setLanguageLevel(CURRENT);
}
@Test
void rangeOfAnnotationMemberDeclarationIsCorrect() {
String code = "@interface AD { String foo(); }";
CompilationUnit cu = parse(code);
AnnotationMemberDeclaration memberDeclaration =
cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration();
assertTrue(memberDeclaration.hasRange());
assertEquals(
new Range(new Position(1, 17), new Position(1, 29)),
memberDeclaration.getRange().get());
}
@Test
void testSourcePositionsWithUnicodeEscapes() {
String code = "@interface AD \\u007B String foo(); \\u007D";
CompilationUnit cu = parseWithUnicodeEscapes(code).getResult().get();
AnnotationMemberDeclaration memberDeclaration =
cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration();
assertTrue(memberDeclaration.hasRange());
assertEquals(
new Range(new Position(1, 22), new Position(1, 34)),
memberDeclaration.getRange().get());
}
@Test
void testSourcePositionsWithBrokenUnicodeEscapes() {
// Source positions
// 111111111122222222 2 22333 3333
// 123456789012345678901234567 8 90123 4567
String code = "@interface AD { String X = \"\\uABC\"; }";
ParseResult<CompilationUnit> cu = parseWithUnicodeEscapes(code);
assertFalse(cu.getResult().isPresent());
assertEquals(
"Lexical error at line 1, column 34. Encountered: \"\\\"\" (34), after : \"\\\"\\\\uABC\"",
cu.getProblem(0).getMessage());
}
private static ParseResult<CompilationUnit> parseWithUnicodeEscapes(String code) {
ParserConfiguration config = new ParserConfiguration();
config.setPreprocessUnicodeEscapes(true);
return new JavaParser(config).parse(code);
}
@Test
void rangeOfAnnotationMemberDeclarationWithArrayTypeIsCorrect() {
String code = "@interface AD { String[] foo(); }";
CompilationUnit cu = parse(code);
AnnotationMemberDeclaration memberDeclaration =
cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration();
assertTrue(memberDeclaration.hasRange());
assertEquals(
new Range(new Position(1, 17), new Position(1, 31)),
memberDeclaration.getRange().get());
}
@Test
void rangeOfArrayCreationLevelWithExpressionIsCorrect() {
String code = "new int[123][456]";
ArrayCreationExpr expression = parseExpression(code);
Optional<Range> range;
range = expression.getLevels().get(0).getRange();
assertTrue(range.isPresent());
assertEquals(new Range(new Position(1, 8), new Position(1, 12)), range.get());
range = expression.getLevels().get(1).getRange();
assertTrue(range.isPresent());
assertEquals(new Range(new Position(1, 13), new Position(1, 17)), range.get());
}
@Test
void rangeOfArrayCreationLevelWithoutExpressionIsCorrect() {
String code = "new int[][]";
ArrayCreationExpr expression = parseExpression(code);
Optional<Range> range;
range = expression.getLevels().get(0).getRange();
assertTrue(range.isPresent());
assertEquals(new Range(new Position(1, 8), new Position(1, 9)), range.get());
range = expression.getLevels().get(1).getRange();
assertTrue(range.isPresent());
assertEquals(new Range(new Position(1, 10), new Position(1, 11)), range.get());
}
@Test
void parseErrorContainsLocation() {
ParseResult<CompilationUnit> result = new JavaParser().parse(COMPILATION_UNIT, provider("class X { // blah"));
Problem problem = result.getProblem(0);
assertEquals(range(1, 9, 1, 17), problem.getLocation().get().toRange().get());
assertEquals(
"Parse error. Found <EOF>, expected one of \";\" \"<\" \"@\" \"abstract\" \"boolean\" \"byte\" \"char\" \"class\" \"default\" \"double\" \"enum\" \"exports\" \"final\" \"float\" \"int\" \"interface\" \"long\" \"module\" \"native\" \"non-sealed\" \"open\" \"opens\" \"permits\" \"private\" \"protected\" \"provides\" \"public\" \"record\" \"requires\" \"sealed\" \"short\" \"static\" \"strictfp\" \"synchronized\" \"to\" \"transient\" \"transitive\" \"uses\" \"void\" \"volatile\" \"when\" \"with\" \"yield\" \"{\" \"}\" <IDENTIFIER>",
problem.getMessage());
assertInstanceOf(ParseException.class, problem.getCause().get());
}
@Test
void parseIntersectionType() {
String code = "(Runnable & Serializable) (() -> {})";
Expression expression = parseExpression(code);
Type type = expression.asCastExpr().getType();
assertTrue(type instanceof IntersectionType);
IntersectionType intersectionType = type.asIntersectionType();
assertEquals(2, intersectionType.getElements().size());
assertTrue(intersectionType.getElements().get(0) instanceof ClassOrInterfaceType);
assertEquals(
"Runnable",
intersectionType.getElements().get(0).asClassOrInterfaceType().getNameAsString());
assertTrue(intersectionType.getElements().get(1) instanceof ClassOrInterfaceType);
assertEquals(
"Serializable",
intersectionType.getElements().get(1).asClassOrInterfaceType().getNameAsString());
}
@Test
void parseArrayInitialization() {
String code = "{1,2,3}";
ArrayInitializerExpr expression = parseArrayInitializerExpr(code);
assertEquals(3, expression.getValues().size());
}
@Test
void rangeOfIntersectionType() {
String code = "class A {" + LineSeparator.SYSTEM
+ " Object f() {" + LineSeparator.SYSTEM
+ " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); "
+ LineSeparator.SYSTEM
+ "}}";
CompilationUnit cu = parse(code);
MethodDeclaration methodDeclaration =
cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
ReturnStmt returnStmt =
methodDeclaration.getBody().get().getStatement(0).asReturnStmt();
CastExpr castExpr = returnStmt.getExpression().get().asCastExpr();
Type type = castExpr.getType();
assertEquals(range(3, 13, 3, 54), type.getRange().get());
}
@Test
void rangeOfCast() {
String code = "class A {" + LineSeparator.SYSTEM
+ " Object f() {" + LineSeparator.SYSTEM
+ " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); "
+ LineSeparator.SYSTEM
+ "}}";
CompilationUnit cu = parse(code);
MethodDeclaration methodDeclaration =
cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
ReturnStmt returnStmt =
methodDeclaration.getBody().get().getStatement(0).asReturnStmt();
CastExpr castExpr = returnStmt.getExpression().get().asCastExpr();
assertEquals(range(3, 12, 3, 101), castExpr.getRange().get());
}
@Test
void rangeOfCastNonIntersection() {
String code = "class A {" + LineSeparator.SYSTEM
+ " Object f() {" + LineSeparator.SYSTEM
+ " return (Comparator<Map.Entry<K, V>> )(c1, c2) -> c1.getKey().compareTo(c2.getKey()); "
+ LineSeparator.SYSTEM
+ "}}";
CompilationUnit cu = parse(code);
MethodDeclaration methodDeclaration =
cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
ReturnStmt returnStmt =
methodDeclaration.getBody().get().getStatement(0).asReturnStmt();
CastExpr castExpr = returnStmt.getExpression().get().asCastExpr();
assertEquals(range(3, 12, 3, 101), castExpr.getRange().get());
}
@Test
void rangeOfLambda() {
String code = "class A {" + LineSeparator.SYSTEM
+ " Object f() {" + LineSeparator.SYSTEM
+ " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); "
+ LineSeparator.SYSTEM
+ "}}";
CompilationUnit cu = parse(code);
MethodDeclaration methodDeclaration =
cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
ReturnStmt returnStmt =
methodDeclaration.getBody().get().getStatement(0).asReturnStmt();
CastExpr castExpr = returnStmt.getExpression().get().asCastExpr();
LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr();
assertEquals(range(3, 56, 3, 101), lambdaExpr.getRange().get());
assertEquals(
GeneratedJavaParserConstants.LPAREN,
lambdaExpr.getTokenRange().get().getBegin().getKind());
assertEquals(
GeneratedJavaParserConstants.RPAREN,
lambdaExpr.getTokenRange().get().getEnd().getKind());
}
@Test
void rangeOfLambdaBody() {
String code = "class A {" + LineSeparator.SYSTEM
+ " Object f() {" + LineSeparator.SYSTEM
+ " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); "
+ LineSeparator.SYSTEM
+ "}}";
CompilationUnit cu = parse(code);
MethodDeclaration methodDeclaration =
cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
ReturnStmt returnStmt =
methodDeclaration.getBody().get().getStatement(0).asReturnStmt();
CastExpr castExpr = returnStmt.getExpression().get().asCastExpr();
LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr();
Statement lambdaBody = lambdaExpr.getBody();
assertEquals(range(3, 68, 3, 101), lambdaBody.getRange().get());
}
@Test
void testNotStoringTokens() {
JavaParser javaParser = new JavaParser(new ParserConfiguration().setStoreTokens(false));
ParseResult<CompilationUnit> result = javaParser.parse(ParseStart.COMPILATION_UNIT, provider("class X{}"));
assertFalse(result.getResult().get().getTokenRange().isPresent());
}
@Test
void trailingCodeIsAnError() {
assertThrows(ParseProblemException.class, () -> parseBlock("{} efijqoifjqefj"));
}
@Test
void trailingWhitespaceIsIgnored() {
BlockStmt blockStmt = parseBlock("{} // hello");
assertEquals("{}", blockStmt.getTokenRange().get().toString());
}
@Test
void parsingInitializedAndUnitializedVarsInForStmt() {
ForStmt forStmt = parseStatement("for(int a,b=0;;){}").asForStmt();
assertEquals(1, forStmt.getInitialization().size());
assertTrue(forStmt.getInitialization().get(0).isVariableDeclarationExpr());
assertEquals(
2,
forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.size());
assertEquals(
"a",
forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(0)
.getNameAsString());
assertEquals(
"b",
forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(1)
.getNameAsString());
assertFalse(forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(0)
.getInitializer()
.isPresent());
assertTrue(forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(1)
.getInitializer()
.isPresent());
}
@Test
void parsingInitializedAndUnitializedVarsInForStmtComplexCase() {
// See issue 1281
ForStmt forStmt =
parseStatement("for(int i, j = array2.length - 1;;){}").asForStmt();
assertEquals(1, forStmt.getInitialization().size());
assertTrue(forStmt.getInitialization().get(0).isVariableDeclarationExpr());
assertEquals(
2,
forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.size());
assertEquals(
"i",
forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(0)
.getNameAsString());
assertEquals(
"j",
forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(1)
.getNameAsString());
assertFalse(forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(0)
.getInitializer()
.isPresent());
assertTrue(forStmt.getInitialization()
.get(0)
.asVariableDeclarationExpr()
.getVariables()
.get(1)
.getInitializer()
.isPresent());
}
@Test
void creatingNewObjectCreationExprShouldDefaultToParsing() {
String className = String.class.getCanonicalName();
ClassOrInterfaceType type = parseClassOrInterfaceType(className);
ObjectCreationExpr expected = parseExpression("new " + className + "()");
ObjectCreationExpr actual = new ObjectCreationExpr(null, type, NodeList.nodeList());
assertEquals(expected, actual);
}
@Test
void parseModuleDeclaration() {
StaticJavaParser.parseModuleDeclaration("module X {}");
}
@Test
void parseModuleDirective() {
StaticJavaParser.parseModuleDirective("opens C;");
}
@Test
void parseTypeParameter() {
StaticJavaParser.parseTypeParameter("T extends Serializable & AttachableListener");
}
@Test
void parseTypeDeclaration() {
StaticJavaParser.parseTypeDeclaration("enum Z {A, B}");
}
@Test
void xxx() {
YamlPrinter.print(StaticJavaParser.parse("class X{}"));
}
@Test
void issue2879() {
StaticJavaParser.parse("public class Test {" + " public void method(int @MyAnno ... param) {}"
+ "}"
+ "@Target(java.lang.annotation.ElementType.TYPE_USE) @interface MyAnno {}");
}
}

View File

@@ -0,0 +1,168 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.GeneratedJavaParserConstants.*;
import static com.github.javaparser.JavaToken.Category.*;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.Range.range;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.expr.Expression;
import java.lang.reflect.Field;
import java.util.Iterator;
import org.junit.jupiter.api.Test;
class JavaTokenTest {
@Test
void testAFewTokens() {
ParseResult<Expression> result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/1 "));
Iterator<JavaToken> iterator =
result.getResult().get().getTokenRange().get().iterator();
assertToken("1", range(1, 1, 1, 1), INTEGER_LITERAL, LITERAL, iterator.next());
assertToken(" ", range(1, 2, 1, 2), SPACE, WHITESPACE_NO_EOL, iterator.next());
assertToken("+", range(1, 3, 1, 3), PLUS, OPERATOR, iterator.next());
assertToken("/*2*/", range(1, 4, 1, 8), MULTI_LINE_COMMENT, COMMENT, iterator.next());
assertToken("1", range(1, 9, 1, 9), INTEGER_LITERAL, LITERAL, iterator.next());
assertToken(" ", range(1, 10, 1, 10), SPACE, WHITESPACE_NO_EOL, iterator.next());
assertToken("", range(1, 10, 1, 10), EOF, WHITESPACE_NO_EOL, iterator.next());
assertFalse(iterator.hasNext());
}
private void assertToken(String image, Range range, int kind, JavaToken.Category category, JavaToken token) {
assertEquals(image, token.getText());
assertEquals(range, token.getRange().get());
assertEquals(kind, token.getKind());
assertEquals(category, token.getCategory());
token.getNextToken()
.ifPresent(nt -> assertEquals(token, nt.getPreviousToken().get()));
token.getPreviousToken()
.ifPresent(pt -> assertEquals(token, pt.getNextToken().get()));
assertTrue(token.getNextToken().isPresent() || token.getPreviousToken().isPresent());
}
@Test
void testAFewImagesForTokenKinds() {
assertEquals("=", new JavaToken(ASSIGN).getText());
// TODO this shouldn't be a space.
assertEquals(" ", new JavaToken(EOF).getText());
assertEquals("*/", new JavaToken(JAVADOC_COMMENT).getText());
}
@Test
void testKindEnum() {
JavaToken.Kind kind = JavaToken.Kind.valueOf(GeneratedJavaParserConstants.ASSERT);
assertEquals(JavaToken.Kind.ASSERT, kind);
assertEquals(GeneratedJavaParserConstants.ASSERT, kind.getKind());
}
/**
* Two places where "generated" token types exist.
* - Firstly, {@link GeneratedJavaParserConstants} which is produced by JavaCC
* - Secondly, {@link JavaToken}, which is produced by JavaParser
* <p>
* This test makes a best-effort attempt to ensure that the two are aligned.
*/
@Test
void test() throws NoSuchFieldException, IllegalAccessException {
final int tokenCount = GeneratedJavaParserConstants.tokenImage.length;
assertEquals(tokenCount, JavaToken.Kind.values().length, "Error - mismatch between number of tokens.");
// Iterate through the JP Tokens, and ensure that it matches the JavaCC tokens.
for (int i = 0; i < tokenCount; i++) {
// Details about the Java Parser Token
JavaToken.Kind jpToken = JavaToken.Kind.valueOf(i);
String jpTokenName = jpToken.name();
int jpTokenNumber = jpToken.getKind();
// Details about the JavaCC Token (using reflection)
Field declaredField = GeneratedJavaParserConstants.class.getDeclaredField(jpTokenName);
String javaCcTokenName = declaredField.getName();
Object javaccTokenNumber = declaredField.get(null); // static fields, therefore null is okay
// Optional printing -- for debugging purposes.
// System.out.println(i + " - " +
// jpTokenName + " (" + jpTokenNumber + ") - " +
// javaCcTokenName + " (" + javaccTokenNumber + ")"
// );
assertEquals(jpTokenName, javaCcTokenName);
assertEquals(
javaccTokenNumber,
jpTokenNumber,
"Error - Likely need to rerun JP Generators following a grammar change." + "\nProblem with `"
+ jpTokenName + "`." + "\nNote mismatch between:"
+ "\n - token #"
+ javaccTokenNumber + " - GeneratedJavaParserConstants (generated using JavaCC)"
+ "\n - token #"
+ jpTokenNumber + " - JavaToken (generated using JP Generators).");
}
}
@Test
void testDeleteToken() {
ParseResult<Expression> result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1+/*2*/1\n"));
TokenRange tokenRange = result.getResult().get().getTokenRange().get();
JavaToken tokenToBeDeleted = tokenRange.getBegin().getNextToken().get();
tokenToBeDeleted.deleteToken();
JavaToken nextTokenAfterDelete = tokenRange.getBegin().getNextToken().get();
JavaToken previous = nextTokenAfterDelete.getPreviousToken().get();
assertNotEquals(tokenToBeDeleted, nextTokenAfterDelete);
assertEquals("/*2*/", nextTokenAfterDelete.getText());
assertEquals("1", previous.getText());
}
@Test
void testFindLastToken() {
ParseResult<Expression> result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/3 "));
TokenRange tokenRange = result.getResult().get().getTokenRange().get();
Iterator<JavaToken> iterator = tokenRange.iterator();
assertToken(
"", range(1, 10, 1, 10), EOF, WHITESPACE_NO_EOL, iterator.next().findLastToken());
// getEnd token in TokenRange is not the same as the last token from findLastToken()
// assertEquals(tokenRange.getEnd(), tokenRange.getBegin().findLastToken());
}
@Test
void testFindFirstToken() {
ParseResult<Expression> result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/3+4"));
Iterator<JavaToken> iterator =
result.getResult().get().getTokenRange().get().iterator();
iterator.next();
iterator.next();
iterator.next();
assertEquals("/*2*/", iterator.next().getText());
assertToken(
"1",
range(1, 1, 1, 1),
INTEGER_LITERAL,
LITERAL,
iterator.next().findFirstToken());
}
}

View File

@@ -0,0 +1,187 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.javadoc.Javadoc;
import com.github.javaparser.javadoc.JavadocBlockTag;
import com.github.javaparser.javadoc.description.JavadocDescription;
import com.github.javaparser.utils.LineSeparator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class JavadocParserTest {
@Test
void parseSimplestContent() {
Assertions.assertEquals(
new Javadoc(JavadocDescription.parseText("A simple line of text")),
JavadocParser.parse("A simple line of text"));
}
@Test
void parseEmptySingleLine() {
Assertions.assertEquals(
new Javadoc(JavadocDescription.parseText("")), JavadocParser.parse(LineSeparator.SYSTEM.asRawString()));
}
@Test
void parseSingleLineWithSpacing() {
assertEquals(
new Javadoc(JavadocDescription.parseText("The line number of the first character of this Token.")),
JavadocParser.parse(" The line number of the first character of this Token. "));
}
@Test
void parseSingleLineWithNewLines() {
assertEquals(
new Javadoc(JavadocDescription.parseText("The string image of the token.")),
JavadocParser.parse(
LineSeparator.SYSTEM + " * The string image of the token." + LineSeparator.SYSTEM + " "));
}
@Test
void parseCommentWithNewLines() {
String text = LineSeparator.SYSTEM + " * The version identifier for this Serializable class."
+ LineSeparator.SYSTEM + " * Increment only if the <i>serialized</i> form of the"
+ LineSeparator.SYSTEM + " * class changes."
+ LineSeparator.SYSTEM + " ";
assertEquals(
new Javadoc(JavadocDescription.parseText("The version identifier for this Serializable class."
+ LineSeparator.SYSTEM + "Increment only if the <i>serialized</i> form of the"
+ LineSeparator.SYSTEM + "class changes.")),
JavadocParser.parse(text));
}
@Test
void parseCommentWithIndentation() {
String text = "Returns a new Token object, by default." + LineSeparator.SYSTEM
+ " * However, if you want, you can create and return subclass objects based on the value of ofKind."
+ LineSeparator.SYSTEM + " *"
+ LineSeparator.SYSTEM + " * case MyParserConstants.ID : return new IDToken(ofKind, image);"
+ LineSeparator.SYSTEM + " *"
+ LineSeparator.SYSTEM + " * to the following switch statement. Then you can cast matchedToken";
assertEquals(
new Javadoc(
JavadocDescription.parseText("Returns a new Token object, by default." + LineSeparator.SYSTEM
+ "However, if you want, you can create and return subclass objects based on the value of ofKind."
+ LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ " case MyParserConstants.ID : return new IDToken(ofKind, image);"
+ LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ "to the following switch statement. Then you can cast matchedToken")),
JavadocParser.parse(text));
}
@Test
void parseBlockTagsAndEmptyDescription() {
String text = LineSeparator.SYSTEM + " * @deprecated"
+ LineSeparator.SYSTEM + " * @see #getEndColumn"
+ LineSeparator.SYSTEM + " ";
assertEquals(
new Javadoc(JavadocDescription.parseText(""))
.addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.DEPRECATED, ""))
.addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.SEE, "#getEndColumn")),
JavadocParser.parse(text));
}
@Test
void parseBlockTagsAndProvideTagName() {
String expectedText = LineSeparator.SYSTEM + " * @unofficial" + LineSeparator.SYSTEM + " " + " ";
Javadoc underTest =
new Javadoc(JavadocDescription.parseText("")).addBlockTag(new JavadocBlockTag("unofficial", ""));
assertEquals(underTest, JavadocParser.parse(expectedText));
assertEquals(1, underTest.getBlockTags().size());
assertEquals("unofficial", underTest.getBlockTags().get(0).getTagName());
}
@Test
void parseParamBlockTags() {
String text = LineSeparator.SYSTEM
+ " * Add a field to this and automatically add the import of the type if needed"
+ LineSeparator.SYSTEM + " *"
+ LineSeparator.SYSTEM + " * @param typeClass the type of the field"
+ LineSeparator.SYSTEM + " * @param name the name of the field"
+ LineSeparator.SYSTEM + " * @param modifiers the modifiers like {@link Modifier#PUBLIC}"
+ LineSeparator.SYSTEM + " * @return the {@link FieldDeclaration} created"
+ LineSeparator.SYSTEM + " ";
Javadoc res = JavadocParser.parse(text);
assertEquals(
new Javadoc(JavadocDescription.parseText(
"Add a field to this and automatically add the import of the type if needed"))
.addBlockTag(JavadocBlockTag.createParamBlockTag("typeClass", "the type of the field"))
.addBlockTag(JavadocBlockTag.createParamBlockTag("name", "the name of the field"))
.addBlockTag(JavadocBlockTag.createParamBlockTag(
"modifiers", "the modifiers like {@link Modifier#PUBLIC}"))
.addBlockTag(new JavadocBlockTag(
JavadocBlockTag.Type.RETURN, "the {@link FieldDeclaration} created")),
res);
}
@Test
void parseMultilineParamBlockTags() {
String text = LineSeparator.SYSTEM
+ " * Add a field to this and automatically add the import of the type if needed"
+ LineSeparator.SYSTEM + " *"
+ LineSeparator.SYSTEM + " * @param typeClass the type of the field"
+ LineSeparator.SYSTEM + " * continued in a second line"
+ LineSeparator.SYSTEM + " * @param name the name of the field"
+ LineSeparator.SYSTEM + " * @param modifiers the modifiers like {@link Modifier#PUBLIC}"
+ LineSeparator.SYSTEM + " * @return the {@link FieldDeclaration} created"
+ LineSeparator.SYSTEM + " ";
Javadoc res = JavadocParser.parse(text);
assertEquals(
new Javadoc(JavadocDescription.parseText(
"Add a field to this and automatically add the import of the type if needed"))
.addBlockTag(JavadocBlockTag.createParamBlockTag(
"typeClass",
"the type of the field" + LineSeparator.SYSTEM + " continued in a second line"))
.addBlockTag(JavadocBlockTag.createParamBlockTag("name", "the name of the field"))
.addBlockTag(JavadocBlockTag.createParamBlockTag(
"modifiers", "the modifiers like {@link Modifier#PUBLIC}"))
.addBlockTag(new JavadocBlockTag(
JavadocBlockTag.Type.RETURN, "the {@link FieldDeclaration} created")),
res);
}
@Test
void startsWithAsteriskEmpty() {
assertEquals(-1, JavadocParser.startsWithAsterisk(""));
}
@Test
void startsWithAsteriskNoAsterisk() {
assertEquals(-1, JavadocParser.startsWithAsterisk(" ciao"));
}
@Test
void startsWithAsteriskAtTheBeginning() {
assertEquals(0, JavadocParser.startsWithAsterisk("* ciao"));
}
@Test
void startsWithAsteriskAfterSpaces() {
assertEquals(3, JavadocParser.startsWithAsterisk(" * ciao"));
}
}

View File

@@ -0,0 +1,121 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest;
import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter;
import com.github.javaparser.utils.LineSeparator;
import java.util.Optional;
import org.junit.jupiter.api.Test;
public class LineSeparatorProcessorTest extends AbstractLexicalPreservingTest {
// TODO: Add more tests outside the "happy path" (e.g. mixed EOL, no EOL, etc.)
/*
* This test case must prevent an UnsupportedOperation Removed throwed by LexicalPreservation when we try to replace an expression
*/
public void doTest(LineSeparator lineSeparator) {
String eol = lineSeparator.asRawString();
considerCode("" + " public class Foo { //comment"
+ eol + " private String a;"
+ eol + " private String b;"
+ eol + " private String c;"
+ eol + " private String d;"
+ eol + " }");
// Note: Expect the platform's EOL character when printing
String expected = "" + " public class Foo { //comment"
+ eol + " private String newField;"
+ eol + " "
+ eol + " private String a;"
+ eol + " private String b;"
+ eol + " private String c;"
+ eol + " private String d;"
+ eol + " }";
// create a new field declaration
VariableDeclarator variable = new VariableDeclarator(new ClassOrInterfaceType("String"), "newField");
FieldDeclaration fd = new FieldDeclaration(new NodeList(Modifier.privateModifier()), variable);
Optional<ClassOrInterfaceDeclaration> cd = cu.findFirst(ClassOrInterfaceDeclaration.class);
// add the new variable
cd.get().getMembers().addFirst(fd);
// should be printed like this
// System.out.println("\n\nOriginal:\n" + original);
// System.out.println("\n\nExpected:\n" + expected);
// but the result is
final String actual = LexicalPreservingPrinter.print(cu);
// System.out.println("\n\nActual:\n" + actual);
// The LineEndingProcessingProvider sets the line ending to the root node.
// Child nodes should then "inherit" then line ending style.
LineSeparator lineSeparator_cu = cu.getLineEndingStyle();
LineSeparator lineSeparator_fd = fd.getLineEndingStyle();
// System.out.println("lineSeparator_cu.describe() = " + lineSeparator_cu.describe());
// System.out.println("lineSeparator_fd.describe() = " + lineSeparator_fd.describe());
// Assert that it has been detected and injected correctly.
LineSeparator detectedLineSeparator = LineSeparator.detect(actual);
assertEquals(lineSeparator, detectedLineSeparator);
assertEquals(lineSeparator, lineSeparator_cu);
assertEquals(lineSeparator, lineSeparator_fd);
// The line ending data is injected at the root node, thus should only exist there.
assertTrue(
cu.containsData(Node.LINE_SEPARATOR_KEY),
"Expected the processor provider to have set the data on the root node.");
assertFalse(
fd.containsData(Node.LINE_SEPARATOR_KEY),
"Expected the line ending value to have been inherited, not set directly");
}
@Test
public void testWithCr() {
doTest(LineSeparator.CR);
}
@Test
public void testWithCrLf() {
doTest(LineSeparator.CRLF);
}
@Test
public void testWithLf() {
doTest(LineSeparator.LF);
}
// TODO: Test for textblocks
}

View File

@@ -0,0 +1,112 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.stmt.LabeledStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.stmt.UnparsableStmt;
import org.junit.jupiter.api.Test;
class ParseErrorRecoveryTest {
private final JavaParser parser = new JavaParser();
@Test
void compilationUnitRecovery() {
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, provider("XXX"))
.getResult()
.get();
assertEquals(UNPARSABLE, cu.getParsed());
}
@Test
void bodystatementSemicolonRecovery() {
MethodDeclaration cu = parser.parse(ParseStart.CLASS_BODY, provider("int x(){X X X;}"))
.getResult()
.get()
.asMethodDeclaration();
Statement xxx = cu.getBody().get().getStatements().get(0);
assertEquals(UNPARSABLE, xxx.getParsed());
}
@Test
void bodystatementClosingBraceRecovery() {
MethodDeclaration cu = parser.parse(ParseStart.CLASS_BODY, provider("int x(){X X X}"))
.getResult()
.get()
.asMethodDeclaration();
Statement xxx = cu.getBody().get();
assertEquals(1, xxx.getChildNodes().size());
assertTrue(xxx.getChildNodes().get(0) instanceof UnparsableStmt);
}
@Test
void labeledStatementSemicolonRecovery() {
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, provider("class X{int x(){aaa:X X X;}}"))
.getResult()
.get();
LabeledStmt xxx = cu.getClassByName("X")
.get()
.getMethods()
.get(0)
.getBody()
.get()
.getStatements()
.get(0)
.asLabeledStmt();
assertEquals(UNPARSABLE, xxx.getStatement().getParsed());
}
@Test
void testIncompleteClassParse() {
CompilationUnit compilationUnit = parser.parse(getClass().getResourceAsStream("Sample.java"))
.getResult()
.get();
assertFalse(compilationUnit.getTypes().isEmpty());
assertFalse(compilationUnit.getTypes().get(0).getMembers().isEmpty());
}
@Test
void testBodyRecoverIf() {
CompilationUnit compilationUnit = parser.parse(
ParseStart.COMPILATION_UNIT, provider("class A { int a() { if() }}"))
.getResult()
.get();
assertFalse(compilationUnit.getTypes().isEmpty());
assertEquals(1, compilationUnit.getTypes().get(0).getMembers().size());
}
@Test
void testBodyRecoverLevel() {
CompilationUnit compilationUnit = parser.parse(
ParseStart.COMPILATION_UNIT, provider("class A { int a() { int b = if (true) {int c = 5;} }}"))
.getResult()
.get();
assertFalse(compilationUnit.getTypes().isEmpty());
assertEquals(1, compilationUnit.getTypes().get(0).getMembers().size());
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.RAW;
import static com.github.javaparser.Providers.provider;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class ParserConfigurationTest {
@Test
void storeNoTokens() {
ParseResult<CompilationUnit> result = new JavaParser(new ParserConfiguration().setStoreTokens(false))
.parse(ParseStart.COMPILATION_UNIT, provider("class X{}"));
assertFalse(result.getResult().get().getTokenRange().isPresent());
assertTrue(result.getResult().get().findAll(Node.class).stream()
.noneMatch(node -> node.getTokenRange().isPresent()));
}
@Test
void noProblemsHere() {
ParseResult<Statement> result =
new JavaParser(new ParserConfiguration().setLanguageLevel(RAW)).parse(STATEMENT, provider("try{}"));
assertTrue(result.isSuccessful());
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.UnicodeEscapeProcessingProviderTest.process;
import static com.github.javaparser.UnicodeEscapeProcessingProviderTest.provider;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.UnicodeEscapeProcessingProvider.PositionMapping;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Test case for {@link PositionMapping}.
*
* @author <a href="mailto:bhu@top-logic.com">Bernhard Haumacher</a>
*/
@SuppressWarnings("javadoc")
public class PositionMappingTest {
@Test
public void testNoMapping() throws IOException {
List<List<String>> input =
lines(line("Hello World !\n"), line("Next Line\r"), line("Third Line\r\n"), line("Fourth Line."));
String inputText = text(input);
UnicodeEscapeProcessingProvider provider = provider(inputText);
String outputText = process(provider);
assertEquals(inputText, outputText);
PositionMapping mapping = provider.getPositionMapping();
assertTrue(mapping.isEmpty());
assertEquals(4, provider.getInputCounter().getLine());
assertEquals(4, provider.getOutputCounter().getLine());
assertSame(PositionMapping.PositionUpdate.NONE, mapping.lookup(new Position(10000, 1)));
}
@Test
public void testEncodedLineFeed() throws IOException {
List<List<String>> input = lines(line("B", "\\u000A", "C"));
List<List<String>> output = lines(line("B", "\n"), line("C"));
checkConvert(input, output);
}
@Test
public void testComplexMapping() throws IOException {
List<List<String>> input = lines(
// Character positions:
// 111 1 11111 1222 2 2222 2
// 1 2 34567 89012 3 45678 9012 3 45678 9
line(
"H",
"\\u00E4",
"llo W",
"\\u00F6",
"rld!",
"\\u000A",
"123 N",
"\\u00E4",
"xt Line",
"\\u000D",
"Third Line",
"\r\n"),
line("Fo", "\\u00FC", "rth Line."));
List<List<String>> output = lines(
line("H", "ä", "llo W", "ö", "rld!", "\n"),
line("123 N", "ä", "xt Line", "\r"),
line("Third Line", "\r\n"),
line("Fo", "ü", "rth Line."));
checkConvert(input, output);
}
private void checkConvert(List<List<String>> input, List<List<String>> output) throws IOException {
UnicodeEscapeProcessingProvider provider = provider(text(input));
String decoded = process(provider);
assertEquals(text(output), decoded);
PositionMapping mapping = provider.getPositionMapping();
// Coarse grained test.
assertEquals(input.size(), provider.getInputCounter().getLine());
assertEquals(output.size(), provider.getOutputCounter().getLine());
// Fine grained test.
int inPosLine = 1;
int inPosColumn = 1;
int outPosLine = 1;
int outPosColumn = 1;
Iterator<List<String>> outLineIt = output.iterator();
List<String> outLine = outLineIt.next();
Iterator<String> outPartIt = outLine.iterator();
String outPart = outPartIt.next();
boolean outFinished = false;
for (List<String> inLine : input) {
for (String inPart : inLine) {
assertFalse(outFinished);
Position inPos = new Position(inPosLine, inPosColumn);
Position outPos = new Position(outPosLine, outPosColumn);
Position transfomedOutPos = mapping.transform(outPos);
assertEquals(
inPos,
transfomedOutPos,
"Position mismatch at '" + outPart + "' " + outPos + " -> '" + inPart + "' " + inPos + ".");
outPosColumn += outPart.length();
inPosColumn += inPart.length();
if (!outPartIt.hasNext()) {
if (outLineIt.hasNext()) {
outPartIt = outLineIt.next().iterator();
outPosLine++;
outPosColumn = 1;
outPart = outPartIt.next();
} else {
outFinished = true;
}
} else {
outPart = outPartIt.next();
}
}
inPosColumn = 1;
inPosLine++;
}
}
private static String text(List<List<String>> input) {
StringBuilder result = new StringBuilder();
for (List<String> line : input) {
for (String part : line) {
result.append(part);
}
}
return result.toString();
}
@SafeVarargs
private static List<String> line(String... parts) {
return Arrays.asList(parts);
}
@SafeVarargs
private static List<List<String>> lines(List<String>... lines) {
return Arrays.asList(lines);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class PositionTest {
@Test
public void testOrIfInvalid() {
Position p1 = new Position(1, 1);
Position p2 = new Position(2, 2);
assertEquals(p1, p1.orIfInvalid(p2));
Position invalid = new Position(0, 0);
Position invalid2 = new Position(0, 1);
assertEquals(p1, invalid.orIfInvalid(p1));
assertEquals(invalid2, invalid2.orIfInvalid(invalid));
}
@Test
public void testPositionExceptionFormat() {
IllegalArgumentException thrown1 =
Assertions.assertThrows(IllegalArgumentException.class, () -> new Position(-10, 1));
assertEquals("Can't position at line -10", thrown1.getMessage());
IllegalArgumentException thrown2 =
Assertions.assertThrows(IllegalArgumentException.class, () -> new Position(1, -10));
assertEquals("Can't position at column -10", thrown2.getMessage());
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.TestUtils.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ProblemTest {
@Test
void testSimpleGetters() {
Problem problem = new Problem("Parse error", TokenRange.INVALID, new Exception());
assertEquals(TokenRange.INVALID, problem.getLocation().get());
assertEquals("Parse error", problem.getMessage());
assertInstanceOf(Exception.class, problem.getCause().get());
}
@Test
void testVerboseMessage() {
Problem problem = new Problem("Parse error", TokenRange.INVALID, null);
assertEquals("(line ?,col ?) Parse error", problem.getVerboseMessage());
}
@Test
void testVerboseMessageWithoutLocation() {
Problem problem = new Problem("Parse error", null, null);
assertEquals("Parse error", problem.getVerboseMessage());
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.CompilationUnit;
import java.io.IOException;
import java.nio.charset.Charset;
import org.junit.jupiter.api.Test;
class ProvidersTest {
@Test
void testResourceProvider() throws IOException {
Provider provider = Providers.resourceProvider("com/github/javaparser/issue_samples/Issue290.java.txt");
assertNotNull(provider);
JavaParser parser = new JavaParser();
ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
assertTrue(parse.isSuccessful());
}
@Test
void testResourceProviderWithWrongEncoding() throws IOException {
Provider provider = Providers.resourceProvider("com/github/javaparser/TestFileIso88591.java");
assertNotNull(provider);
JavaParser parser = new JavaParser();
ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
assertFalse(parse.isSuccessful());
}
@Test
void testResourceProviderWithEncoding() throws IOException {
Provider provider = Providers.resourceProvider(
"com/github/javaparser/TestFileIso88591.java", Charset.forName("ISO-8859-1"));
assertNotNull(provider);
JavaParser parser = new JavaParser();
ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
assertTrue(parse.isSuccessful());
}
}

View File

@@ -0,0 +1,297 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class RangeTest {
private final Position pos1 = new Position(10, 11);
private final Position pos2 = new Position(20, 21);
private final Range range_orderedPositions = Range.range(pos1, pos2);
private final Range range_reversedPositions = Range.range(pos2, pos1);
private final Position posA1 = new Position(1, 1);
private final Position posB1 = new Position(2, 1);
private final Position posC1 = new Position(3, 1);
private final Position posD1 = new Position(4, 1);
private final Position posE1 = new Position(5, 1);
private final Position posA5 = new Position(1, 5);
private final Position posB5 = new Position(2, 5);
private final Position posC5 = new Position(3, 5);
private final Position posD5 = new Position(4, 5);
private final Position posE5 = new Position(5, 5);
private final Range arbitraryRange = Range.range(1, 1, 3, 10);
// Potential expansion option for a larger variety of these categories of values to be provided to parameterised
// tests.
// @formatter:off
private Range[] rangePair_overlappingButNotContained =
new Range[] {Range.range(posA1, posC1), Range.range(posB1, posE1)};
private Range[] rangePair_unrelated = new Range[] {Range.range(posA1, posB1), Range.range(posD1, posE1)};
private Range[] rangePair_equalBeginEnd = new Range[] {Range.range(posA1, posB1), Range.range(posA1, posB1)};
private Range[] rangePair_strictlyContained = new Range[] {Range.range(posA1, posE1), Range.range(posB1, posD1)};
private Range[] rangePair_touchingLineAndColumn =
new Range[] {Range.range(posA1, posC1), Range.range(posC1, posE1)};
private Range[] rangePair_touchingLineNotColumn =
new Range[] {Range.range(posA1, posC1), Range.range(posC5, posD1)};
// @formatter:on
@Test
void constructorWithOrderedPositions() {
assertEquals(10, range_orderedPositions.begin.line);
assertEquals(11, range_orderedPositions.begin.column);
assertEquals(20, range_orderedPositions.end.line);
assertEquals(21, range_orderedPositions.end.column);
}
@Test
void constructorWithReversedPositions() {
assertEquals(10, range_reversedPositions.begin.line);
assertEquals(11, range_reversedPositions.begin.column);
assertEquals(20, range_reversedPositions.end.line);
assertEquals(21, range_reversedPositions.end.column);
}
@Test
void rangePair_equalBeginEnd_contains_true() {
assertTrue(rangePair_equalBeginEnd[0].contains(rangePair_equalBeginEnd[1]));
}
@Test
void rangePair_equalBeginEnd_strictlyContains_false() {
assertFalse(rangePair_equalBeginEnd[0].strictlyContains(rangePair_equalBeginEnd[1]));
}
@Test
void rangePair_overlappingButNotContained_contains_false() {
Range r1 = rangePair_overlappingButNotContained[0];
Range r2 = rangePair_overlappingButNotContained[1];
assertFalse(r1.contains(r2));
assertFalse(r2.contains(r1));
}
@Test
void rangePair_overlappingButNotContained_strictlyContains_false() {
Range r1 = rangePair_overlappingButNotContained[0];
Range r2 = rangePair_overlappingButNotContained[1];
assertFalse(r1.strictlyContains(r2));
assertFalse(r2.strictlyContains(r1));
}
@Test
void rangePair_unrelated_contains_false() {
Range r1 = rangePair_unrelated[0];
Range r2 = rangePair_unrelated[1];
assertFalse(r1.contains(r2));
assertFalse(r2.contains(r1));
}
@Test
void rangePair_unrelated_strictlyContains_false() {
Range r1 = rangePair_unrelated[0];
Range r2 = rangePair_unrelated[1];
assertFalse(r1.strictlyContains(r2));
assertFalse(r2.strictlyContains(r1));
}
@Test
void rangePair_strictlyContained_contains() {
Range r1 = rangePair_strictlyContained[0];
Range r2 = rangePair_strictlyContained[1];
assertTrue(r1.contains(r2));
assertFalse(r2.contains(r1));
}
@Test
void rangePair_strictlyContained_strictlyContains() {
Range r1 = rangePair_strictlyContained[0];
Range r2 = rangePair_strictlyContained[1];
assertTrue(r1.strictlyContains(r2));
assertFalse(r2.strictlyContains(r1));
}
@Test
void rangePair_touchingLineAndColumn_contains() {
Range r1 = rangePair_touchingLineAndColumn[0];
Range r2 = rangePair_touchingLineAndColumn[1];
assertFalse(r1.contains(r2));
assertFalse(r2.contains(r1));
}
@Test
void rangePair_touchingLineAndColumn_strictlyContains() {
Range r1 = rangePair_touchingLineAndColumn[0];
Range r2 = rangePair_touchingLineAndColumn[1];
assertFalse(r1.strictlyContains(r2));
assertFalse(r2.strictlyContains(r1));
}
@Test
void containsConsiderLines() {
Range r1 = Range.range(22, 9, 22, 29);
Range r2 = Range.range(26, 19, 26, 28);
assertFalse(r1.contains(r2));
assertFalse(r2.contains(r1));
}
@Test
void rangePair_touchingLineAndColumn_overlapsAccountsForColumn_true() {
Range r1 = rangePair_touchingLineAndColumn[0];
Range r2 = rangePair_touchingLineAndColumn[1];
assertTrue(r1.overlapsWith(r2));
assertTrue(r2.overlapsWith(r1));
}
@Test
void rangePair_touchingLineNotColumn_overlapsAccountsForColumn_false() {
Range r1 = rangePair_touchingLineNotColumn[0];
Range r2 = rangePair_touchingLineNotColumn[1];
assertFalse(r1.overlapsWith(r2));
assertFalse(r2.overlapsWith(r1));
}
@Test
void lineCountIsReturned() {
Range r1 = Range.range(1, 1, 5, 2);
assertEquals(5, r1.getLineCount());
Range r2 = Range.range(26, 5, 57, 6);
assertEquals(32, r2.getLineCount());
}
@Test
void arbitraryRange_containsItsBegin_true() {
Range r = arbitraryRange;
assertTrue(r.contains(r.begin));
}
@Test
void arbitraryRange_containsItsEnd_true() {
Range r = arbitraryRange;
assertTrue(r.contains(r.end));
}
@Test
void arbitraryRange_strictlyContainItsBegin_false() {
Range r = arbitraryRange;
assertFalse(r.strictlyContains(r.begin));
}
@Test
void arbitraryRange_strictlyContainItsEnd_false() {
Range r = arbitraryRange;
assertFalse(r.strictlyContains(r.end));
}
@Test
void touchingLineColumnRangesOverlap() {
Range r1 = Range.range(1, 1, 3, 10);
Range r2 = Range.range(3, 10, 5, 10);
assertTrue(r1.overlapsWith(r2));
assertTrue(r2.overlapsWith(r1));
}
@Test
void touchingLineNotColumnRangesDoNotOverlap() {
Range r1 = Range.range(1, 1, 3, 5);
Range r2 = Range.range(3, 10, 5, 10);
assertFalse(r1.overlapsWith(r2));
assertFalse(r2.overlapsWith(r1));
}
@Test
void rangePair_equalBeginEnd_overlap_true() {
Range r1 = rangePair_equalBeginEnd[0];
Range r2 = rangePair_equalBeginEnd[1];
assertTrue(r1.overlapsWith(r2));
assertTrue(r2.overlapsWith(r1));
}
@Test
void rangePair_unrelated_overlap_false() {
Range r1 = rangePair_unrelated[0];
Range r2 = rangePair_unrelated[1];
assertFalse(r1.overlapsWith(r2));
assertFalse(r2.overlapsWith(r1));
}
@Test
void rangePair_touchingLineAndColumn_overlap_false() {
Range r1 = rangePair_touchingLineAndColumn[0];
Range r2 = rangePair_touchingLineAndColumn[1];
assertTrue(r1.overlapsWith(r2));
assertTrue(r2.overlapsWith(r1));
}
@Test
void rangePair_overlappingButNotContained_overlap_true() {
Range r1 = rangePair_overlappingButNotContained[0];
Range r2 = rangePair_overlappingButNotContained[1];
assertTrue(r1.overlapsWith(r2));
assertTrue(r2.overlapsWith(r1));
}
@Test
void rangePair_strictlyContained_overlap_true() {
Range r1 = rangePair_strictlyContained[0];
Range r2 = rangePair_strictlyContained[1];
assertTrue(r1.overlapsWith(r2));
assertTrue(r2.overlapsWith(r1));
}
@Test
void rangePair_is_before() {
Range r1 = Range.range(new Position(1, 1), new Position(1, 2));
Range r2 = Range.range(new Position(1, 3), new Position(1, 4));
assertTrue(r1.isBefore(r2));
}
@Test
void rangePair_is_not_before() {
Range r1 = Range.range(new Position(1, 1), new Position(1, 2));
Range r2 = Range.range(new Position(1, 3), new Position(1, 4));
Range r3 = Range.range(new Position(1, 1), new Position(1, 4));
assertFalse(r2.isBefore(r1));
assertFalse(r3.isBefore(r1));
}
@Test
void rangePair_is_after() {
Range r1 = Range.range(new Position(1, 1), new Position(1, 2));
Range r2 = Range.range(new Position(1, 3), new Position(1, 4));
assertTrue(r2.isAfter(r1));
}
@Test
void rangePair_is_not_after() {
Range r1 = Range.range(new Position(1, 1), new Position(1, 2));
Range r2 = Range.range(new Position(1, 3), new Position(1, 4));
Range r3 = Range.range(new Position(1, 1), new Position(1, 4));
assertFalse(r1.isAfter(r2));
assertFalse(r1.isAfter(r3));
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.StaticJavaParser.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import java.util.Optional;
import org.junit.jupiter.api.Test;
class TokenRangeTest {
@Test
void toStringWorks() {
CompilationUnit cu = parse("class X {\n\tX(){\n// hello\n}\n}");
assertEquals(
"X(){\n// hello\n}",
cu.getClassByName("X")
.get()
.getDefaultConstructor()
.get()
.getTokenRange()
.get()
.toString());
}
@Test
void renumberRangesWorks() {
CompilationUnit cu = parse("class X {\n\tX(){\n// hello\n}\n}");
assertEquals(
"1,1-5/6,1-1/7,1-1/8,1-1/9,1-1/10,1-1/1,2-1/2,2-1/3,2-1/4,2-1/5,2-1/6,2-1/1,3-8/9,3-1/1,4-1/2,4-1/1,5-1/1,5-1/",
makeRangesString(cu));
TokenRange tokenRange = cu.getTokenRange().get();
tokenRange.getBegin().insertAfter(new JavaToken(1, "feif"));
tokenRange
.getBegin()
.getNextToken()
.get()
.getNextToken()
.get()
.insert(new JavaToken(JavaToken.Kind.WINDOWS_EOL.getKind(), "\r\n"));
cu.recalculatePositions();
assertEquals(
"1,1-5/6,1-4/10,1-2/1,2-1/2,2-1/3,2-1/4,2-1/5,2-1/1,3-1/2,3-1/3,3-1/4,3-1/5,3-1/6,3-1/1,4-8/9,4-1/1,5-1/2,5-1/1,6-1/2,6-1/",
makeRangesString(cu));
}
/**
* Make a compact String for comparing token range positions.
*/
private String makeRangesString(Node node) {
Optional<JavaToken> token = node.getTokenRange().map(TokenRange::getBegin);
StringBuilder result = new StringBuilder();
while (token.isPresent()) {
token = token.flatMap(t -> {
result.append(t.getRange()
.map(r -> r.begin.column + "," + r.begin.line + "-" + (r.end.column - r.begin.column + 1) + "/")
.orElse("?"));
return t.getNextToken();
});
}
return result.toString();
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.stmt.SwitchEntry;
import java.io.IOException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
public class TokenTypesTest {
@Test
void everyTokenHasACategory() throws IOException {
final int tokenCount = GeneratedJavaParserConstants.tokenImage.length;
Path tokenTypesPath = mavenModuleRoot(JavaParserTest.class)
.resolve("../javaparser-core/src/main/java/com/github/javaparser/TokenTypes.java");
CompilationUnit tokenTypesCu = parse(tokenTypesPath);
// -1 to take off the default: case.
int switchEntries = tokenTypesCu.findAll(SwitchEntry.class).size() - 1;
// The amount of "case XXX:" in TokenTypes.java should be equal to the amount of tokens JavaCC knows about:
assertEquals(tokenCount, switchEntries);
}
@Test
void throwOnUnrecognisedTokenType() {
assertThrows(AssertionError.class, () -> {
TokenTypes.getCategory(-1);
});
}
}

View File

@@ -0,0 +1,147 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
/**
* Test case for {@link UnicodeEscapeProcessingProvider}.
*/
public class UnicodeEscapeProcessingProviderTest {
@Test
void testUnicodeEscape() throws IOException {
assertEquals("13" + '\u12aA' + "98", new String(read("13\\u12aA98")));
}
@Test
void testEscapedUnicodeEscape() throws IOException {
assertEquals("13\\\\u12aA98", new String(read("13\\\\u12aA98")));
}
@Test
void testUnicodeEscapeWithMultipleUs() throws IOException {
assertEquals("13" + '\u12aA' + "98", new String(read("13\\uuuuuu12aA98")));
}
@Test
void testInputEndingInBackslash() throws IOException {
assertEquals("foobar\\", new String(read("foobar\\")));
}
@Test
void testInputEndingInBackslashU() throws IOException {
assertEquals("foobar\\u", new String(read("foobar\\u")));
}
@Test
void testInputEndingInBackslashUs() throws IOException {
assertEquals("foobar\\uuuuuu", new String(read("foobar\\uuuuuu")));
}
@Test
void testInputEndingInBackslashU1() throws IOException {
assertEquals("foobar\\uA", new String(read("foobar\\uA")));
}
@Test
void testInputEndingInBackslashU2() throws IOException {
assertEquals("foobar\\uAB", new String(read("foobar\\uAB")));
}
@Test
void testInputEndingInBackslashU3() throws IOException {
assertEquals("foobar\\uABC", new String(read("foobar\\uABC")));
}
@Test
void testInputEndingUnicodeEscape() throws IOException {
assertEquals("foobar\uABCD", new String(read("foobar\\uABCD")));
}
@Test
void testEmptyInput() throws IOException {
assertEquals("", new String(read("")));
}
@Test
void testBadUnicodeEscape0() throws IOException {
assertEquals("13\\ux", new String(read("13\\ux")));
}
@Test
void testBadUnicodeEscape1() throws IOException {
assertEquals("13\\u1x", new String(read("13\\u1x")));
}
@Test
void testBadUnicodeEscape2() throws IOException {
assertEquals("13\\u1Ax", new String(read("13\\u1Ax")));
}
@Test
void testBadUnicodeEscape3() throws IOException {
assertEquals("13\\u1ABx", new String(read("13\\u1ABx")));
}
@Test
void testBadUnicodeEscapeMultipleUs() throws IOException {
assertEquals("13\\uuuuuu1ABx", new String(read("13\\uuuuuu1ABx")));
}
@Test
void testPushBackWithFullBuffer() throws IOException {
assertEquals("12345678\\uuxxxxxxxxxxxxxxxxxxxxxxx", new String(read("12345678\\uuxxxxxxxxxxxxxxxxxxxxxxx")));
}
@Test
void testPushBackWithBufferShift() throws IOException {
assertEquals("12345678\\uuxx", new String(read("12345678\\uuxx")));
}
static String read(String source) throws IOException {
return process(provider(source));
}
static UnicodeEscapeProcessingProvider provider(String source) {
UnicodeEscapeProcessingProvider provider = new UnicodeEscapeProcessingProvider(10, new StringProvider(source));
return provider;
}
static String process(UnicodeEscapeProcessingProvider provider) throws IOException {
StringBuilder result = new StringBuilder();
char[] buffer = new char[10];
while (true) {
int direct = provider.read(buffer, 0, buffer.length);
if (direct < 0) {
break;
}
result.append(buffer, 0, direct);
}
provider.close();
return result.toString();
}
}

View File

@@ -0,0 +1,158 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.*;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import java.io.IOException;
import org.junit.jupiter.api.Test;
public class AncestorDescendantTests {
@Test
void nodeIsNotAncestorOfItself() throws IOException {
JavaParser parser = new JavaParser();
Provider provider = Providers.resourceProvider("com/github/javaparser/range/A.java");
assertNotNull(provider);
ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
assertTrue(parse.isSuccessful());
VariableDeclarationExpr node = parse.getResult()
.get()
.getType(0) // class A
.getMember(0)
.asMethodDeclaration() // method foo()
.getBody()
.get()
.getStatement(0)
.asExpressionStmt() // int a = 42;
.getExpression()
.asVariableDeclarationExpr(); // a = 42
assertFalse(node.isAncestorOf(node));
}
@Test
void nodeIsNotDescendantOfItself() throws IOException {
JavaParser parser = new JavaParser();
Provider provider = Providers.resourceProvider("com/github/javaparser/range/A.java");
assertNotNull(provider);
ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
assertTrue(parse.isSuccessful());
VariableDeclarationExpr node = parse.getResult()
.get()
.getType(0) // class A
.getMember(0)
.asMethodDeclaration() // method foo()
.getBody()
.get()
.getStatement(0)
.asExpressionStmt() // int a = 42;
.getExpression()
.asVariableDeclarationExpr(); // a = 42
assertFalse(node.isDescendantOf(node));
}
@Test
void nodeInSameFileIsDescendantOfAncestor() throws IOException {
JavaParser parser = new JavaParser();
Provider provider = Providers.resourceProvider("com/github/javaparser/range/A.java");
assertNotNull(provider);
ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider);
assertTrue(parse.isSuccessful());
VariableDeclarationExpr superNode = parse.getResult()
.get()
.getType(0) // class A
.getMember(0)
.asMethodDeclaration() // method foo()
.getBody()
.get()
.getStatement(0)
.asExpressionStmt() // int a = 42;
.getExpression()
.asVariableDeclarationExpr(); // a = 42
Expression subNode = superNode.getVariable(0).getInitializer().get(); // 42
assertTrue(superNode.isAncestorOf(subNode));
assertFalse(subNode.isAncestorOf(superNode));
assertTrue(subNode.isDescendantOf(superNode));
assertFalse(superNode.isDescendantOf(subNode));
}
@Test
void nodesInTwoDifferentFilesAreNotDescendantOrAncestorOfEachOther() throws IOException {
JavaParser parser = new JavaParser();
Provider providerA = Providers.resourceProvider("com/github/javaparser/range/A.java");
assertNotNull(providerA);
ParseResult<CompilationUnit> parseA = parser.parse(ParseStart.COMPILATION_UNIT, providerA);
assertTrue(parseA.isSuccessful());
Provider providerB = Providers.resourceProvider("com/github/javaparser/range/B.java");
assertNotNull(providerB);
ParseResult<CompilationUnit> parseB = parser.parse(ParseStart.COMPILATION_UNIT, providerB);
assertTrue(parseB.isSuccessful());
VariableDeclarationExpr superNodeA = parseA.getResult()
.get()
.getType(0) // class A
.getMember(0)
.asMethodDeclaration() // method foo()
.getBody()
.get()
.getStatement(0)
.asExpressionStmt() // int a = 42;
.getExpression()
.asVariableDeclarationExpr(); // a = 42
Expression subNodeA = superNodeA.getVariable(0).getInitializer().get(); // 42
VariableDeclarationExpr superNodeB = parseB.getResult()
.get()
.getType(0) // class B
.getMember(0)
.asMethodDeclaration() // method foo()
.getBody()
.get()
.getStatement(0)
.asExpressionStmt() // int b = 42;
.getExpression()
.asVariableDeclarationExpr(); // b = 42
Expression subNodeB = superNodeB.getVariable(0).getInitializer().get(); // 42
assertFalse(superNodeA.isAncestorOf(superNodeB));
assertFalse(superNodeA.isDescendantOf(subNodeB));
assertFalse(superNodeB.isAncestorOf(superNodeA));
assertFalse(superNodeB.isDescendantOf(subNodeA));
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
class CompilationUnitTest {
@Test
void issue578TheFirstCommentIsWithinTheCompilationUnit() {
CompilationUnit compilationUnit =
parse("// This is my class, with my comment\n" + "class A {\n" + " static int a;\n" + "}");
assertEquals(1, compilationUnit.getAllContainedComments().size());
}
@Test
void testGetSourceRoot() throws IOException {
Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class)
.resolve(Paths.get("src", "test", "resources"))
.normalize();
Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "Z.java"));
CompilationUnit cu = parse(testFile);
Path sourceRoot1 = cu.getStorage().get().getSourceRoot();
assertEquals(sourceRoot, sourceRoot1);
}
@Test
void testGetSourceRootWithBadPackageDeclaration() {
assertThrows(RuntimeException.class, () -> {
Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class)
.resolve(Paths.get("src", "test", "resources"))
.normalize();
Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "A.java"));
CompilationUnit cu = parse(testFile);
cu.getStorage().get().getSourceRoot();
});
}
@Test
void testGetSourceRootInDefaultPackage() throws IOException {
Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class)
.resolve(Paths.get("src", "test", "resources", "com", "github", "javaparser", "storage"))
.normalize();
Path testFile = sourceRoot.resolve(Paths.get("B.java"));
CompilationUnit cu = parse(testFile);
Path sourceRoot1 = cu.getStorage().get().getSourceRoot();
assertEquals(sourceRoot, sourceRoot1);
}
@Test
void testGetPrimaryTypeName() throws IOException {
Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class)
.resolve(Paths.get("src", "test", "resources"))
.normalize();
Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType.java"));
CompilationUnit cu = parse(testFile);
assertEquals("PrimaryType", cu.getPrimaryTypeName().get());
}
@Test
void testNoPrimaryTypeName() {
CompilationUnit cu = parse("class PrimaryType{}");
assertFalse(cu.getPrimaryTypeName().isPresent());
}
@Test
void testGetPrimaryType() throws IOException {
Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class)
.resolve(Paths.get("src", "test", "resources"))
.normalize();
Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType.java"));
CompilationUnit cu = parse(testFile);
assertEquals("PrimaryType", cu.getPrimaryType().get().getNameAsString());
}
@Test
void testNoPrimaryType() throws IOException {
Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class)
.resolve(Paths.get("src", "test", "resources"))
.normalize();
Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType2.java"));
CompilationUnit cu = parse(testFile);
assertFalse(cu.getPrimaryType().isPresent());
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.javaparser.ast.expr.SimpleName;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class DataKeyTest {
private static final DataKey<String> ABC = new DataKey<String>() {};
private static final DataKey<String> DEF = new DataKey<String>() {};
private static final DataKey<List<String>> LISTY = new DataKey<List<String>>() {};
private static final DataKey<List<String>> DING = new DataKey<List<String>>() {};
@Test
void addAFewKeysAndSeeIfTheyAreStoredCorrectly() {
Node node = new SimpleName();
node.setData(ABC, "Hurray!");
node.setData(LISTY, Arrays.asList("a", "b"));
node.setData(ABC, "w00t");
assertThat(node.getData(ABC)).contains("w00t");
assertThat(node.getData(LISTY)).containsExactly("a", "b");
assertThat(node.containsData(ABC)).isTrue();
assertThat(node.containsData(LISTY)).isTrue();
assertThat(node.containsData(DING)).isFalse();
}
@Test
void removeWorks() {
Node node = new SimpleName();
node.setData(ABC, "Hurray!");
node.removeData(ABC);
assertThat(node.containsData(ABC)).isFalse();
}
@Test
void aNonExistentKeyThrowsAnException() {
Node node = new SimpleName();
assertThrows(IllegalStateException.class, () -> node.getData(DING));
}
@Test
void cloningCopiesData() {
Node node = new SimpleName();
node.setData(ABC, "ABC!");
node.setData(DEF, "DEF!");
Node clone = node.clone();
assertEquals("ABC!", clone.getData(ABC));
assertEquals("DEF!", clone.getData(DEF));
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.StaticJavaParser.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.TryStmt;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
/**
* Some tests for finding descendant and ancestor nodes.
*/
class FindNodeTest {
@Test
void testFindFirst() {
CompilationUnit cu = parse("class Foo {\n" + " void foo() {\n"
+ " try {\n"
+ " } catch (Exception e) {\n"
+ " } finally {\n"
+ " try {\n"
+ " } catch (Exception e) {\n"
+ " foo();\n"
+ " } finally {\n"
+ " }\n"
+ " }\n"
+ "\n"
+ " }\n"
+ "}\n");
// find the method call expression foo()
MethodCallExpr actual = cu.findFirst(MethodCallExpr.class).orElse(null);
MethodCallExpr expected = cu.getType(0)
.getMember(0)
.asMethodDeclaration()
.getBody()
.get()
.getStatement(0)
.asTryStmt()
.getFinallyBlock()
.get()
.getStatement(0)
.asTryStmt()
.getCatchClauses()
.get(0)
.getBody()
.getStatement(0)
.asExpressionStmt()
.getExpression()
.asMethodCallExpr();
assertEquals(expected, actual);
}
@Test
void testFindAncestralFinallyBlock() {
CompilationUnit cu = parse("class Foo {\n" + " void foo() {\n"
+ " try {\n"
+ " } catch (Exception e) {\n"
+ " } finally {\n"
+ " try {\n"
+ " } catch (Exception e) {\n"
+ " foo();\n"
+ " } finally {\n"
+ " }\n"
+ " }\n"
+ "\n"
+ " }\n"
+ "}\n");
// find the method call expression foo()
MethodCallExpr methodCallExpr = cu.findFirst(MethodCallExpr.class).orElse(null);
// find the finally block that the method call expression foo() is in
Predicate<BlockStmt> predicate = (bs) -> {
if (bs.getParentNode().isPresent() && bs.getParentNode().get() instanceof TryStmt) {
TryStmt ancestralTryStmt = (TryStmt) bs.getParentNode().get();
return bs == ancestralTryStmt.getFinallyBlock().orElse(null);
}
return false;
};
BlockStmt actual =
methodCallExpr.findAncestor(predicate, BlockStmt.class).orElse(null);
BlockStmt expected = cu.getType(0)
.getMember(0)
.asMethodDeclaration()
.getBody()
.get()
.getStatement(0)
.asTryStmt()
.getFinallyBlock()
.get();
assertEquals(expected, actual);
}
}

View File

@@ -0,0 +1,274 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.StaticJavaParser.parse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.observer.AstObserver;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.PrimitiveType;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class ListObservationTest {
private FieldDeclaration createIntField(String name) {
return new FieldDeclaration(new NodeList<>(), PrimitiveType.intType(), name);
}
private AstObserver createObserver(List<String> changes) {
return new AstObserver() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format(
"change of property %s for %s: from '%s' to '%s'", property, observedNode, oldValue, newValue));
}
@Override
public void parentChange(Node observedNode, Node previousParent, Node newParent) {
changes.add(String.format(
"setting parent for %s: was %s, now is %s", observedNode, previousParent, newParent));
}
@Override
public void listChange(NodeList<?> observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) {
changes.add(String.format("'%s' %s in list at %d", nodeAddedOrRemoved, type, index));
}
@Override
public void listReplacement(NodeList<?> observedNode, int index, Node oldNode, Node newNode) {
changes.add(String.format("'%s' %s in list at %d", oldNode, ListChangeType.REMOVAL, index));
changes.add(String.format("'%s' %s in list at %d", newNode, ListChangeType.ADDITION, index));
}
};
}
@Test
void addAllWithoutIndex() {
List<String> changes = new LinkedList<>();
String code = "class A { void foo(int p) { }}";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().addAll(Arrays.asList(createIntField("a"), createIntField("b"), createIntField("c")));
assertEquals(
Arrays.asList(
"'int a;' ADDITION in list at 1",
"'int b;' ADDITION in list at 2",
"'int c;' ADDITION in list at 3"),
changes);
}
@Test
void addAllWithIndex() {
List<String> changes = new LinkedList<>();
String code = "class A { void foo(int p) { }}";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().addAll(0, Arrays.asList(createIntField("a"), createIntField("b"), createIntField("c")));
assertEquals(
Arrays.asList(
"'int a;' ADDITION in list at 0",
"'int b;' ADDITION in list at 1",
"'int c;' ADDITION in list at 2"),
changes);
}
@Test
void clear() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().clear();
assertEquals(
Arrays.asList(
"'int a;' REMOVAL in list at 0",
"'int b;' REMOVAL in list at 0",
"'int c;' REMOVAL in list at 0"),
changes);
}
@Test
void set() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().set(1, createIntField("d"));
assertEquals(Arrays.asList("'int b;' REMOVAL in list at 1", "'int d;' ADDITION in list at 1"), changes);
}
@Test
void removeNode() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; int d; int e; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().remove(cd.getFieldByName("c").get());
assertThat(changes).containsExactlyInAnyOrder("'int c;' REMOVAL in list at 2");
}
@Test
void removeFirstNode() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; int d; int e; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().removeFirst();
assertThat(changes).containsExactlyInAnyOrder("'int a;' REMOVAL in list at 0");
assertEquals(cd.getMembers().size(), 4);
for (int i = 3; i >= 0; i--) {
assertNotNull(cd.getMembers().removeFirst());
assertEquals(cd.getMembers().size(), i);
}
assertEquals(cd.getMembers().size(), 0);
}
@Test
void removeLastNode() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; int d; int e; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().removeLast();
assertThat(changes).containsExactlyInAnyOrder("'int e;' REMOVAL in list at 4");
assertEquals(cd.getMembers().size(), 4);
for (int i = 3; i >= 0; i--) {
assertNotNull(cd.getMembers().removeLast());
assertEquals(cd.getMembers().size(), i);
}
assertEquals(cd.getMembers().size(), 0);
}
@Test
void removeObject() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; int d; int e; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().remove("hi");
assertThat(changes).isEmpty();
}
@Test
void removeAll() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; int d; int e; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers()
.removeAll(Arrays.asList(
cd.getFieldByName("b").get(),
"foo",
cd.getFieldByName("d").get()));
assertThat(changes).containsExactlyInAnyOrder("'int b;' REMOVAL in list at 1", "'int d;' REMOVAL in list at 2");
}
@Test
void retainAll() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; int d; int e; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers()
.retainAll(Arrays.asList(
cd.getFieldByName("b").get(),
"foo",
cd.getFieldByName("d").get()));
assertThat(changes)
.containsExactlyInAnyOrder(
"'int a;' REMOVAL in list at 0",
"'int c;' REMOVAL in list at 1",
"'int e;' REMOVAL in list at 2");
}
@Test
void replaceAll() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int b; int c; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers().replaceAll(bodyDeclaration -> {
FieldDeclaration clone = (FieldDeclaration) bodyDeclaration.clone();
SimpleName id = clone.getVariable(0).getName();
id.setIdentifier(id.getIdentifier().toUpperCase());
return clone;
});
assertThat(changes)
.containsExactlyInAnyOrder(
"'int a;' REMOVAL in list at 0", "'int A;' ADDITION in list at 0",
"'int b;' REMOVAL in list at 1", "'int B;' ADDITION in list at 1",
"'int c;' REMOVAL in list at 2", "'int C;' ADDITION in list at 2");
}
@Test
void removeIf() {
List<String> changes = new LinkedList<>();
String code = "class A { int a; int longName; int c; }";
CompilationUnit cu = parse(code);
ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get();
cd.getMembers().register(createObserver(changes));
cd.getMembers()
.removeIf(m -> ((FieldDeclaration) m)
.getVariable(0)
.getName()
.getIdentifier()
.length()
> 3);
assertThat(changes).containsExactlyInAnyOrder("'int longName;' REMOVAL in list at 1");
}
}

View File

@@ -0,0 +1,440 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.ast.NodeList.nodeList;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.observer.AstObserver;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest;
import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter;
import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class NodeListTest extends AbstractLexicalPreservingTest {
@Test
void replace() {
final NodeList<Name> list = nodeList(new Name("a"), new Name("b"), new Name("c"));
final boolean replaced = list.replace(new Name("b"), new Name("z"));
assertTrue(replaced);
assertEquals(3, list.size());
assertEquals("a", list.get(0).asString());
assertEquals("z", list.get(1).asString());
assertEquals("c", list.get(2).asString());
}
@Test
void toStringTest() {
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
assertEquals(3, list.size());
assertEquals("[abc, bcd, cde]", list.toString());
}
@Test
void addFirst() {
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
list.addFirst(new Name("xxx"));
assertEquals(4, list.size());
assertEquals("[xxx, abc, bcd, cde]", list.toString());
}
@Test
void addLast() {
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
list.addLast(new Name("xxx"));
assertEquals(4, list.size());
assertEquals("[abc, bcd, cde, xxx]", list.toString());
}
@Test
void addBefore() {
Name n = new Name("bcd");
final NodeList<Name> list = nodeList(new Name("abc"), n, new Name("cde"));
list.addBefore(new Name("xxx"), n);
assertEquals(4, list.size());
assertEquals("[abc, xxx, bcd, cde]", list.toString());
}
@Test
void addAfter() {
Name n = new Name("bcd");
final NodeList<Name> list = nodeList(new Name("abc"), n, new Name("cde"));
list.addAfter(new Name("xxx"), n);
assertEquals(4, list.size());
assertEquals("[abc, bcd, xxx, cde]", list.toString());
}
@Test
void addBeforeFirst() {
Name abc = new Name("abc");
final NodeList<Name> list = nodeList(abc, new Name("bcd"), new Name("cde"));
list.addBefore(new Name("xxx"), abc);
assertEquals(4, list.size());
assertEquals("[xxx, abc, bcd, cde]", list.toString());
}
@Test
void addAfterLast() {
Name cde = new Name("cde");
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), cde);
list.addAfter(new Name("xxx"), cde);
assertEquals(4, list.size());
assertEquals("[abc, bcd, cde, xxx]", list.toString());
}
@Test
public void getFirstWhenEmpty() {
final NodeList<Name> list = nodeList();
Optional<Name> first = list.getFirst();
assertFalse(first.isPresent());
assertEquals("Optional.empty", first.toString());
}
@Test
public void getFirstWhenNonEmpty() {
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
Optional<Name> first = list.getFirst();
assertTrue(first.isPresent());
assertEquals("Optional[abc]", first.toString());
}
@Test
public void getLastWhenEmpty() {
final NodeList<Name> list = nodeList();
Optional<Name> last = list.getLast();
assertFalse(last.isPresent());
assertEquals("Optional.empty", last.toString());
}
@Test
public void getLastWhenNonEmpty() {
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
Optional<Name> last = list.getLast();
assertTrue(last.isPresent());
assertEquals("Optional[cde]", last.toString());
}
@Nested
class IteratorTest {
@Nested
class ObserversTest {
NodeList<Name> list;
ListIterator<Name> iterator;
List<String> propertyChanges;
List<String> parentChanges;
List<String> listChanges;
List<String> listReplacements;
AstObserver testObserver = new AstObserver() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
propertyChanges.add(String.format(
"%s.%s changed from %s to %s",
observedNode.getClass().getSimpleName(),
property.name().toLowerCase(),
oldValue,
newValue));
}
@Override
public void parentChange(Node observedNode, Node previousParent, Node newParent) {
parentChanges.add(String.format(
"%s 's parent changed from %s to %s",
observedNode.getClass().getSimpleName(), previousParent, newParent));
}
@Override
public void listChange(
NodeList<?> observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) {
listChanges.add(String.format(
"%s %s to/from %s at position %d",
nodeAddedOrRemoved.getClass().getSimpleName(),
type.name(),
observedNode.getClass().getSimpleName(),
index));
}
@Override
public void listReplacement(NodeList<?> observedNode, int index, Node oldNode, Node newNode) {
listReplacements.add(String.format(
"%s replaced within %s at position %d",
newNode.getClass().getSimpleName(),
observedNode.getClass().getSimpleName(),
index));
}
};
@BeforeEach
void pre() {
list = nodeList();
list.register(testObserver);
iterator = list.listIterator();
propertyChanges = new ArrayList<>();
parentChanges = new ArrayList<>();
listChanges = new ArrayList<>();
listReplacements = new ArrayList<>();
}
@Test
void whenAdd() {
assertEquals(0, propertyChanges.size());
assertEquals(0, parentChanges.size());
assertEquals(0, listChanges.size());
assertEquals(0, listReplacements.size());
iterator.add(new Name("abc"));
assertEquals(0, propertyChanges.size());
assertEquals(0, parentChanges.size());
assertEquals(1, listChanges.size());
assertEquals(0, listReplacements.size());
assertEquals("Name ADDITION to/from NodeList at position 0", listChanges.get(0));
}
@Test
void whenRemove() {
iterator.add(new Name("abc"));
assertEquals(0, propertyChanges.size());
assertEquals(0, parentChanges.size());
assertEquals(1, listChanges.size());
assertEquals(0, listReplacements.size());
iterator.previous();
iterator.remove();
assertEquals(0, propertyChanges.size());
assertEquals(0, parentChanges.size());
assertEquals(2, listChanges.size());
assertEquals(0, listReplacements.size());
assertEquals("Name ADDITION to/from NodeList at position 0", listChanges.get(0));
assertEquals("Name REMOVAL to/from NodeList at position 0", listChanges.get(1));
}
@Test
void whenSet() {
iterator.add(new Name("abc"));
assertEquals(0, propertyChanges.size());
assertEquals(0, parentChanges.size());
assertEquals(1, listChanges.size());
assertEquals(0, listReplacements.size());
iterator.previous();
iterator.set(new Name("xyz"));
assertEquals(0, propertyChanges.size());
assertEquals(0, parentChanges.size());
assertEquals(1, listChanges.size());
assertEquals(1, listReplacements.size());
assertEquals("Name ADDITION to/from NodeList at position 0", listChanges.get(0));
assertEquals("Name replaced within NodeList at position 0", listReplacements.get(0));
}
@Test
void usageTest() {
final String REFERENCE_TO_BE_DELETED = "bad";
considerCode("" + "@MyAnnotation(myElements = {\"good\", \"bad\", \"ugly\"})\n"
+ "public final class MyClass {\n"
+ "}");
String expected = "" + "@MyAnnotation(myElements = {\"good\", \"ugly\"})\n"
+ "public final class MyClass {\n"
+ "}";
List<NormalAnnotationExpr> annotations = cu.findAll(NormalAnnotationExpr.class);
annotations.forEach(annotation -> {
// testcase, per https://github.com/javaparser/javaparser/issues/2936#issuecomment-731370505
MemberValuePair mvp = annotation.getPairs().get(0);
Expression value = mvp.getValue();
if ((value instanceof ArrayInitializerExpr)) {
NodeList<Expression> myElements = ((ArrayInitializerExpr) value).getValues();
for (Iterator<Expression> iterator = myElements.iterator(); iterator.hasNext(); ) {
Node elt = iterator.next();
{
String nameAsString = ((StringLiteralExpr) elt).asString();
if (REFERENCE_TO_BE_DELETED.equals(nameAsString)) iterator.remove();
}
}
}
});
assertEquals(expected, LexicalPreservingPrinter.print(cu));
}
}
@Nested
class AddRemoveListIteratorTest {
NodeList<Name> list;
ListIterator<Name> iterator;
@BeforeEach
void pre() {
list = nodeList();
iterator = list.listIterator();
}
@Test
void whenAdd() {
assertFalse(iterator.hasNext());
assertFalse(iterator.hasPrevious());
// Note that the element is added before the current cursor, thus is accessible via "previous"
iterator.add(new Name("abc"));
assertFalse(iterator.hasNext());
assertTrue(iterator.hasPrevious());
}
}
@Nested
class EmptyIteratorTest {
NodeList<Name> list;
ListIterator<Name> iterator;
@BeforeEach
void pre() {
list = nodeList();
iterator = list.listIterator();
}
@Test
void whenNext() {
assertThrows(NoSuchElementException.class, () -> {
iterator.next();
});
}
@Test
void whenHasNext() {
assertFalse(iterator.hasNext());
}
@Test
void whenAdd() {
assertFalse(iterator.hasNext());
assertFalse(iterator.hasPrevious());
// Note that the element is added before the current cursor, thus is accessible via "previous"
iterator.add(new Name("abc"));
assertFalse(iterator.hasNext());
assertTrue(iterator.hasPrevious());
}
@Test
void whenSet() {
assertFalse(iterator.hasNext());
assertFalse(iterator.hasPrevious());
assertThrows(IllegalArgumentException.class, () -> {
// Note that the cursor is initially at -1, thus not possible to set the value here
iterator.set(new Name("abc"));
});
// Assert that next/previous are still empty
assertFalse(iterator.hasNext());
assertFalse(iterator.hasPrevious());
}
}
@Nested
class SingleItemIteratorTest {
NodeList<Name> list;
Iterator<Name> iterator;
@BeforeEach
void pre() {
list = nodeList(new Name("abc"));
iterator = list.iterator();
}
@Test
void whenNext() {
Name next = iterator.next();
assertNotNull(next);
}
@Test
void whenHasNext() {
assertTrue(iterator.hasNext());
}
@Test
void whenHasNextRepeated() {
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
}
@Test
void whenHasNextThenNext() {
assertTrue(iterator.hasNext());
iterator.next();
assertFalse(iterator.hasNext());
assertThrows(NoSuchElementException.class, () -> {
iterator.next();
});
}
@Test
void whenRemove() {
Name current = iterator.next();
iterator.remove();
assertFalse(iterator.hasNext());
assertThrows(NoSuchElementException.class, () -> {
iterator.next();
});
}
}
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParseStart;
import com.github.javaparser.Providers;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Test;
class NodePositionTest {
private List<Node> getAllNodes(Node node) {
List<Node> nodes = new LinkedList<>();
nodes.add(node);
node.getChildNodes().forEach(c -> nodes.addAll(getAllNodes(c)));
return nodes;
}
@Test
void packageProtectedClassShouldHavePositionSet() throws IOException {
ensureAllNodesHaveValidBeginPosition("class A { }");
}
@Test
void packageProtectedInterfaceShouldHavePositionSet() throws IOException {
ensureAllNodesHaveValidBeginPosition("interface A { }");
}
@Test
void packageProtectedEnumShouldHavePositionSet() throws IOException {
ensureAllNodesHaveValidBeginPosition("enum A { }");
}
@Test
void packageProtectedAnnotationShouldHavePositionSet() throws IOException {
ensureAllNodesHaveValidBeginPosition("@interface A { }");
}
@Test
void packageProtectedFieldShouldHavePositionSet() throws IOException {
ensureAllNodesHaveValidBeginPosition("public class A { int i; }");
}
@Test
void packageProtectedMethodShouldHavePositionSet() throws IOException {
ensureAllNodesHaveValidBeginPosition("public class A { void foo() {} }");
}
@Test
void packageProtectedConstructorShouldHavePositionSet() throws IOException {
ensureAllNodesHaveValidBeginPosition("public class A { A() {} }");
}
private void ensureAllNodesHaveValidBeginPosition(final String code) {
ParseResult<CompilationUnit> res =
new JavaParser().parse(ParseStart.COMPILATION_UNIT, Providers.provider(code));
assertTrue(res.getProblems().isEmpty());
CompilationUnit cu = res.getResult().get();
getAllNodes(cu).forEach(n -> {
assertNotNull(
n.getRange(),
String.format(
"There should be no node without a range: %s (class: %s)",
n, n.getClass().getCanonicalName()));
if (n.getBegin().get().line == 0 && !n.toString().isEmpty()) {
throw new IllegalArgumentException("There should be no node at line 0: " + n + " (class: "
+ n.getClass().getCanonicalName() + ")");
}
});
}
}

View File

@@ -0,0 +1,286 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.StaticJavaParser.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.Position;
import com.github.javaparser.Range;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.comments.BlockComment;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.comments.JavadocComment;
import com.github.javaparser.ast.comments.LineComment;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.ast.type.PrimitiveType;
import com.github.javaparser.utils.LineSeparator;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class NodeTest {
@Test
void removeOrphanCommentPositiveCase() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A");
Comment c = new LineComment("A comment");
decl.addOrphanComment(c);
assertEquals(1, decl.getOrphanComments().size());
assertSame(decl, c.getParentNode().get());
assertTrue(decl.removeOrphanComment(c));
assertEquals(0, decl.getOrphanComments().size());
assertFalse(c.getParentNode().isPresent());
}
@Test
void removeOrphanCommentNegativeCase() {
ClassOrInterfaceDeclaration aClass = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A");
FieldDeclaration aField =
new FieldDeclaration(new NodeList<>(), new VariableDeclarator(PrimitiveType.intType(), "f"));
aClass.getMembers().add(aField);
Comment c = new LineComment("A comment");
aField.addOrphanComment(c);
// the comment is an orphan comment of the field, so trying to remove it on the class should not work
assertFalse(aClass.removeOrphanComment(c));
assertEquals(1, aField.getOrphanComments().size());
assertTrue(c.getParentNode().isPresent());
}
@Test
void hasJavaDocCommentPositiveCaseWithSetJavaDocComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.setJavadocComment("A comment");
assertTrue(decl.hasJavaDocComment());
}
@Test
void hasJavaDocCommentPositiveCaseWithSetComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.setComment(new JavadocComment("A comment"));
assertTrue(decl.hasJavaDocComment());
}
@Test
void hasJavaDocCommentNegativeCaseNoComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
assertFalse(decl.hasJavaDocComment());
}
@Test
void hasJavaDocCommentNegativeCaseLineComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.setComment(new LineComment("foo"));
assertFalse(decl.hasJavaDocComment());
}
@Test
void hasJavaDocCommentNegativeCaseBlockComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.setComment(new BlockComment("foo"));
assertFalse(decl.hasJavaDocComment());
}
@Test
void findCompilationUnitOfCommentNode() {
CompilationUnit cu = parse(
"class X {\n" + " void x() {\n" + " // this is a comment\n" + " foo();\n" + " }\n" + "}\n");
Comment comment = cu.getType(0)
.getMember(0)
.asMethodDeclaration()
.getBody()
.get()
.getStatement(0)
.getComment()
.get();
assertTrue(comment.findCompilationUnit().isPresent());
}
@Test
void findCompilationUnitOfOrphanCommentNode() {
CompilationUnit cu = parse("class X {\n" + " void x() {\n" + " // this is a comment\n" + " }\n" + "}\n");
Comment comment = cu.getType(0)
.getMember(0)
.asMethodDeclaration()
.getBody()
.get()
.getOrphanComments()
.get(0);
assertTrue(comment.findCompilationUnit().isPresent());
}
@Test
void removeAllOnRequiredProperty() {
CompilationUnit cu = parse("class X{ void x(){}}");
MethodDeclaration methodDeclaration = cu.getType(0).getMethods().get(0);
methodDeclaration.getName().removeForced();
// Name is required, so to remove it the whole method is removed.
assertEquals(String.format("class X {%1$s}%1$s", LineSeparator.SYSTEM), cu.toString());
}
@Test
void removingTheSecondOfAListOfIdenticalStatementsDoesNotMessUpTheParents() {
CompilationUnit unit = parse(String.format(
"public class Example {%1$s" + " public static void example() {%1$s"
+ " boolean swapped;%1$s"
+ " swapped=false;%1$s"
+ " swapped=false;%1$s"
+ " }%1$s"
+ "}%1$s",
LineSeparator.SYSTEM));
// remove the second swapped=false
ExpressionStmt target = unit.findAll(ExpressionStmt.class).get(2);
target.remove();
// This will throw an exception if the parents are bad.
unit.toString();
}
@Test
void findNodeByRange() {
CompilationUnit cu = parse("class X {\n" + " void x() {\n" + " }\n" + "}\n");
ClassOrInterfaceDeclaration coid =
cu.findFirst(ClassOrInterfaceDeclaration.class).get();
MethodDeclaration md = cu.findFirst(MethodDeclaration.class).get();
// The range corresponds to the compilation unit
Optional<Node> node = cu.findByRange(new Range(new Position(1, 1), new Position(4, 2)));
assertTrue(node.isPresent());
assertEquals(cu, node.get());
// The range corresponds to the class declaration
node = cu.findByRange(new Range(new Position(1, 1), new Position(4, 1)));
assertTrue(node.isPresent());
assertEquals(coid, node.get());
// The range corresponds to the method declaration
node = cu.findByRange(new Range(new Position(2, 3), new Position(3, 3)));
assertTrue(node.isPresent());
assertEquals(md, node.get());
// The range is included in the class declaration
node = cu.findByRange(new Range(new Position(1, 1), new Position(1, 1)));
assertTrue(node.isPresent());
assertEquals(coid, node.get());
// The range is not included in the compilation unit
node = cu.findByRange(new Range(new Position(5, 1), new Position(5, 1)));
assertFalse(node.isPresent());
// Search based on the method declaration, but the range corresponds to a parent node.
node = md.findByRange(new Range(new Position(1, 1), new Position(1, 1)));
assertFalse(node.isPresent());
}
@Nested
class PreOrderIteratorTest {
@Test
void rootHasNoChild() {
Node root = new CompilationUnit();
List<Node> nodes = root.findAll(Node.class, Node.TreeTraversal.PREORDER);
assertEquals(Arrays.asList(CompilationUnit.class), classesOf(nodes));
}
@Test
void rootHasChild() {
Node root = new CompilationUnit("com");
List<Node> nodes = root.findAll(Node.class, Node.TreeTraversal.PREORDER);
assertEquals(Arrays.asList(CompilationUnit.class, PackageDeclaration.class, Name.class), classesOf(nodes));
}
@Test
void astHasMultipleLeafs() {
Node root = parse("package com;" + "import com.*;" + "import org.*;" + "abstract class Foo {}");
List<Node> nodes = root.findAll(Node.class, Node.TreeTraversal.PREORDER);
assertEquals(
Arrays.asList(
CompilationUnit.class,
PackageDeclaration.class,
Name.class,
ImportDeclaration.class,
Name.class,
ImportDeclaration.class,
Name.class,
ClassOrInterfaceDeclaration.class,
Modifier.class,
SimpleName.class),
classesOf(nodes));
}
private List<Class<? extends Node>> classesOf(List<Node> nodes) {
return nodes.stream().map(Node::getClass).collect(Collectors.toList());
}
}
@Nested
class PostOrderIteratorTest {
@Test
void rootHasNoChild() {
Node root = new CompilationUnit();
List<Node> nodes = root.findAll(Node.class, Node.TreeTraversal.POSTORDER);
assertEquals(Arrays.asList(CompilationUnit.class), classesOf(nodes));
}
@Test
void rootHasChild() {
Node root = new CompilationUnit("com");
List<Node> nodes = root.findAll(Node.class, Node.TreeTraversal.POSTORDER);
assertEquals(Arrays.asList(Name.class, PackageDeclaration.class, CompilationUnit.class), classesOf(nodes));
}
@Test
void astHasMultipleLeafs() {
Node root = parse("package com;" + "import com.*;" + "import org.*;" + "abstract class Foo {}");
List<Node> nodes = root.findAll(Node.class, Node.TreeTraversal.POSTORDER);
assertEquals(
Arrays.asList(
Name.class,
PackageDeclaration.class,
Name.class,
ImportDeclaration.class,
Name.class,
ImportDeclaration.class,
Modifier.class,
SimpleName.class,
ClassOrInterfaceDeclaration.class,
CompilationUnit.class),
classesOf(nodes));
}
private List<Class<? extends Node>> classesOf(List<Node> nodes) {
return nodes.stream().map(Node::getClass).collect(Collectors.toList());
}
}
}

View File

@@ -0,0 +1,329 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.StaticJavaParser.parse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.observer.AstObserver;
import com.github.javaparser.ast.observer.AstObserverAdapter;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.PrimitiveType;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class ObservationTest {
@Test
void registerSubTree() {
String code = "class A { int f; void foo(int p) { return 'z'; }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format(
"%s.%s changed from %s to %s",
observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue));
}
};
cu.registerForSubtree(observer);
assertThat(changes).isEmpty();
cu.getClassByName("A").get().setName("MyCoolClass");
assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass");
cu.getClassByName("MyCoolClass")
.get()
.getFieldByName("f")
.get()
.getVariable(0)
.setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean");
cu.getClassByName("MyCoolClass")
.get()
.getMethodsByName("foo")
.get(0)
.getParameterByName("p")
.get()
.setName("myParam");
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean",
"Parameter.name changed from p to myParam");
}
@Test
void registerWithJustNodeMode() {
String code = "class A { int f; void foo(int p) { return 'z'; }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format(
"%s.%s changed from %s to %s",
observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue));
}
};
cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.JUST_THIS_NODE);
assertThat(changes).isEmpty();
cu.getClassByName("A").get().setName("MyCoolClass");
assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass");
cu.getClassByName("MyCoolClass")
.get()
.getFieldByName("f")
.get()
.getVariable(0)
.setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass");
cu.getClassByName("MyCoolClass")
.get()
.getMethodsByName("foo")
.get(0)
.getParameterByName("p")
.get()
.setName("myParam");
assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass");
cu.getClassByName("MyCoolClass")
.get()
.addField("int", "bar")
.getVariables()
.get(0)
.setInitializer("0");
assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass");
}
@Test
void registerWithNodeAndExistingDescendantsMode() {
String code = "class A { int f; void foo(int p) { return 'z'; }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format(
"%s.%s changed from %s to %s",
observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue));
}
};
cu.getClassByName("A")
.get()
.register(observer, Node.ObserverRegistrationMode.THIS_NODE_AND_EXISTING_DESCENDANTS);
assertThat(changes).isEmpty();
cu.getClassByName("A").get().setName("MyCoolClass");
assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass");
cu.getClassByName("MyCoolClass")
.get()
.getFieldByName("f")
.get()
.getVariable(0)
.setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean");
cu.getClassByName("MyCoolClass")
.get()
.getMethodsByName("foo")
.get(0)
.getParameterByName("p")
.get()
.setName("myParam");
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean",
"Parameter.name changed from p to myParam");
cu.getClassByName("MyCoolClass")
.get()
.addField("int", "bar")
.getVariables()
.get(0)
.setInitializer("0");
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean",
"Parameter.name changed from p to myParam");
}
@Test
void registerWithSelfPropagatingMode() {
String code = "class A { int f; void foo(int p) { return 'z'; }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format(
"%s.%s changed from %s to %s",
observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue));
}
};
cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING);
assertThat(changes).isEmpty();
cu.getClassByName("A").get().setName("MyCoolClass");
assertThat(changes).containsExactlyInAnyOrder("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass");
cu.getClassByName("MyCoolClass")
.get()
.getFieldByName("f")
.get()
.getVariable(0)
.setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN));
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean");
cu.getClassByName("MyCoolClass")
.get()
.getMethodsByName("foo")
.get(0)
.getParameterByName("p")
.get()
.setName("myParam");
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean",
"Parameter.name changed from p to myParam");
cu.getClassByName("MyCoolClass")
.get()
.addField("int", "bar")
.getVariables()
.get(0)
.setInitializer("0");
assertThat(changes)
.containsExactlyInAnyOrder(
"ClassOrInterfaceDeclaration.name changed from A to MyCoolClass",
"FieldDeclaration.maximum_common_type changed from int to boolean",
"VariableDeclarator.type changed from int to boolean",
"Parameter.name changed from p to myParam",
"VariableDeclarator.initializer changed from null to 0");
}
@Test
void deleteAParameterTriggerNotifications() {
String code = "class A { void foo(int p) { }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void listChange(NodeList<?> observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) {
changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index);
}
};
cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING);
cu.getClassByName("A")
.get()
.getMethodsByName("foo")
.get(0)
.getParameter(0)
.remove();
assertThat(changes).containsExactlyInAnyOrder("removing [int p] from index 0");
}
@Test
void deleteClassNameDoesNotTriggerNotifications() {
String code = "class A { void foo(int p) { }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void listChange(NodeList<?> observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) {
changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index);
}
};
cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING);
// I cannot remove the name of a type
assertFalse(cu.getClassByName("A").get().getName().remove());
assertThat(changes).isEmpty();
}
@Test
void deleteMethodBodyDoesTriggerNotifications() {
String code = "class A { void foo(int p) { }}";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new AstObserverAdapter() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add("setting [" + property + "] to " + newValue);
}
@Override
public void listChange(NodeList<?> observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) {
changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index);
}
};
cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING);
assertTrue(cu.getClassByName("A")
.get()
.getMethodsByName("foo")
.get(0)
.getBody()
.get()
.remove());
assertThat(changes).containsExactlyInAnyOrder("setting [BODY] to null");
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.ast.Node.Parsedness.PARSED;
import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.Problem;
import com.github.javaparser.utils.LineSeparator;
import org.junit.jupiter.api.Test;
class ParseResultTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration());
@Test
void whenParsingSucceedsThenWeGetResultsAndNoProblems() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{}"));
assertThat(result.getResult().isPresent()).isTrue();
assertThat(result.getResult().get().getParsed()).isEqualTo(PARSED);
assertThat(result.getProblems()).isEmpty();
assertThat(result.toString()).isEqualTo("Parsing successful");
}
@Test
void whenParsingFailsThenWeGetProblemsAndABadResult() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class {"));
assertThat(result.getResult().isPresent()).isTrue();
assertThat(result.getResult().get().getParsed()).isEqualTo(UNPARSABLE);
assertThat(result.getProblems().size()).isEqualTo(1);
Problem problem = result.getProblem(0);
assertThat(problem.getMessage())
.isEqualTo(
"Parse error. Found \"{\", expected one of \"enum\" \"exports\" \"module\" \"open\" \"opens\" \"permits\" \"provides\" \"record\" \"requires\" \"sealed\" \"strictfp\" \"to\" \"transitive\" \"uses\" \"when\" \"with\" \"yield\" <IDENTIFIER>");
assertThat(result.toString())
.startsWith("Parsing failed:" + LineSeparator.SYSTEM + "(line 1,col 1) Parse error.");
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.StaticJavaParser.parsePackageDeclaration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.utils.LineSeparator;
import org.junit.jupiter.api.Test;
class ReplaceNodeTest {
@Test
void testSimplePropertyWithGenericReplace() {
CompilationUnit cu = parse("package x; class Y {}");
cu.replace(cu.getPackageDeclaration().get(), parsePackageDeclaration("package z;"));
assertEquals(
String.format("package z;%1$s" + "%1$s" + "class Y {%1$s" + "}%1$s", LineSeparator.SYSTEM),
cu.toString());
}
@Test
void testListProperty() {
CompilationUnit cu = parse("package x; class Y {}");
cu.replace(
cu.getClassByName("Y").get(),
parse("class B{int y;}").getClassByName("B").get());
assertEquals(
String.format(
"package x;%1$s" + "%1$s" + "class B {%1$s" + "%1$s" + " int y;%1$s" + "}%1$s",
LineSeparator.SYSTEM),
cu.toString());
}
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.expr.SimpleName;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class WalkFindTest {
@Test
void findCompilationUnit() {
CompilationUnit cu = parse("class X{int x;}");
VariableDeclarator x = cu.getClassByName("X")
.get()
.getMember(0)
.asFieldDeclaration()
.getVariables()
.get(0);
assertEquals(cu, x.findCompilationUnit().get());
}
@Test
void findParent() {
CompilationUnit cu = parse("class X{int x;}");
SimpleName x = cu.getClassByName("X")
.get()
.getMember(0)
.asFieldDeclaration()
.getVariables()
.get(0)
.getName();
assertEquals("int x;", x.findAncestor(FieldDeclaration.class).get().toString());
}
@Test
void findParentFromTypes() {
CompilationUnit cu = parse("class X{Integer x;}");
VariableDeclarator vd = cu.getClassByName("X")
.get()
.getMember(0)
.asFieldDeclaration()
.getVariables()
.get(0);
assertEquals(
FieldDeclaration.class.getName(),
vd.findAncestor(new Class[] {
CompilationUnit.class, ClassOrInterfaceDeclaration.class, FieldDeclaration.class
})
.get()
.getClass()
.getName());
assertEquals(
ClassOrInterfaceDeclaration.class.getName(),
vd.findAncestor(new Class[] {CompilationUnit.class, ClassOrInterfaceDeclaration.class})
.get()
.getClass()
.getName());
}
@Test
void cantFindCompilationUnit() {
VariableDeclarator x = new VariableDeclarator();
assertFalse(x.findCompilationUnit().isPresent());
}
@Test
void genericWalk() {
Expression e = parseExpression("1+1");
StringBuilder b = new StringBuilder();
e.walk(n -> b.append(n.toString()));
assertEquals("1 + 111", b.toString());
}
@Test
void classSpecificWalk() {
Expression e = parseExpression("1+1");
StringBuilder b = new StringBuilder();
e.walk(IntegerLiteralExpr.class, n -> b.append(n.toString()));
assertEquals("11", b.toString());
}
@Test
void conditionalFindAll() {
Expression e = parseExpression("1+2+3");
List<IntegerLiteralExpr> ints = e.findAll(IntegerLiteralExpr.class, n -> n.asInt() > 1);
assertEquals("[2, 3]", ints.toString());
}
@Test
void typeOnlyFindAll() {
Expression e = parseExpression("1+2+3");
List<IntegerLiteralExpr> ints = e.findAll(IntegerLiteralExpr.class);
assertEquals("[1, 2, 3]", ints.toString());
}
@Test
void typeOnlyFindAllMatchesSubclasses() {
Expression e = parseExpression("1+2+3");
List<Node> ints = e.findAll(Node.class);
assertEquals("[1 + 2 + 3, 1 + 2, 1, 2, 3]", ints.toString());
}
@Test
void conditionalTypedFindFirst() {
Expression e = parseExpression("1+2+3");
Optional<IntegerLiteralExpr> ints = e.findFirst(IntegerLiteralExpr.class, n -> n.asInt() > 1);
assertEquals("Optional[2]", ints.toString());
}
@Test
void typeOnlyFindFirst() {
Expression e = parseExpression("1+2+3");
Optional<IntegerLiteralExpr> ints = e.findFirst(IntegerLiteralExpr.class);
assertEquals("Optional[1]", ints.toString());
}
@Test
void stream() {
Expression e = parseExpression("1+2+3");
List<IntegerLiteralExpr> ints = e.stream()
.filter(n -> n instanceof IntegerLiteralExpr)
.map(IntegerLiteralExpr.class::cast)
.filter(i -> i.asInt() > 1)
.collect(Collectors.toList());
assertEquals("[2, 3]", ints.toString());
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.TestParser.parseStatement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class AnnotationDeclarationTest {
@Test
void cantAddField() {
assertThrows(IllegalStateException.class, () -> new AnnotationDeclaration().addField(Object.class, "oo"));
}
@Test
void issue2216() {
Statement statement = parseStatement("TT tt = new <String> @TypeAnno @TA2 TT( \"S\" );");
assertEquals("TT tt = new <String> @TypeAnno @TA2 TT(\"S\");", statement.toString());
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.utils.TestParser;
import org.junit.jupiter.api.Test;
class AnnotationMemberDeclarationTest {
@Test
void whenSettingNameTheParentOfNameIsAssigned() {
AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration();
SimpleName name = new SimpleName("foo");
decl.setName(name);
assertTrue(name.getParentNode().isPresent());
assertSame(decl, name.getParentNode().get());
}
@Test
void removeDefaultValueWhenNoDefaultValueIsPresent() {
AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration();
SimpleName name = new SimpleName("foo");
decl.setName(name);
decl.removeDefaultValue();
assertFalse(decl.getDefaultValue().isPresent());
}
@Test
void removeDefaultValueWhenDefaultValueIsPresent() {
AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration();
SimpleName name = new SimpleName("foo");
decl.setName(name);
Expression defaultValue = new IntegerLiteralExpr("2");
decl.setDefaultValue(defaultValue);
decl.removeDefaultValue();
assertFalse(defaultValue.getParentNode().isPresent());
}
@Test
void annotationDeclarationShouldSupportRecordChild() {
CompilationUnit cu = TestParser.parseCompilationUnit(
ParserConfiguration.LanguageLevel.BLEEDING_EDGE,
"" + "@interface Foo {\n" + " record Bar(String s) {}\n" + "}");
RecordDeclaration bar =
cu.getAnnotationDeclarationByName("Foo").get().getMember(0).asRecordDeclaration();
assertEquals(1, bar.getParameters().size());
Parameter parameter = bar.getParameter(0);
assertEquals("String", parameter.getTypeAsString());
assertEquals("s", parameter.getNameAsString());
}
}

View File

@@ -0,0 +1,184 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.utils.TestParser;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.opentest4j.AssertionFailedError;
class ClassOrInterfaceDeclarationTest {
@Test
void staticNestedClass() {
CompilationUnit cu = parse("class X{static class Y{}}");
ClassOrInterfaceDeclaration y =
cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration();
assertFalse(y.isInnerClass());
assertTrue(y.isNestedType());
assertFalse(y.isLocalClassDeclaration());
}
@Test
void nestedInterface() {
CompilationUnit cu = parse("class X{interface Y{}}");
ClassOrInterfaceDeclaration y =
cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration();
assertFalse(y.isInnerClass());
assertTrue(y.isNestedType());
assertFalse(y.isLocalClassDeclaration());
}
@Test
void nonStaticNestedClass() {
CompilationUnit cu = parse("class X{class Y{}}");
ClassOrInterfaceDeclaration y =
cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration();
assertTrue(y.isInnerClass());
assertTrue(y.isNestedType());
assertFalse(y.isLocalClassDeclaration());
}
@Test
void topClass() {
CompilationUnit cu = parse("class X{}");
ClassOrInterfaceDeclaration y = cu.getClassByName("X").get();
assertFalse(y.isInnerClass());
assertFalse(y.isNestedType());
assertFalse(y.isLocalClassDeclaration());
}
@Test
void localClass() {
MethodDeclaration method = parseBodyDeclaration("void x(){class X{};}").asMethodDeclaration();
ClassOrInterfaceDeclaration x =
method.findFirst(ClassOrInterfaceDeclaration.class).get();
assertFalse(x.isInnerClass());
assertFalse(x.isNestedType());
assertTrue(x.isLocalClassDeclaration());
}
@Test
void sealedClass() {
CompilationUnit cu = TestParser.parseCompilationUnit(
ParserConfiguration.LanguageLevel.JAVA_17, "sealed class X permits Y, Z {}");
ClassOrInterfaceDeclaration x = cu.getClassByName("X").get();
assertFalse(x.isInnerClass());
assertFalse(x.isNestedType());
assertFalse(x.isLocalClassDeclaration());
assertTrue(x.hasModifier(Modifier.Keyword.SEALED));
assertEquals(x.getPermittedTypes().size(), 2);
assertEquals(x.getPermittedTypes().get(0).getNameAsString(), "Y");
assertEquals(x.getPermittedTypes().get(1).getNameAsString(), "Z");
}
@Test
void nonSealedClass() {
CompilationUnit cu =
TestParser.parseCompilationUnit(ParserConfiguration.LanguageLevel.JAVA_17, "non-sealed class X{}");
ClassOrInterfaceDeclaration x = cu.getClassByName("X").get();
assertFalse(x.isInnerClass());
assertFalse(x.isNestedType());
assertFalse(x.isLocalClassDeclaration());
assertTrue(x.hasModifier(Modifier.Keyword.NON_SEALED));
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {
"JAVA_8", "JAVA_9", "JAVA_10", "JAVA_11", "JAVA_12", "JAVA_13", "JAVA_14", "JAVA_15", "JAVA_16",
"JAVA_17"
})
void sealedFieldNamePermitted(ParserConfiguration.LanguageLevel languageLevel) {
assertDoesNotThrow(() -> {
TestParser.parseVariableDeclarationExpr(languageLevel, "boolean sealed");
});
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_8", "JAVA_9", "JAVA_10", "JAVA_11", "JAVA_12", "JAVA_13", "JAVA_14", "JAVA_15", "JAVA_16"})
void sealedClassOrInterfaceNamePermitted(ParserConfiguration.LanguageLevel languageLevel) {
assertDoesNotThrow(() -> {
TestParser.parseCompilationUnit(languageLevel, "class sealed {}");
});
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_17"})
void sealedClassOrInterfaceNameNotPermitted(ParserConfiguration.LanguageLevel languageLevel) {
assertThrows(AssertionFailedError.class, () -> {
TestParser.parseCompilationUnit(languageLevel, "class sealed {}");
});
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {
"JAVA_8", "JAVA_9", "JAVA_10", "JAVA_11", "JAVA_12", "JAVA_13", "JAVA_14", "JAVA_15", "JAVA_16",
"JAVA_17"
})
void permitsFieldNamePermitted(ParserConfiguration.LanguageLevel languageLevel) {
assertDoesNotThrow(() -> {
TestParser.parseVariableDeclarationExpr(languageLevel, "boolean permits");
});
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_8", "JAVA_9", "JAVA_10", "JAVA_11", "JAVA_12", "JAVA_13", "JAVA_14", "JAVA_15", "JAVA_16"})
void permitsClassOrInterfaceNamePermitted(ParserConfiguration.LanguageLevel languageLevel) {
assertDoesNotThrow(() -> {
TestParser.parseCompilationUnit(languageLevel, "class permits {}");
});
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_17"})
void permitsClassOrInterfaceNameNotPermitted(ParserConfiguration.LanguageLevel languageLevel) {
assertThrows(AssertionFailedError.class, () -> {
TestParser.parseCompilationUnit(languageLevel, "class permits {}");
});
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.utils.LineSeparator;
import org.junit.jupiter.api.Test;
class ConstructorDeclarationTest {
@Test
void acceptsSuper() {
ConstructorDeclaration cons = new ConstructorDeclaration("Cons");
cons.createBody().addStatement("super();");
assertEquals(
String.format("public Cons() {%1$s" + " super();%1$s" + "}", LineSeparator.SYSTEM), cons.toString());
}
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Modifier.Keyword;
import com.github.javaparser.ast.NodeList;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class FieldDeclarationTest {
@Test
void wofjweoifj() {
CompilationUnit compilationUnit = parse("" + "class A {\n" + " int a, b;\n" + "}");
BodyDeclaration<?> declaration = compilationUnit.getType(0).getMembers().get(0);
FieldDeclaration fieldDeclaration = declaration.asFieldDeclaration();
VariableDeclarator var1 = fieldDeclaration.getVariables().get(0);
VariableDeclarator var2 = fieldDeclaration.getVariables().get(1);
assertEquals(var1, var1.getType().getParentNode().get());
assertEquals(var2, var2.getType().getParentNode().get());
}
@Test
void setModifiersPrimitiveType() {
FieldDeclaration field =
parseBodyDeclaration("public static final int var = 1;").asFieldDeclaration();
testChangingModifiers(field);
}
@Test
void setModifiersNonPrimitiveType() {
FieldDeclaration field =
parseBodyDeclaration("public static final String var = \"a\";").asFieldDeclaration();
testChangingModifiers(field);
}
private void testChangingModifiers(FieldDeclaration field) {
NodeList<Modifier> modifiers = field.getModifiers();
assertTrue(modifiers.contains(Modifier.publicModifier()));
assertTrue(modifiers.contains(Modifier.staticModifier()));
assertTrue(modifiers.contains(Modifier.finalModifier()));
assertEquals(3, modifiers.size());
field.setModifiers(new NodeList<Modifier>());
modifiers = field.getModifiers();
assertEquals(0, modifiers.size());
field.setModifiers(Keyword.PRIVATE, Keyword.SYNCHRONIZED);
modifiers = field.getModifiers();
assertTrue(modifiers.contains(Modifier.privateModifier()));
assertTrue(modifiers.contains(Modifier.synchronizedModifier()));
assertEquals(2, modifiers.size());
}
@Test
void interfaceFieldTest() {
CompilationUnit compilationUnit = parse("" + "interface A {\n"
+ " int a = 1;\n"
+ " static int a_s = 1;\n"
+ " final int a_f = 1;\n"
+ " static final int a_s_f = 1;\n"
+ " String b = \"b\";\n"
+ " static String b_s = \"b\";\n"
+ " final String b_f = \"b\";\n"
+ " static final String b_s_f = \"b\";\n"
+ "}\n");
for (int i = 0; i < 8; ++i) {
BodyDeclaration<?> declaration =
compilationUnit.getType(0).getMembers().get(i);
FieldDeclaration fieldDeclaration = declaration.asFieldDeclaration();
Assertions.assertTrue(fieldDeclaration.isStatic());
Assertions.assertTrue(fieldDeclaration.isFinal());
}
}
/**
* Regression test for issue #4056.
*/
@Test
void testEnumWithPrivateFieldInsideInterface() {
String source = "interface Outer {\n" + " enum Numbers {\n"
+ " ONE(1),\n"
+ " TWO(2),\n"
+ " THREE(3);\n"
+ "\n"
+ " Numbers(int i) {\n"
+ " this.i = i;\n"
+ " }\n"
+ "\n"
+ " private int i;\n"
+ " }\n"
+ "}";
CompilationUnit cu = StaticJavaParser.parse(source);
FieldDeclaration i = cu.getTypes()
.get(0)
.asClassOrInterfaceDeclaration()
.getMembers()
.get(0)
.asEnumDeclaration()
.getFields()
.get(0);
assertAll(() -> assertFalse(i.isPublic()), () -> assertFalse(i.isStatic()), () -> assertFalse(i.isFinal()));
}
}

View File

@@ -0,0 +1,169 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.StaticJavaParser.parseBodyDeclaration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.CompilationUnit;
import org.junit.jupiter.api.Test;
class MethodDeclarationTest {
@Test
void annotationsAllowedAfterGenericsAndBeforeReturnType() {
parseBodyDeclaration("public <T> @Abc String method() {return null;}");
}
@Test
void annotationsAllowedBeforeGenerics() {
parseBodyDeclaration("public @Abc <T> String method() {return null;}");
}
@Test
void explicitReceiverParameters1() {
MethodDeclaration method = parseBodyDeclaration(
"void InnerInner(@mypackage.Anno Source.@mypackage.Anno Inner Source.Inner.this) { }")
.asMethodDeclaration();
assertEquals("Source.Inner.this", method.getReceiverParameter().get().getNameAsString());
}
@Test
void explicitReceiverParameters2() {
MethodDeclaration method = parseBodyDeclaration("void x(A this) { }").asMethodDeclaration();
assertEquals("this", method.getReceiverParameter().get().getNameAsString());
}
@Test
void explicitReceiverParameters3() {
MethodDeclaration method = parseBodyDeclaration("void x(A that) { }").asMethodDeclaration();
assertFalse(method.getReceiverParameter().isPresent());
}
@Test
void signaturesEqual() {
MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration();
MethodDeclaration method2 = parseBodyDeclaration("int x(String z);").asMethodDeclaration();
assertEquals(method1.getSignature(), method2.getSignature());
}
@Test
void signaturesEqualWhenGenericsDiffer() {
MethodDeclaration method1 =
parseBodyDeclaration("void x(List<Long> a) { }").asMethodDeclaration();
MethodDeclaration method2 =
parseBodyDeclaration("void x(List<Integer> a) { }").asMethodDeclaration();
assertEquals(method1.getSignature(), method2.getSignature());
}
@Test
void signaturesEqualWhenAnnotationsDiffer() {
MethodDeclaration method1 =
parseBodyDeclaration("void x(@A @B List a) { }").asMethodDeclaration();
MethodDeclaration method2 =
parseBodyDeclaration("void x(@C List a) { }").asMethodDeclaration();
assertEquals(method1.getSignature(), method2.getSignature());
}
@Test
void signaturesDifferentName() {
MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration();
MethodDeclaration method2 = parseBodyDeclaration("int y(String z);").asMethodDeclaration();
assertNotEquals(method1.getSignature(), method2.getSignature());
}
@Test
void signaturesDifferentTypes() {
MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration();
MethodDeclaration method2 = parseBodyDeclaration("int x(int z);").asMethodDeclaration();
assertNotEquals(method1.getSignature(), method2.getSignature());
}
@Test
void signaturesDifferentVarargs() {
MethodDeclaration method1 = parseBodyDeclaration("int x(int z);").asMethodDeclaration();
MethodDeclaration method2 = parseBodyDeclaration("int x(int... z);").asMethodDeclaration();
assertNotEquals(method1.getSignature(), method2.getSignature());
}
@Test
void signatureToString() {
MethodDeclaration method1 =
parseBodyDeclaration("int x(int z, String q);").asMethodDeclaration();
assertEquals("x(int, String)", method1.getSignature().toString());
}
@Test
void isVariableArityMethod() {
MethodDeclaration method1 = parseBodyDeclaration("int x(int... z);").asMethodDeclaration();
assertTrue(method1.isVariableArityMethod());
MethodDeclaration method2 =
parseBodyDeclaration("int x(int i, int... z);").asMethodDeclaration();
assertTrue(method2.isVariableArityMethod());
}
@Test
void isFixedArityMethod() {
MethodDeclaration method1 = parseBodyDeclaration("int x(int z);").asMethodDeclaration();
assertTrue(method1.isFixedArityMethod());
MethodDeclaration method2 = parseBodyDeclaration("int x();").asMethodDeclaration();
assertTrue(method2.isFixedArityMethod());
}
/*
* A method in the body of an interface may be declared public or private
* (§6.6). If no access modifier is given, the method is implicitly public.
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
*/
@Test
void isMethodInterfaceImplictlyPublic() {
CompilationUnit cu = parse("interface Foo { void m(); }");
assertTrue(cu.findFirst(MethodDeclaration.class).get().isPublic());
cu = parse("interface Foo { public void m(); }");
assertTrue(cu.findFirst(MethodDeclaration.class).get().isPublic());
cu = parse("interface Foo { abstract void m(); }");
assertTrue(cu.findFirst(MethodDeclaration.class).get().isPublic());
cu = parse("interface Foo { private void m(); }");
assertFalse(cu.findFirst(MethodDeclaration.class).get().isPublic());
}
/*
* An interface method lacking a private, default, or static modifier is implicitly abstract.
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
*/
@Test
void isMethodInterfaceImplictlyAbstract() {
CompilationUnit cu = parse("interface Foo { void m(); }");
assertTrue(cu.findFirst(MethodDeclaration.class).get().isAbstract());
cu = parse("interface Foo { abstract void m(); }");
assertTrue(cu.findFirst(MethodDeclaration.class).get().isAbstract());
cu = parse("interface Foo { private void m(); }");
assertFalse(cu.findFirst(MethodDeclaration.class).get().isAbstract());
cu = parse("interface Foo { static void m(); }");
assertFalse(cu.findFirst(MethodDeclaration.class).get().isAbstract());
cu = parse("interface Foo { default void m(){} }");
assertFalse(cu.findFirst(MethodDeclaration.class).get().isAbstract());
}
}

View File

@@ -0,0 +1,732 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import com.github.javaparser.utils.TestParser;
import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.opentest4j.AssertionFailedError;
public class RecordDeclarationTest {
@Nested
class LanguageLevels {
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_13", "JAVA_13_PREVIEW", "JAVA_14", "JAVA_15"})
void basicGrammarCompiles_languageLevelValidation_forbidden(ParserConfiguration.LanguageLevel languageLevel) {
String s = "record Point(int x, int y) { }";
assertThrows(AssertionFailedError.class, () -> {
CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s);
});
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_14_PREVIEW", "JAVA_15_PREVIEW", "JAVA_16", "JAVA_16_PREVIEW"})
void basicGrammarCompiles_languageLevelValidation_permitted(ParserConfiguration.LanguageLevel languageLevel) {
String s = "record Point(int x, int y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s);
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_14_PREVIEW", "JAVA_15_PREVIEW", "JAVA_16", "JAVA_16_PREVIEW"})
void languageLevelValidation_recordAsTypeIdentifier_permitted(ParserConfiguration.LanguageLevel languageLevel) {
String s = "class record {}";
assertThrows(AssertionFailedError.class, () -> {
CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s);
});
}
@ParameterizedTest
@EnumSource(
value = ParserConfiguration.LanguageLevel.class,
names = {"JAVA_13", "JAVA_13_PREVIEW", "JAVA_14", "JAVA_15"})
void languageLevelValidation_recordAsTypeIdentifier_forbidden(ParserConfiguration.LanguageLevel languageLevel) {
String s = "class record {}";
CompilationUnit cu = TestParser.parseCompilationUnit(languageLevel, s);
}
}
/**
* https://openjdk.java.net/jeps/395#Description
*/
@Test
void basicGrammarCompiles() {
String s = "record Point(int x, int y) { }";
assertOneRecordDeclaration(TestParser.parseCompilationUnit(s));
}
/**
* https://openjdk.java.net/jeps/395#Description
*/
@Test
void basicGrammar() {
String s = "record Point(int x, int y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
RecordDeclaration recordDeclaration =
cu.findAll(RecordDeclaration.class).get(0);
assertTrue(recordDeclaration.isRecordDeclaration());
assertTrue(recordDeclaration.getImplementedTypes().isEmpty());
assertTrue(recordDeclaration.getTypeParameters().isEmpty());
assertTrue(recordDeclaration.getFullyQualifiedName().isPresent());
assertEquals("Point", recordDeclaration.getFullyQualifiedName().get());
assertTrue(recordDeclaration.isRecordDeclaration());
NodeList<Parameter> parameters = recordDeclaration.getParameters();
assertEquals(2, parameters.size());
Parameter parameter0 = parameters.get(0);
assertEquals("x", parameter0.getNameAsString());
assertEquals("int", parameter0.getTypeAsString());
Parameter parameter1 = parameters.get(1);
assertEquals("y", parameter1.getNameAsString());
assertEquals("int", parameter1.getTypeAsString());
assertEquals(0, recordDeclaration.getMembers().size());
}
/**
* https://openjdk.java.net/jeps/395#Description
*/
@Test
void basicRecordPrints() {
String s = "record Point(int x, int y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
String expected = "" + "record Point(int x, int y) {\n" + "}\n" + "";
assertEqualsStringIgnoringEol(expected, cu.toString());
}
@Test
void genericRecordPrints() {
String s = "record Point<X,Y>(X x, Y y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
String expected = "" + "record Point<X, Y>(X x, Y y) {\n" + "}\n" + "";
assertEqualsStringIgnoringEol(expected, cu.toString());
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-record
*/
@Test
void record_cannotExtend() {
String s = "record Point(int x, int y) extends OtherThing { }";
assertCompilationFails(s);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_cannotBeAbstract() {
String s = "abstract record Point(int x, int y) { }";
assertCompilationFails(s);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_mayImplementInterfaces() {
String s = "record Point(int x, int y) implements OtherInterface { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_mayBeStatic() {
String s = "static record Point(int x, int y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
@Test
void recordWithVarArgs() {
String s = "record R(T1 c1, Tn... cn){ }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
List<RecordDeclaration> recordDeclarations = cu.findAll(RecordDeclaration.class);
assertEquals(1, recordDeclarations.size());
RecordDeclaration recordDeclaration = recordDeclarations.get(0);
NodeList<Parameter> parameters = recordDeclaration.getParameters();
assertEquals(2, parameters.size());
Parameter parameter0 = parameters.get(0);
assertEquals("c1", parameter0.getNameAsString());
assertEquals("T1", parameter0.getTypeAsString());
assertFalse(parameter0.isVarArgs());
Parameter parameter1 = parameters.get(1);
assertEquals("cn", parameter1.getNameAsString());
assertEquals("Tn", parameter1.getTypeAsString());
assertTrue(parameter1.isVarArgs());
}
@Test
void recordWithAnnotationedParameters() {
String s = "record Card(@MyAnno Rank rank, @MyAnno Suit suit) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
List<RecordDeclaration> recordDeclarations = cu.findAll(RecordDeclaration.class);
assertEquals(1, recordDeclarations.size());
RecordDeclaration recordDeclaration = recordDeclarations.get(0);
NodeList<Parameter> parameters = recordDeclaration.getParameters();
assertEquals(2, parameters.size());
Parameter parameter0 = parameters.get(0);
assertEquals("rank", parameter0.getNameAsString());
assertEquals("Rank", parameter0.getTypeAsString());
assertEquals(1, parameter0.getAnnotations().size());
Parameter parameter1 = parameters.get(1);
assertEquals("suit", parameter1.getNameAsString());
assertEquals("Suit", parameter1.getTypeAsString());
assertEquals(1, parameter1.getAnnotations().size());
assertEquals(0, recordDeclaration.getMembers().size());
}
@Test
void record_emptyMembers() {
String s = "record Point(int x, int y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
List<RecordDeclaration> recordDeclarations = cu.findAll(RecordDeclaration.class);
RecordDeclaration recordDeclaration = recordDeclarations.get(0);
assertEquals(0, recordDeclaration.getMembers().size());
}
@Test
void record_permitStaticMethods() {
String s = "" + "record ABC(int x, int y) {\n"
+ "\n"
+ " static public int abc() {\n"
+ " return x;\n"
+ " }\n"
+ "\n"
+ "}\n"
+ "";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
@Test
void record_permitMethods() {
String s = "" + "record ABC(int x, int y) {\n"
+ "\n"
+ " public int x() {\n"
+ " return x;\n"
+ " }\n"
+ "\n"
+ " public String xyz() {\n"
+ " return \"10\";\n"
+ " }\n"
+ "\n"
+ "}\n"
+ "";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
@Test
void record_forbidNonStaticFields() {
String s = "record Point(int x, int y) { int z; }";
assertCompilationFails(s);
}
@Test
void record_permitStaticFields() {
String s = "record Point(int x, int y) { static int z; }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
@Test
void record_permitPublicStaticFieldInRecord1() {
String s = "public final record RecordPublicField() {" + " public static final Object EMPTY = new Object();"
+ "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
@Test
void record_permitPublicStaticFieldInNestedRecord() {
String s =
"public final record RecordTopLevel(Object member) {\n" + " private static record RecordNested() {\n"
+ " public static final RecordNested EMPTY = new RecordNested();\n"
+ " }\n"
+ "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertTwoRecordDeclarations(cu);
}
@Test
void record_permitStaticFields2() {
String s = "" + "record ABC(int x, int y) {\n"
+ "\n"
+ " static int z;\n"
+ "\n"
+ " static {\n"
+ " int z = 10;\n"
+ " }\n"
+ "\n"
+ " public int x() {\n"
+ " return x;\n"
+ " }\n"
+ "\n"
+ "}\n"
+ "";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_isImplicitlyFinal() {
String s = "record Point(int x, int y) { static int z; }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.FINAL));
assertTrue(recordDeclaration.isFinal(), "Records are implicitly final.");
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_isImplicitlyFinalWithoutExplicit() {
String s = "record Point(int x, int y) { static int z; }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.FINAL));
assertTrue(recordDeclaration.isFinal(), "Records are implicitly final.");
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_canHaveGenerics() {
String s = "record Point <T> (T x, int y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertFalse(recordDeclaration.getTypeParameters().isEmpty());
assertEquals("T", recordDeclaration.getTypeParameters().get(0).getNameAsString());
}
@Test
void record_mustNotAllowMismatchedComponentAccessorReturnType() {
String s = "record Point(int x, int y) {\n" + " public String x() {\n"
+ " return \"10\";\n"
+ " }\n"
+ "}";
assertCompilationFails(s);
}
@Test
void record_allowMethodsWithSameNameAsRecordComponentButNotAnAccessorMethod() {
String s = "record Point(int x, int y) {\n" + " public String x(int a) {\n"
+ " return \"10\";\n"
+ " }\n"
+ "}";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
@Test
void record_allowMethodsWithSameNameAsRecordComponentButNotAnAccessorMethod2() {
String s = "record Point(int x, int y) {\n" + " public int x(int a) {\n"
+ " return 10;\n"
+ " }\n"
+ "}";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
@Test
void record_allowComponentAccessorWithMatchingType() {
String s =
"record Point(int x, int y) {\n" + " public int x() {\n" + " return 10;\n" + " }\n" + "}";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_allowNestedWithinClass() {
String s = "\n" + "class X {\n" + " record Point(int x, int y) {\n" + " }\n" + "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_componentsAreImplicitlyFinal() {
String s = "record Point(int x, int y) { }";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
RecordDeclaration recordDeclaration =
cu.findAll(RecordDeclaration.class).get(0);
NodeList<Parameter> parameters = recordDeclaration.getParameters();
assertTrue(parameters.get(0).isFinal());
assertTrue(parameters.get(1).isFinal());
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_allowClassWithinRecord() {
String s = "\n" + "record Point(int x, int y) {\n" + " class X {\n" + " }\n" + "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
List<RecordDeclaration> recordDeclarations = cu.findAll(RecordDeclaration.class);
assertEquals(1, recordDeclarations.size());
RecordDeclaration recordDeclaration = recordDeclarations.get(0);
BodyDeclaration<?> member = recordDeclaration.getMember(0);
assertTrue(member.isClassOrInterfaceDeclaration());
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_allowNestedWithinInterface() {
String s = "\n" + "interface X {\n" + " record Point(int x, int y) {\n" + " }\n" + "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_allowNestedWithinEnum() {
String s = "\n" + "enum ABC {\n"
+ " ABC;\n"
+ " \n"
+ " record Point(int x, int y) {\n"
+ " }\n"
+ "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_allowNestedMultiple() {
String s = "\n" + "interface Y {\n"
+ " class X {\n"
+ " record Point(int x, int y) {\n"
+ " }\n"
+ " }\n"
+ "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_allowNestedMultiple2() {
String s = "\n" + "interface Y {\n"
+ " class X {\n"
+ " record Point(int x, int y) {\n"
+ " }\n"
+ " record PointB(int x, int y) {\n"
+ " }\n"
+ " }\n"
+ "\n"
+ " record PointC(int x, int y) {\n"
+ " }\n"
+ "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
List<RecordDeclaration> recordDeclarations = cu.findAll(RecordDeclaration.class);
assertEquals(3, recordDeclarations.size());
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_topLevelRecordsAreNotStatic() {
String s = "record Point(int x, int y) { }\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
RecordDeclaration recordDeclaration =
cu.findAll(RecordDeclaration.class).get(0);
assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.STATIC));
assertFalse(recordDeclaration.isStatic(), "Top level Records are NOT implicitly static.");
}
/**
* https://openjdk.java.net/jeps/395#Restrictions-on-records
*/
@Test
void record_nestedRecordsAreImplicitlyStatic() {
String s = "\n" + "class X {\n" + " record Point(int x, int y) {\n" + " }\n" + "}\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
RecordDeclaration recordDeclaration =
cu.findAll(RecordDeclaration.class).get(0);
assertFalse(recordDeclaration.hasModifier(Modifier.Keyword.STATIC));
assertTrue(recordDeclaration.isStatic(), "Nested Records are implicitly static.");
}
@Test
void record_canBeCreatedUsingKeywordNew() {
String s = "\n" + "\n"
+ "record Point(int x, int y) {\n"
+ "}\n"
+ "\n"
+ "class X {\n"
+ " public static void main(String[] args) {\n"
+ " new Point(10, 3);\n"
+ " }\n"
+ "}\n\n";
CompilationUnit cu = TestParser.parseCompilationUnit(s);
assertOneRecordDeclaration(cu);
ClassOrInterfaceDeclaration coid =
cu.findAll(ClassOrInterfaceDeclaration.class).get(0);
List<ObjectCreationExpr> objectCreationExprs = coid.findAll(ObjectCreationExpr.class);
assertEquals(1, objectCreationExprs.size());
ObjectCreationExpr objectCreationExpr = objectCreationExprs.get(0);
assertEquals("Point", objectCreationExpr.getTypeAsString());
}
/**
* Note the Record Declaration Constructor does not include parameters.
* (parameters are, instead, included within the record declaration)
* <p>
* https://bugs.openjdk.java.net/browse/JDK-8222777
*/
@Test
void recordDeclarationFromTheJDK8222777() {
CompilationUnit cu = TestParser.parseCompilationUnit("" + "public record Range(int lo, int hi) {\n"
+ "\n"
+ " public Range {\n"
+ " if (lo > hi) /* referring here to the implicit constructor parameters */\n"
+ " throw new IllegalArgumentException(String.format(\"(%d,%d)\", lo, hi));\n"
+ " }\n"
+ "}");
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertThat(recordDeclaration.getNameAsString()).isEqualTo("Range");
assertThat(recordDeclaration.getModifiers()).containsExactly(Modifier.publicModifier());
// test parameters
// get constructor
// test parameters (none)
}
@Test
void recordDeclaration_exampleFromJls_8_10_4_1_normalCanonicalConstructors() {
CompilationUnit cu = TestParser.parseCompilationUnit("" + "import java.lang.annotation.Target;\n"
+ "import java.lang.annotation.ElementType;\n"
+ "\n"
+ "@interface Foo {}\n"
+ "@interface Bar {}\n"
+ "\n"
+ "record Person(@Foo String name) {\n"
+ " Person(String name2) {\n"
+ " }\n"
+ "}");
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertThat(recordDeclaration.getNameAsString()).isEqualTo("Person");
assertThat(recordDeclaration.getModifiers()).isEmpty();
assertThat(recordDeclaration.getConstructors()).hasSize(1);
assertThat(recordDeclaration.getCompactConstructors()).hasSize(0);
}
@Test
void compactConstructor_exampleFromJls_8_10_4_2_compactConstructors() {
CompilationUnit cu = TestParser.parseCompilationUnit("" + "record Rational(int num, int denom) {\n"
+ " private static int gcd(int a, int b) {\n"
+ " if (b == 0) return Math.abs(a);\n"
+ " else return gcd(b, a % b);\n"
+ " }\n"
+ " \n"
+ " Rational {\n"
+ " int gcd = gcd(num, denom);\n"
+ " num /= gcd;\n"
+ " denom /= gcd;\n"
+ " }\n"
+ "}\n");
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertThat(recordDeclaration.getNameAsString()).isEqualTo("Rational");
assertThat(recordDeclaration.getModifiers()).isEmpty();
assertThat(recordDeclaration.getConstructors()).hasSize(0);
assertThat(recordDeclaration.getCompactConstructors()).hasSize(1);
}
@Test
void nonCompactConstructor_exampleFromJls_8_10_4_2_compactConstructors() {
CompilationUnit cu = TestParser.parseCompilationUnit("" + "record Rational(int num, int denom) {\n"
+ " private static int gcd(int a, int b) {\n"
+ " if (b == 0) return Math.abs(a);\n"
+ " else return gcd(b, a % b);\n"
+ " }\n"
+ " \n"
+ " Rational(int num, int demon) {\n"
+ " int gcd = gcd(num, denom);\n"
+ " num /= gcd;\n"
+ " denom /= gcd;\n"
+ " this.num = num;\n"
+ " this.denom = denom;\n"
+ " }\n"
+ "}\n");
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertThat(recordDeclaration.getNameAsString()).isEqualTo("Rational");
assertThat(recordDeclaration.getModifiers()).isEmpty();
assertThat(recordDeclaration.getConstructors()).hasSize(1);
assertThat(recordDeclaration.getCompactConstructors()).hasSize(0);
}
/**
* https://openjdk.java.net/jeps/395
*/
@Test
void localRecords() {
CompilationUnit cu = TestParser.parseCompilationUnit("" + "class Scratch {\n"
+ " List<Merchant> findTopMerchants(List<Merchant> merchants, int month) {\n"
+ " // Local record\n"
+ " record MerchantSales(Merchant merchant, double sales) {}\n"
+ "\n"
+ " return merchants.stream()\n"
+ " .map(merchant -> new MerchantSales(merchant, computeSales(merchant, month)))\n"
+ " .sorted((m1, m2) -> Double.compare(m2.sales(), m1.sales()))\n"
+ " .map(MerchantSales::merchant)\n"
+ " .collect(toList());\n"
+ " }\n"
+ "}\n");
RecordDeclaration recordDeclaration =
cu.findFirst(RecordDeclaration.class).get();
assertThat(recordDeclaration.getNameAsString()).isEqualTo("MerchantSales");
}
@Test
void instanceFieldIsNotAllowedInRecord() {
String s = "record X { int record; }";
assertThrows(AssertionFailedError.class, () -> {
CompilationUnit cu = TestParser.parseCompilationUnit(s);
});
}
private void assertCompilationFails(String s) {
assertThrows(AssertionFailedError.class, () -> {
CompilationUnit cu = TestParser.parseCompilationUnit(s);
});
}
private void assertOneRecordDeclaration(CompilationUnit cu) {
List<RecordDeclaration> recordDeclarations = cu.findAll(RecordDeclaration.class);
assertEquals(1, recordDeclarations.size());
}
private void assertTwoRecordDeclarations(CompilationUnit cu) {
List<RecordDeclaration> recordDeclarations = cu.findAll(RecordDeclaration.class);
assertEquals(2, recordDeclarations.size());
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.TestParser.parseBodyDeclaration;
import static com.github.javaparser.utils.TestParser.parseCompilationUnit;
import static java.util.stream.Collectors.joining;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.Node;
import org.junit.jupiter.api.Test;
class TypeDeclarationTest {
@Test
void qualifiedNameOfClassInDefaultPackage() {
assertFQN("X", parseCompilationUnit("class X{ }"));
}
@Test
void qualifiedNameOfClassInAPackage() {
assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; class X{}"));
}
@Test
void qualifiedNameOfInterfaceInAPackage() {
assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; interface X{}"));
}
@Test
void qualifiedNameOfEnumInAPackage() {
assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; enum X{}"));
}
@Test
void qualifiedNameOfAnnotationInAPackage() {
assertFQN("a.b.c.X", parseCompilationUnit("package a.b.c; @interface X{}"));
}
@Test
void qualifiedNameOfNestedClassInAPackage() {
assertFQN(
"a.b.c.Outer,a.b.c.Outer.Nested",
parseCompilationUnit("package a.b.c; class Outer{ class Nested {} }"));
}
@Test
void qualifiedNameOfAnonymousClassCantBeQueried() {
assertFQN("X", parseCompilationUnit("class X{ int aaa() {new Object(){};} }"));
}
@Test
void qualifiedNameOfLocalClassIsEmpty() {
assertFQN("X,?", parseCompilationUnit("class X{ int aaa() {class Local {}} }"));
}
@Test
void qualifiedNameOfDetachedClassIsEmpty() {
assertFQN("?", parseBodyDeclaration("class X{}"));
}
void assertFQN(String fqn, Node node) {
assertEquals(
fqn,
node.findAll(TypeDeclaration.class).stream()
.map(td -> (TypeDeclaration<?>) td)
.map(td -> td.getFullyQualifiedName().orElse("?"))
.collect(joining(",")));
}
}

View File

@@ -0,0 +1,209 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.comments;
import static com.github.javaparser.StaticJavaParser.parse;
import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.javadoc.Javadoc;
import com.github.javaparser.javadoc.description.JavadocDescription;
import com.github.javaparser.printer.configuration.DefaultConfigurationOption;
import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration;
import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration.ConfigOption;
import com.github.javaparser.printer.configuration.Indentation;
import com.github.javaparser.printer.configuration.Indentation.IndentType;
import com.github.javaparser.printer.configuration.PrinterConfiguration;
import com.github.javaparser.utils.LineSeparator;
import org.junit.jupiter.api.Test;
class CommentTest {
private static final PrinterConfiguration PRETTY_PRINTER_CONFIG_TWO_INDENT = new DefaultPrinterConfiguration()
.addOption(new DefaultConfigurationOption(ConfigOption.INDENTATION, new Indentation(IndentType.SPACES, 2)));
@Test
void removeOrphanComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A");
Comment c = new LineComment("A comment");
decl.addOrphanComment(c);
assertEquals(1, decl.getOrphanComments().size());
assertTrue(c.remove());
assertEquals(0, decl.getOrphanComments().size());
}
@Test
void removeAssociatedComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "A");
Comment c = new LineComment("A comment");
decl.setComment(c);
assertTrue(decl.getComment().isPresent());
assertTrue(c.remove());
assertFalse(decl.getComment().isPresent());
}
@Test
void cannotRemoveCommentNotUsedAnywhere() {
Comment c = new LineComment("A comment");
assertFalse(c.remove());
}
@Test
void unicodeEscapesArePreservedInComments() {
CompilationUnit cu = parse("// xxx\\u2122xxx");
Comment comment = cu.getAllContainedComments().get(0);
assertEquals(" xxx\\u2122xxx", comment.getContent());
}
@Test
void testReplaceDuplicateJavaDocComment() {
// Arrange
CompilationUnit cu = parse("public class MyClass {" + LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ " /**"
+ LineSeparator.SYSTEM + " * Comment A"
+ LineSeparator.SYSTEM + " */"
+ LineSeparator.SYSTEM + " public void oneMethod() {"
+ LineSeparator.SYSTEM + " }"
+ LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ " /**"
+ LineSeparator.SYSTEM + " * Comment A"
+ LineSeparator.SYSTEM + " */"
+ LineSeparator.SYSTEM + " public void anotherMethod() {"
+ LineSeparator.SYSTEM + " }"
+ LineSeparator.SYSTEM + "}"
+ LineSeparator.SYSTEM);
MethodDeclaration methodDeclaration =
cu.findFirst(MethodDeclaration.class).get();
// Act
Javadoc javadoc = new Javadoc(JavadocDescription.parseText("Change Javadoc"));
methodDeclaration.setJavadocComment("", javadoc);
// Assert
assertEqualsStringIgnoringEol(
"public class MyClass {\n" + "\n"
+ " /**\n"
+ " * Change Javadoc\n"
+ " */\n"
+ " public void oneMethod() {\n"
+ " }\n"
+ "\n"
+ " /**\n"
+ " * Comment A\n"
+ " */\n"
+ " public void anotherMethod() {\n"
+ " }\n"
+ "}\n",
cu.toString(PRETTY_PRINTER_CONFIG_TWO_INDENT));
}
@Test
void testRemoveDuplicateComment() {
// Arrange
CompilationUnit cu = parse("public class MyClass {" + LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ " /**"
+ LineSeparator.SYSTEM + " * Comment A"
+ LineSeparator.SYSTEM + " */"
+ LineSeparator.SYSTEM + " public void oneMethod() {"
+ LineSeparator.SYSTEM + " }"
+ LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ " /**"
+ LineSeparator.SYSTEM + " * Comment A"
+ LineSeparator.SYSTEM + " */"
+ LineSeparator.SYSTEM + " public void anotherMethod() {"
+ LineSeparator.SYSTEM + " }"
+ LineSeparator.SYSTEM + "}"
+ LineSeparator.SYSTEM);
MethodDeclaration methodDeclaration =
cu.findFirst(MethodDeclaration.class).get();
// Act
methodDeclaration.removeComment();
// Assert
assertEqualsStringIgnoringEol(
"public class MyClass {\n" + "\n"
+ " public void oneMethod() {\n"
+ " }\n"
+ "\n"
+ " /**\n"
+ " * Comment A\n"
+ " */\n"
+ " public void anotherMethod() {\n"
+ " }\n"
+ "}\n",
cu.toString(PRETTY_PRINTER_CONFIG_TWO_INDENT));
}
@Test
void testRemoveDuplicateJavaDocComment() {
// Arrange
CompilationUnit cu = parse("public class MyClass {" + LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ " /**"
+ LineSeparator.SYSTEM + " * Comment A"
+ LineSeparator.SYSTEM + " */"
+ LineSeparator.SYSTEM + " public void oneMethod() {"
+ LineSeparator.SYSTEM + " }"
+ LineSeparator.SYSTEM + LineSeparator.SYSTEM
+ " /**"
+ LineSeparator.SYSTEM + " * Comment A"
+ LineSeparator.SYSTEM + " */"
+ LineSeparator.SYSTEM + " public void anotherMethod() {"
+ LineSeparator.SYSTEM + " }"
+ LineSeparator.SYSTEM + "}"
+ LineSeparator.SYSTEM);
MethodDeclaration methodDeclaration =
cu.findAll(MethodDeclaration.class).get(1);
// Act
methodDeclaration.removeJavaDocComment();
// Assert
assertEqualsStringIgnoringEol(
"public class MyClass {\n" + "\n"
+ " /**\n"
+ " * Comment A\n"
+ " */\n"
+ " public void oneMethod() {\n"
+ " }\n"
+ "\n"
+ " public void anotherMethod() {\n"
+ " }\n"
+ "}\n",
cu.toString(PRETTY_PRINTER_CONFIG_TWO_INDENT));
}
@Test()
void testVerifyOrphanCommentInsertedInEmptyBlock() {
BlockStmt block = new BlockStmt();
block.addOrphanComment(new LineComment("TODO"));
assertTrue(block.toString().contains("TODO"));
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.ArrayCreationLevel;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.type.PrimitiveType;
import org.junit.jupiter.api.Test;
class ArrayCreationExprTest {
@Test
void correctlyCreatesExpressionWithDefaultConstructor() {
ArrayCreationExpr expr = new ArrayCreationExpr();
assertEquals("new empty[] {}", expr.toString());
}
@Test
void correctlyCreatesExpressionWithSimpleConstructor() {
ArrayCreationExpr expr = new ArrayCreationExpr(PrimitiveType.byteType());
assertEquals("new byte[] {}", expr.toString());
}
@Test
void correctlyCreatesExpressionWithFullConstructor() {
ArrayInitializerExpr initializer = new ArrayInitializerExpr(
new NodeList<>(new IntegerLiteralExpr("1"), new IntegerLiteralExpr("2"), new IntegerLiteralExpr("3")));
ArrayCreationExpr expr =
new ArrayCreationExpr(PrimitiveType.intType(), new NodeList<>(new ArrayCreationLevel()), initializer);
assertEquals("new int[] { 1, 2, 3 }", expr.toString());
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class AssignExprTest {
@Test
void convertOperator() {
assertEquals(
BinaryExpr.Operator.PLUS,
AssignExpr.Operator.PLUS.toBinaryOperator().get());
}
}

View File

@@ -0,0 +1,138 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.StaticJavaParser;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class BinaryExprTest {
@Test
void convertOperator() {
assertEquals(
AssignExpr.Operator.PLUS,
BinaryExpr.Operator.PLUS.toAssignOperator().get());
}
/**
* Evaluation takes place left to right, with && taking precedence over ||
*
* true || false && false || false
* true || (1) || false
* ( 2 ) || false
* ( 3 )
*
* true || false && false || false
* true || (false) || false
* ( true ) || false
* ( true )
*/
@Nested
class LogicalOperatorPrecedence {
@Test
public void logicalAndOr() {
Expression expression = StaticJavaParser.parseExpression("true || false && false || false");
Expression bracketedExpression = applyBrackets(expression);
String expected = "(true || (false && false)) || false";
String actual = bracketedExpression.toString();
assertEquals(expected, actual);
}
@Test
public void logicalOrEvaluationLeftToRight() {
Expression expression = StaticJavaParser.parseExpression("false || true || false || true || false || true");
Expression bracketedExpression = applyBrackets(expression);
String expected = "((((false || true) || false) || true) || false) || true";
String actual = bracketedExpression.toString();
assertEquals(expected, actual);
}
@Test
public void logicalAndEvaluationLeftToRight() {
Expression expression = StaticJavaParser.parseExpression("false && true && false && true && false && true");
Expression bracketedExpression = applyBrackets(expression);
String expected = "((((false && true) && false) && true) && false) && true";
String actual = bracketedExpression.toString();
assertEquals(expected, actual);
}
@Test
public void andTakesPrecedenceOverOr() {
Expression expression = StaticJavaParser.parseExpression("true || false && false");
Expression bracketedExpression = applyBrackets(expression);
String expected = "true || (false && false)";
String actual = bracketedExpression.toString();
assertEquals(expected, actual);
}
@Test
public void andTakesPrecedenceOverOrThenLeftToRight() {
Expression expression = StaticJavaParser.parseExpression("true || false && false || true");
Expression bracketedExpression = applyBrackets(expression);
String expected = "(true || (false && false)) || true";
String actual = bracketedExpression.toString();
assertEquals(expected, actual);
}
@Test
public void example() {
Expression expression =
StaticJavaParser.parseExpression("year % 4 == 0 && year % 100 != 0 || year % 400 == 0");
Expression bracketedExpression = applyBrackets(expression);
String expected = "((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)";
String actual = bracketedExpression.toString();
assertEquals(expected, actual);
}
}
private Expression applyBrackets(Expression expression) {
expression.findAll(BinaryExpr.class).stream()
.filter(binaryExpr -> binaryExpr.getOperator() == BinaryExpr.Operator.AND
|| binaryExpr.getOperator() == BinaryExpr.Operator.OR)
.forEach(binaryExpr -> {
if (!binaryExpr.getLeft().isBooleanLiteralExpr()) {
binaryExpr.setLeft(new EnclosedExpr(binaryExpr.getLeft()));
}
if (!binaryExpr.getRight().isBooleanLiteralExpr()) {
binaryExpr.setRight(new EnclosedExpr(binaryExpr.getRight()));
}
});
return expression;
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseStart;
import com.github.javaparser.ParserConfiguration;
import org.junit.jupiter.api.Test;
class CharLiteralExprTest {
@Test
void parseSimpleChar() {
CharLiteralExpr c = parseExpression("'a'");
assertEquals("a", c.getValue());
}
@Test
void parseSimpleEscape() {
CharLiteralExpr c = parseExpression("'\\t'");
assertEquals("\\t", c.getValue());
}
@Test
void parseUnicode() {
CharLiteralExpr c = parseExpression("'Ω'");
assertEquals("Ω", c.getValue());
}
@Test
void parseNumericEscape() {
CharLiteralExpr c = parseExpression("'\\177'");
assertEquals("\\177", c.getValue());
}
@Test
void parseUnicodeEscape() {
CharLiteralExpr c = parseExpression("'\\u03a9'");
assertEquals("\\u03a9", c.getValue());
}
@Test
void parseUnicodeEscapedEscape() {
JavaParser javaParser = new JavaParser(new ParserConfiguration().setPreprocessUnicodeEscapes(true));
CharLiteralExpr c = javaParser
.parse(ParseStart.EXPRESSION, provider("'\\u005c''"))
.getResult()
.get()
.asCharLiteralExpr();
assertEquals("\\'", c.getValue());
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class DoubleLiteralExprTest {
@Test
void test1() {
float x = 0x0.00_00_02p-126f;
DoubleLiteralExpr e = parseExpression("0x0.00_00_02p-126f");
Assertions.assertEquals(x, e.asDouble());
}
@Test
void test2() {
double x = 0x0.000_000_000_000_1p-1_022;
DoubleLiteralExpr e = parseExpression("0x0.000_000_000_000_1p-1_022");
Assertions.assertEquals(x, e.asDouble());
}
@Test
void test3() {
double a = 0x1.p+1;
DoubleLiteralExpr e = parseExpression("0x1.p+1");
Assertions.assertEquals(a, e.asDouble());
}
@Test
void test4() {
double a = 0x.0p0;
DoubleLiteralExpr e = parseExpression("0x.0p0");
Assertions.assertEquals(a, e.asDouble());
}
@Test
void test5() {
double x = 0x0_0.0_0p-1_0;
DoubleLiteralExpr e = parseExpression("0x0_0.0_0p-1_0");
Assertions.assertEquals(x, e.asDouble());
}
}

View File

@@ -0,0 +1,178 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.ParserConfiguration.LanguageLevel;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.utils.TestParser;
import org.junit.jupiter.api.Test;
/**
* See the following JEPs: "Pattern Matching for instanceof"
* <ul>
* <li>JDK14 - Preview - https://openjdk.java.net/jeps/305</li>
* <li>JDK15 - Second Preview - https://openjdk.java.net/jeps/375</li>
* <li>JDK16 - Release - https://openjdk.java.net/jeps/395</li>
* </ul>
*
* <blockquote>
* The instanceof grammar is extended accordingly:
*
* <pre>
* RelationalExpression:
* ...
* RelationalExpression instanceof ReferenceType
* RelationalExpression instanceof Pattern
*
* Pattern:
* ReferenceType Identifier
* </pre>
* </blockquote>
*/
class InstanceOfExprTest {
@Test
void annotationsOnTheType_patternExpression() {
InstanceOfExpr expr =
TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, "obj instanceof @A @DA String s");
assertThat(expr.getType().getAnnotations())
.containsExactly(new MarkerAnnotationExpr("A"), new MarkerAnnotationExpr("DA"));
}
@Test
void annotationsOnTheType_finalPatternExpression() {
InstanceOfExpr expr =
TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, "obj instanceof @A final @DA String s");
assertThat(expr.getType().getAnnotations())
.containsExactly(new MarkerAnnotationExpr("A"), new MarkerAnnotationExpr("DA"));
}
@Test
void annotationsOnTheType_finalPatternExpression_prettyPrinter() {
InstanceOfExpr expr =
TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, "obj instanceof @A final @DA String s");
assertEquals("obj instanceof final @A @DA String s", expr.toString());
}
@Test
void annotationsOnTheType_referenceTypeExpression() {
InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14, "obj instanceof @A @DA String");
assertThat(expr.getType().getAnnotations())
.containsExactly(new MarkerAnnotationExpr("A"), new MarkerAnnotationExpr("DA"));
}
@Test
void instanceOf_patternExpression() {
String x = "obj instanceof String s";
InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x);
assertEquals("obj", expr.getExpression().toString());
assertEquals("String", expr.getType().asString());
assertTrue(expr.getPattern().isPresent());
PatternExpr patternExpr = expr.getPattern().get();
assertInstanceOf(TypePatternExpr.class, patternExpr);
TypePatternExpr typePatternExpr = patternExpr.asTypePatternExpr();
assertEquals("String", typePatternExpr.getType().asString());
assertEquals("s", typePatternExpr.getName().asString());
assertFalse(typePatternExpr.isFinal());
//
assertTrue(expr.getName().isPresent());
assertEquals("s", expr.getName().get().asString());
}
@Test
void instanceOf_patternExpression_prettyPrinter() {
String x = "obj instanceof String s";
InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x);
assertEquals("obj instanceof String s", expr.toString());
}
@Test
void instanceOf_referenceTypeExpression() {
String x = "obj instanceof String";
InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14, x);
assertEquals("obj", expr.getExpression().toString());
assertEquals(String.class.getSimpleName(), expr.getType().asString());
assertFalse(expr.getPattern().isPresent());
//
assertFalse(expr.getName().isPresent());
}
@Test
void instanceOf_finalPatternExpression() {
String x = "obj instanceof final String s";
InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x);
assertEquals("obj", expr.getExpression().toString());
assertEquals("String", expr.getType().asString());
assertTrue(expr.getPattern().isPresent());
PatternExpr patternExpr = expr.getPattern().get();
assertInstanceOf(TypePatternExpr.class, patternExpr);
TypePatternExpr typePatternExpr = patternExpr.asTypePatternExpr();
assertEquals("String", typePatternExpr.getType().asString());
assertEquals("s", typePatternExpr.getName().asString());
assertTrue(typePatternExpr.isFinal());
//
assertTrue(expr.getName().isPresent());
assertEquals("s", expr.getName().get().asString());
}
@Test
void instanceOf_finalPatternExpression_prettyPrinter() {
String x = "obj instanceof final String s";
InstanceOfExpr expr = TestParser.parseExpression(LanguageLevel.JAVA_14_PREVIEW, x);
assertEquals("obj instanceof final String s", expr.toString());
}
/*
* resolution / scoping tests?
*
* <pre>
* {@code
* if (!(obj instanceof String s)) {
* .. s.contains(..) ..
* } else {
* .. s.contains(..) ..
* }
* }
* </pre>
*
* Allowed / in scope: {@code if (obj instanceof String s && s.length() > 5) {..}}
* Not in scope: {@code if (obj instanceof String s || s.length() > 5) {..}}
*
*/
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseBlock;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.type.UnknownType;
import org.junit.jupiter.api.Test;
class LambdaExprTest {
@Test
void lambdaRange1() {
Expression expression = parseExpression("x -> y");
assertRange("x", "y", expression);
}
@Test
void lambdaRange2() {
Expression expression = parseExpression("(x) -> y");
assertRange("(", "y", expression);
}
private void assertRange(String startToken, String endToken, Node node) {
TokenRange tokenRange = node.getTokenRange().get();
assertEquals(startToken, tokenRange.getBegin().asString());
assertEquals(endToken, tokenRange.getEnd().asString());
}
@Test
void getExpressionBody() {
LambdaExpr lambdaExpr = parseExpression("x -> y").asLambdaExpr();
assertEquals("Optional[y]", lambdaExpr.getExpressionBody().toString());
}
@Test
void getNoExpressionBody() {
LambdaExpr lambdaExpr = parseExpression("x -> {y;}").asLambdaExpr();
assertEquals("Optional.empty", lambdaExpr.getExpressionBody().toString());
}
@Test
void oneParameterAndExpressionUtilityConstructor() {
LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseExpression("5"));
assertEquals("a -> 5", expr.toString());
}
@Test
void oneParameterAndStatementUtilityConstructor() {
LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseBlock("{return 5;}"));
assertEqualsStringIgnoringEol("a -> {\n return 5;\n}", expr.toString());
}
@Test
void multipleParametersAndExpressionUtilityConstructor() {
LambdaExpr expr = new LambdaExpr(
new NodeList<>(new Parameter(new UnknownType(), "a"), new Parameter(new UnknownType(), "b")),
parseExpression("5"));
assertEquals("(a, b) -> 5", expr.toString());
}
@Test
void multipleParametersAndStatementUtilityConstructor() {
LambdaExpr expr = new LambdaExpr(
new NodeList<>(new Parameter(new UnknownType(), "a"), new Parameter(new UnknownType(), "b")),
parseBlock("{return 5;}"));
assertEqualsStringIgnoringEol("(a, b) -> {\n return 5;\n}", expr.toString());
}
@Test
void zeroParametersAndStatementUtilityConstructor() {
LambdaExpr expr = new LambdaExpr(new NodeList<>(), parseBlock("{return 5;}"));
assertEqualsStringIgnoringEol("() -> {\n return 5;\n}", expr.toString());
}
}

View File

@@ -0,0 +1,188 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigInteger;
import org.assertj.core.data.Percentage;
import org.junit.jupiter.api.Test;
@SuppressWarnings("OctalInteger")
class LiteralStringValueExprTest {
@Test
void trivialLiteralsAreConverted() {
assertThat(new CharLiteralExpr('\t').getValue()).isEqualTo("\\t");
assertThat(new CharLiteralExpr('\b').getValue()).isEqualTo("\\b");
assertThat(new CharLiteralExpr('\f').getValue()).isEqualTo("\\f");
assertThat(new CharLiteralExpr('\r').getValue()).isEqualTo("\\r");
assertThat(new CharLiteralExpr('\n').getValue()).isEqualTo("\\n");
assertThat(new CharLiteralExpr('\\').getValue()).isEqualTo("\\\\");
assertThat(new CharLiteralExpr('\"').getValue()).isEqualTo("\\\"");
assertThat(new IntegerLiteralExpr("0B0").asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr("0b0").asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr("0X0").asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr("0x0").asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr(0).asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr(00).asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr(0B0).asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr(0b0).asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr(0X0).asInt()).isEqualTo(0);
assertThat(new IntegerLiteralExpr(0x0).asInt()).isEqualTo(0);
assertThat(new LongLiteralExpr("0B0L").asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr("0b0L").asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr("0X0L").asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr("0x0L").asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr(0L).asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr(00L).asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr(0B0L).asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr(0b0L).asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr(0X0L).asLong()).isEqualTo(0);
assertThat(new LongLiteralExpr(0x0L).asLong()).isEqualTo(0);
assertThat(new DoubleLiteralExpr("0.0f").asDouble()).isEqualTo(0.0);
assertThat(new DoubleLiteralExpr("0.0F").asDouble()).isEqualTo(0.0);
assertThat(new DoubleLiteralExpr("0.0d").asDouble()).isEqualTo(0.0);
assertThat(new DoubleLiteralExpr("0.0D").asDouble()).isEqualTo(0.0);
assertThat(new DoubleLiteralExpr(0.0F).asDouble()).isEqualTo(0.0);
assertThat(new DoubleLiteralExpr(0.0f).asDouble()).isEqualTo(0.0);
assertThat(new DoubleLiteralExpr(0.0D).asDouble()).isEqualTo(0.0);
assertThat(new DoubleLiteralExpr(0.0d).asDouble()).isEqualTo(0.0);
}
@Test
void lowerAndUpperBoundIntegersAreConverted() {
IntegerLiteralExpr dec = parseExpression("2147483647");
IntegerLiteralExpr posOct = parseExpression("0177_7777_7777");
IntegerLiteralExpr negOct = parseExpression("0377_7777_7777");
IntegerLiteralExpr posHex = parseExpression("0x7fff_ffff");
IntegerLiteralExpr negHex = parseExpression("0xffff_ffff");
IntegerLiteralExpr posBin = parseExpression("0b0111_1111_1111_1111_1111_1111_1111_1111");
IntegerLiteralExpr negBin = parseExpression("0b1000_0000_0000_0000_0000_0000_0000_0000");
assertThat(dec.asInt()).isEqualTo(2147483647);
assertThat(posOct.asInt()).isEqualTo(2147483647); // 0177_7777_7777
assertThat(negOct.asInt()).isEqualTo(-1); // 0377_7777_7777
assertThat(posHex.asInt()).isEqualTo(0x7fff_ffff);
assertThat(negHex.asInt()).isEqualTo(0xffff_ffff);
assertThat(posBin.asInt()).isEqualTo(0b0111_1111_1111_1111_1111_1111_1111_1111);
assertThat(negBin.asInt()).isEqualTo(0b1000_0000_0000_0000_0000_0000_0000_0000);
}
@Test
void negativeLiteralValues() {
UnaryExpr unaryIntExpr = parseExpression("-2147483648"); // valid, Integer.MIN_VALUE
IntegerLiteralExpr literalIntExpr = (IntegerLiteralExpr) unaryIntExpr.getExpression();
IntegerLiteralExpr notValidIntExpr = parseExpression("2147483648"); // not valid
UnaryExpr unaryLongExpr = parseExpression("-9223372036854775808L"); // valid, Long.MIN_VALUE
LongLiteralExpr literalLongExpr = (LongLiteralExpr) unaryLongExpr.getExpression();
LongLiteralExpr notValidLongExpr = parseExpression("9223372036854775808L"); // not valid
assertThat(literalIntExpr.asNumber()).isEqualTo(2147483648L);
assertThat(literalLongExpr.asNumber()).isEqualTo(new BigInteger("9223372036854775808"));
assertThatThrownBy(notValidIntExpr::asNumber).isInstanceOf(NumberFormatException.class);
assertThatThrownBy(notValidLongExpr::asNumber).isInstanceOf(NumberFormatException.class);
}
@Test
void lowerAndUpperBoundLongsAreConverted() {
LongLiteralExpr dec = parseExpression("9223372036854775807L");
LongLiteralExpr posOct = parseExpression("07_7777_7777_7777_7777_7777L");
LongLiteralExpr negOct = parseExpression("010_0000_0000_0000_0000_0000L");
LongLiteralExpr posHex = parseExpression("0x7fff_ffff_ffff_ffffL");
LongLiteralExpr negHex = parseExpression("0xffff_ffff_ffff_ffffL");
LongLiteralExpr posBin =
parseExpression("0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111L");
LongLiteralExpr negBin =
parseExpression("0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000L");
assertThat(dec.asLong()).isEqualTo(9223372036854775807L);
assertThat(posOct.asLong()).isEqualTo(9223372036854775807L); // 07_7777_7777_7777_7777_7777L
assertThat(negOct.asLong()).isEqualTo(-9223372036854775808L); // 010_0000_0000_0000_0000_0000L
assertThat(posHex.asLong()).isEqualTo(0x7fff_ffff_ffff_ffffL);
assertThat(negHex.asLong()).isEqualTo(0xffff_ffff_ffff_ffffL);
assertThat(posBin.asLong())
.isEqualTo(0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111L);
assertThat(negBin.asLong())
.isEqualTo(0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000L);
}
@Test
void charLiteralsAreConverted() {
CharLiteralExpr a = parseExpression("'a'");
CharLiteralExpr percent = parseExpression("'%'");
CharLiteralExpr tab = parseExpression("'\\t'");
CharLiteralExpr newLine = parseExpression("'\\n'");
CharLiteralExpr slash = parseExpression("'\\\\'");
CharLiteralExpr quote = parseExpression("'\\''");
CharLiteralExpr omega = parseExpression("'\\u03a9'");
CharLiteralExpr unicode = parseExpression("'\\uFFFF'");
CharLiteralExpr ascii = parseExpression("'\\177'");
CharLiteralExpr trademark = parseExpression("'™'");
assertThat(a.asChar()).isEqualTo('a');
assertThat(percent.asChar()).isEqualTo('%');
assertThat(tab.asChar()).isEqualTo('\t');
assertThat(newLine.asChar()).isEqualTo('\n');
assertThat(slash.asChar()).isEqualTo('\\');
assertThat(quote.asChar()).isEqualTo('\'');
assertThat(omega.asChar()).isEqualTo('\u03a9');
assertThat(unicode.asChar()).isEqualTo('\uFFFF');
assertThat(ascii.asChar()).isEqualTo('\177');
assertThat(trademark.asChar()).isEqualTo('™');
}
@Test
void lowerAndUpperBoundDoublesAreConverted() {
DoubleLiteralExpr posFloat = parseExpression("3.4028235e38f");
DoubleLiteralExpr negFloat = parseExpression("1.40e-45f");
DoubleLiteralExpr posDouble = parseExpression("1.7976931348623157e308");
DoubleLiteralExpr negDouble = parseExpression("4.9e-324");
DoubleLiteralExpr posHexFloat = parseExpression("0x1.fffffffffffffp1023");
DoubleLiteralExpr negHexFloat = parseExpression("0x0.0000000000001P-1022");
assertThat(posFloat.asDouble()).isCloseTo(3.4028235e38f, Percentage.withPercentage(1));
assertThat(negFloat.asDouble()).isCloseTo(1.40e-45f, Percentage.withPercentage(1));
assertThat(posDouble.asDouble()).isEqualTo(1.7976931348623157e308);
assertThat(negDouble.asDouble()).isEqualTo(4.9e-324);
assertThat(posHexFloat.asDouble()).isEqualTo(0x1.fffffffffffffp1023);
assertThat(negHexFloat.asDouble()).isEqualTo(0x0.0000000000001P-1022);
}
@Test
void specialCharactersInStringsAreEscaped() {
assertThat(new StringLiteralExpr("\n").getValue()).isEqualTo("\\n");
assertThat(new StringLiteralExpr("\r").getValue()).isEqualTo("\\r");
assertThat(new StringLiteralExpr("").setEscapedValue("\n").getValue()).isEqualTo("\\n");
assertThat(new StringLiteralExpr("").setEscapedValue("\r").getValue()).isEqualTo("\\r");
assertThat(new StringLiteralExpr("").setEscapedValue("\n").asString()).isEqualTo("\n");
assertThat(new StringLiteralExpr("").setEscapedValue("\r").asString()).isEqualTo("\r");
assertThat(new StringLiteralExpr("Hello\nWorld\rHello\"World\'").asString())
.isEqualTo("Hello\nWorld\rHello\"World\'");
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static java.util.Optional.empty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class MethodCallExprTest {
@Test
void replaceLambdaIssue1290() {
MethodCallExpr methodCallExpr =
parseExpression("callSomeFun(r -> r instanceof SomeType)").asMethodCallExpr();
LambdaExpr lambdaExpr = methodCallExpr.getArgument(0).asLambdaExpr();
MethodCallExpr lambdaWrapper = new MethodCallExpr("lambdaWrapper");
lambdaExpr.replace(lambdaWrapper);
assertEquals(2, methodCallExpr.getChildNodes().size());
assertEquals(empty(), lambdaExpr.getParentNode());
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.TestUtils.assertExpressionValid;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
class MethodReferenceExprTest {
@Test
void methodReferenceExprHasAlwaysAScope() {
assertNotNull(new MethodReferenceExpr().getScope());
}
@Test
void reference1() {
assertExpressionValid("String::length");
}
@Test
void reference2() {
assertExpressionValid("System::currentTimeMillis // static method");
}
@Test
void reference3() {
assertExpressionValid("List<String>::size // explicit type arguments for generic type");
}
@Test
void reference4() {
assertExpressionValid("List::size // inferred type arguments for generic type");
}
@Test
void reference5() {
assertExpressionValid("int[]::clone");
}
@Test
void reference6() {
assertExpressionValid("T::tvarMember");
}
@Test
void reference7() {
assertExpressionValid("System.out::println");
}
@Test
void reference8() {
assertExpressionValid("\"abc\"::length");
}
@Test
void reference9() {
assertExpressionValid("foo[x]::bar");
}
@Test
void reference10() {
assertExpressionValid("(test ? list.replaceAll(String::trim) : list) :: iterator");
}
@Test
void reference10Annotated1() {
assertExpressionValid("(test ? list.replaceAll(@A String::trim) : list) :: iterator");
}
@Test
void reference11() {
assertExpressionValid("String::valueOf // overload resolution needed");
}
@Test
void reference12() {
assertExpressionValid("Arrays::sort // type arguments inferred from context");
}
@Test
void reference13() {
assertExpressionValid("Arrays::<String>sort // explicit type arguments");
}
@Test
void reference14() {
assertExpressionValid("ArrayList<String>::new // constructor for parameterized type");
}
@Test
void reference15() {
assertExpressionValid("ArrayList::new // inferred type arguments");
}
@Test
void reference16() {
assertExpressionValid("Foo::<Integer>new // explicit type arguments");
}
@Test
void reference17() {
assertExpressionValid("Bar<String>::<Integer>new // generic class, generic constructor");
}
@Test
void reference18() {
assertExpressionValid("Outer.Inner::new // inner class constructor");
}
@Test
void reference19() {
assertExpressionValid("int[]::new // array creation");
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.*;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ParseProblemException;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.printer.ConcreteSyntaxModel;
import com.github.javaparser.utils.LineSeparator;
import org.junit.jupiter.api.Test;
class NameTest {
@Test
void outerNameExprIsTheRightMostIdentifier() {
Name name = parseName("a.b.c");
assertEquals("c", name.getIdentifier());
}
@Test
void parsingAndUnparsingWorks() {
Name name = parseName("a.b.c");
assertEquals("a.b.c", name.asString());
}
@Test
void parsingEmptyNameThrowsException() {
assertThrows(ParseProblemException.class, () -> parseName(""));
}
@Test
void importName() {
ImportDeclaration importDeclaration = parseImport("import java.util.List;");
assertEquals("import java.util.List;" + LineSeparator.SYSTEM, importDeclaration.toString());
assertEquals("import java.util.List;", ConcreteSyntaxModel.genericPrettyPrint(importDeclaration));
}
@Test
void packageName() {
CompilationUnit cu = parse("package p1.p2;");
assertEquals("package p1.p2;" + LineSeparator.SYSTEM + LineSeparator.SYSTEM, cu.toString());
assertEquals(
"package p1.p2;" + LineSeparator.SYSTEM + LineSeparator.SYSTEM,
ConcreteSyntaxModel.genericPrettyPrint(cu));
}
@Test
void isInternalNegative() {
Name name = parseName("a.b.c");
assertFalse(name.isInternal());
}
@Test
void isInternalPositive() {
Name name = parseName("a.b.c");
assertTrue(name.getQualifier().get().isInternal());
assertTrue(name.getQualifier().get().getQualifier().get().isInternal());
}
@Test
void isTopLevelNegative() {
Name name = parseName("a.b.c");
assertFalse(name.getQualifier().get().isTopLevel());
assertFalse(name.getQualifier().get().getQualifier().get().isTopLevel());
}
@Test
void isTopLevelPositive() {
Name name = parseName("a.b.c");
assertTrue(name.isTopLevel());
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.utils.TestParser;
import org.junit.jupiter.api.Test;
class ObjectCreationExprTest {
@Test
void aaa() {
Expression e = TestParser.parseExpression("new @Test N()");
assertEquals("new @Test N()", e.toString());
}
}

View File

@@ -0,0 +1,122 @@
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.NodeList;
import java.util.function.Consumer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* This class exists to test the generated methods for the various Pattern expression
* types. Actual pattern functionality is tested in the context of instanceof expressions
* or switch entries.
*/
public class PatternExprTest {
private static final ParserConfiguration.LanguageLevel storedLanguageLevel =
StaticJavaParser.getParserConfiguration().getLanguageLevel();
@BeforeAll
public static void setLanguageLevel() {
StaticJavaParser.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.BLEEDING_EDGE);
}
@AfterAll
public static void resetLanguageLevel() {
StaticJavaParser.getParserConfiguration().setLanguageLevel(storedLanguageLevel);
}
class TestConsumer<T> implements Consumer<T> {
public boolean isConsumed = false;
@Override
public void accept(T t) {
isConsumed = true;
}
}
@Test
public void patternGeneratedMethodsShouldWork() {
Expression expr = parseExpression("x instanceof Foo f");
assertTrue(expr.isInstanceOfExpr());
InstanceOfExpr instanceOfExpr = expr.asInstanceOfExpr();
assertTrue(instanceOfExpr.getPattern().isPresent());
PatternExpr pattern = instanceOfExpr.getPattern().get();
assertTrue(pattern.isPatternExpr());
assertTrue(pattern.isTypePatternExpr());
assertInstanceOf(PatternExpr.class, pattern.asPatternExpr());
assertInstanceOf(TypePatternExpr.class, pattern.asTypePatternExpr());
assertFalse(instanceOfExpr.isPatternExpr());
assertFalse(instanceOfExpr.isTypePatternExpr());
assertThrows(IllegalStateException.class, () -> instanceOfExpr.asPatternExpr());
assertThrows(IllegalStateException.class, () -> instanceOfExpr.asTypePatternExpr());
TestConsumer<PatternExpr> validPattern = new TestConsumer<>();
pattern.ifPatternExpr(validPattern);
assertTrue(validPattern.isConsumed);
TestConsumer<TypePatternExpr> validTypePattern = new TestConsumer<>();
pattern.ifTypePatternExpr(validTypePattern);
assertTrue(validTypePattern.isConsumed);
TestConsumer<PatternExpr> invalidPattern = new TestConsumer<>();
instanceOfExpr.ifPatternExpr(invalidPattern);
assertFalse(invalidPattern.isConsumed);
TestConsumer<TypePatternExpr> invalidTypePattern = new TestConsumer<>();
instanceOfExpr.ifTypePatternExpr(invalidTypePattern);
assertFalse(invalidTypePattern.isConsumed);
}
@Test
public void recordPatternGeneratedMethodsShouldWork() {
Expression expr = parseExpression("x instanceof Foo(Bar b)");
assertTrue(expr.isInstanceOfExpr());
InstanceOfExpr instanceOfExpr = expr.asInstanceOfExpr();
assertTrue(instanceOfExpr.getPattern().isPresent());
PatternExpr pattern = instanceOfExpr.getPattern().get();
assertTrue(pattern.isRecordPatternExpr());
assertTrue(pattern.toRecordPatternExpr().isPresent());
RecordPatternExpr recordPattern = pattern.asRecordPatternExpr();
NodeList<Modifier> newModifiers = new NodeList<>();
Modifier newModifier = new Modifier();
newModifiers.add(newModifier);
recordPattern.setModifiers(newModifiers);
assertEquals(newModifiers, recordPattern.getModifiers());
recordPattern.replace(newModifier, newModifier);
assertEquals(newModifiers, recordPattern.getModifiers());
recordPattern.remove(newModifier);
assertTrue(recordPattern.getModifiers().isEmpty());
TestConsumer<RecordPatternExpr> validPattern = new TestConsumer<>();
pattern.ifRecordPatternExpr(validPattern);
assertTrue(validPattern.isConsumed);
NodeList<PatternExpr> patternList = recordPattern.getPatternList();
assertTrue(patternList.isNonEmpty());
recordPattern.replace(patternList.get(0), patternList.get(0));
assertTrue(patternList.isNonEmpty());
RecordPatternExpr newRecordPattern = recordPattern.clone();
assertEquals(recordPattern.getTypeAsString(), newRecordPattern.getTypeAsString());
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseSimpleName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class SimpleNameTest {
@Test
void defaultConstructorSetsIdentifierToEmpty() {
assertEquals("empty", new SimpleName().getIdentifier());
}
@Test
void identifierMustNotBeEmpty() {
assertThrows(AssertionError.class, () -> new SimpleName(""));
}
@Test
void identifierMustNotBeNull() {
assertThrows(AssertionError.class, () -> new SimpleName(null));
}
@Test
void unicodeEscapesArePreservedInIdentifiers() {
SimpleName name = parseSimpleName("xxx\\u2122xxx");
assertEquals("xxx\\u2122xxx", name.asString());
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class StringLiteralExprTest {
@Test
void unicodeEscapesArePreservedInStrings() {
StringLiteralExpr omega = parseExpression("\"xxx\\u03a9xxx\"");
assertEquals("xxx\\u03a9xxx", omega.getValue());
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.javaparser.ParseProblemException;
import org.junit.jupiter.api.Test;
class SuperExprTest {
@Test
void justSuper() {
assertThrows(ParseProblemException.class, () -> parseExpression("super"));
}
@Test
void singleScopeSuper() {
Expression expr = parseExpression("A.super");
Name className = expr.asSuperExpr().getTypeName().get();
assertEquals("A", className.asString());
}
@Test
void multiScopeSuper() {
Expression expr = parseExpression("a.B.super");
Name className = expr.asSuperExpr().getTypeName().get();
assertEquals("a.B", className.asString());
}
}

View File

@@ -0,0 +1,483 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.ast.stmt.SwitchEntry.Type.*;
import static com.github.javaparser.utils.TestParser.*;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.Range;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.stmt.SwitchEntry;
import com.github.javaparser.ast.stmt.SwitchStmt;
import com.github.javaparser.resolution.Navigator;
import org.junit.jupiter.api.Test;
class SwitchExprTest {
@Test
void jep325Example2() {
NodeList<Expression> entry2labels = parseStatement(
"int numLetters = switch (day) {\n" + " case MONDAY, FRIDAY, SUNDAY -> 6;\n"
+ " case TUESDAY -> 7;\n"
+ " case THURSDAY, SATURDAY -> 8;\n"
+ " case WEDNESDAY -> 9;\n"
+ "};")
.findAll(SwitchEntry.class)
.get(0)
.getLabels();
assertEquals(3, entry2labels.size());
assertEquals("MONDAY", entry2labels.get(0).toString());
assertEquals("FRIDAY", entry2labels.get(1).toString());
assertEquals("SUNDAY", entry2labels.get(2).toString());
}
@Test
void funkyExpressions() {
parseStatement("int numLetters = switch (day) {\n" + " case 1+1, 2+2 -> 6;\n"
+ " case \"Henk\"-> 7;\n"
+ " case ((3)+3)+3 -> 8;\n"
+ "};");
}
@Test
void jep325Example3() {
parseBodyDeclaration("static void howMany(int k) {\n" + " switch (k) {\n"
+ " case 1 -> System.out.println(\"one\");\n"
+ " case 2 -> System.out.println(\"two\");\n"
+ " case 3 -> System.out.println(\"many\");\n"
+ " }\n"
+ "}");
}
@Test
void aThrowStatement() {
SwitchExpr switchExpr = parseExpression(
"switch (k) {\n" + " case 1 -> throw new Exception(\"one\");\n" + " }")
.findFirst(SwitchExpr.class)
.get();
assertEquals(THROWS_STATEMENT, switchExpr.getEntry(0).getType());
}
@Test
void jep325Example4() {
SwitchExpr switchExpr = parseStatement("T result = switch (arg) {\n" + " case L1 -> e1;\n"
+ " case L2 -> e2;\n"
+ " default -> e3;\n"
+ "};")
.findFirst(SwitchExpr.class)
.get();
assertEquals(EXPRESSION, switchExpr.getEntry(0).getType());
}
@Test
void jep325Example5() {
SwitchExpr switchExpr = parseStatement("int j = switch (day) {\n" + " case MONDAY -> 0;\n"
+ " case TUESDAY -> 1;\n"
+ " default -> {\n"
+ " int k = day.toString().length();\n"
+ " int result = f(k);\n"
+ " yield result;\n"
+ " }\n"
+ "};")
.findFirst(SwitchExpr.class)
.get();
assertEquals(BLOCK, switchExpr.getEntry(2).getType());
assertEquals(
BlockStmt.class, switchExpr.getEntry(2).getStatements().get(0).getClass());
}
@Test
void jep325Example6() {
parseStatement("int result = switch (s) {\n" + " case \"Foo\": \n"
+ " yield 1;\n"
+ " case \"Bar\":\n"
+ " yield 2;\n"
+ " default:\n"
+ " System.out.println(\"Neither Foo nor Bar, hmmm...\");\n"
+ " yield 0;\n"
+ "};");
}
@Test
void yieldMethodCall() {
parseStatement("int randomNumber = switch (5) {\n" + " default -> {\n"
+ " yield a.randomNumberGenerator();\n"
+ " }\n"
+ " case 1 -> {\n"
+ " yield method();\n"
+ " }\n"
+ " case 2 -> {\n"
+ " yield method(args);\n"
+ " }\n"
+ " case 3 -> {\n"
+ " yield this.method();\n"
+ " }\n"
+ " case 4 -> {\n"
+ " yield Clazz.this.method(args);\n"
+ " }\n"
+ "};");
}
@Test
void yieldExpression1() {
parseStatement("int randomNumber = switch (5) {\n" + " default -> {\n"
+ " yield 1 * 1;\n"
+ " }\n"
+ " case 1 -> {\n"
+ " yield (5 + 5);\n"
+ " }\n"
+ " case 2 -> {\n"
+ " yield (5 + 5) * 3;\n"
+ " }\n"
+ "};");
}
@Test
void yieldExpression2() {
parseStatement("boolean b = switch (5) {\n" + " case 3 -> {\n"
+ " yield true || false;\n"
+ " }\n"
+ " default -> {\n"
+ " yield !true;\n"
+ " }\n"
+ "};");
}
@Test
void yieldAssignment() {
parseStatement("int randomNumber = switch (5) {\n" + " default -> {\n"
+ " int x;\n"
+ " yield (x = 5);\n"
+ " }\n"
+ " case 'a' -> {\n"
+ " int x;\n"
+ " yield x = 3;\n"
+ " }\n"
+ "};");
}
@Test
void yieldConditional() {
parseStatement("int randomNumber = switch (5) {\n" + " default -> {\n"
+ " yield x ? 1 : 2;\n"
+ " }\n"
+ " case 1 -> {\n"
+ " yield (x ? 1 : 2);\n"
+ " }\n"
+ " case 2 -> {\n"
+ " yield x < 0 ? 0 : x > y ? y : x;\n"
+ " }\n"
+ "};");
}
@Test
void yieldYield() {
parseStatement("yield = switch (yield) {\n" + " default -> {\n"
+ " yield yield;\n"
+ " }\n"
+ " case yield -> {\n"
+ " yield Clazz.yield();\n"
+ " }\n"
+ " case enumValue2 -> {\n"
+ " yield yield = yield;\n"
+ " }\n"
+ " case enumValue3 -> {\n"
+ " yield yield == yield ? yield : yield;\n"
+ " }\n"
+ "};");
}
@Test
void switchPattern() {
SwitchStmt stmt = parseStatement("switch (value) {\n" + " case Box b -> System.out.println(b);\n" + "}")
.asSwitchStmt();
assertEquals(1, stmt.getEntries().size());
SwitchEntry entry = stmt.getEntry(0);
assertFalse(entry.getGuard().isPresent());
assertEquals(1, entry.getLabels().size());
TypePatternExpr label = entry.getLabels().get(0).asTypePatternExpr();
assertEquals("b", label.getNameAsString());
assertEquals("Box", label.getTypeAsString());
}
@Test
void switchPatternWithGuard() {
SwitchExpr expr = parseExpression(
"switch (value) {\n" + " case Box b when b.nonEmpty() -> b.get() + 12;\n" + "}")
.asSwitchExpr();
assertEquals(1, expr.getEntries().size());
SwitchEntry entry = expr.getEntry(0);
assertTrue(entry.getGuard().isPresent());
Expression guard = entry.getGuard().get();
assertInstanceOf(MethodCallExpr.class, guard);
assertEquals(1, entry.getLabels().size());
TypePatternExpr label = entry.getLabels().get(0).asTypePatternExpr();
assertEquals("b", label.getNameAsString());
assertEquals("Box", label.getTypeAsString());
assertEquals("b.get() + 12;", entry.getStatements().get(0).toString());
}
@Test
void testRemoveGuard() {
SwitchExpr expr = parseExpression("switch (value) {\n" + " case Box b when b.nonEmpty() -> {}\n" + "}")
.asSwitchExpr();
SwitchEntry entry = expr.getEntry(0);
assertTrue(entry.getGuard().isPresent());
entry.removeGuard();
assertFalse(entry.getGuard().isPresent());
assertFalse(Navigator.findNameExpression(entry, "b").isPresent());
}
@Test
void testRemoveWithGuard() {
SwitchExpr expr = parseExpression("switch (value) {\n" + " case Box b when b.nonEmpty() -> {}\n" + "}")
.asSwitchExpr();
SwitchEntry entry = expr.getEntry(0);
assertTrue(entry.getGuard().isPresent());
entry.remove(entry.getGuard().get());
assertFalse(entry.getGuard().isPresent());
assertFalse(Navigator.findNameExpression(entry, "b").isPresent());
}
@Test
void testRecordPattern() {
SwitchExpr expr = parseExpression(
"switch (value) {\n" + " case TwoBox (String s, Box(Integer i)) -> {}\n" + "}")
.asSwitchExpr();
SwitchEntry entry = expr.getEntry(0);
assertTrue(entry.getLabels().get(0).isRecordPatternExpr());
RecordPatternExpr recordPattern = entry.getLabels().get(0).asRecordPatternExpr();
assertEquals("TwoBox", recordPattern.getTypeAsString());
assertEquals(2, recordPattern.getPatternList().size());
assertTrue(recordPattern.getPatternList().get(0).isTypePatternExpr());
TypePatternExpr stringPattern = recordPattern.getPatternList().get(0).asTypePatternExpr();
assertEquals("String", stringPattern.getTypeAsString());
assertEquals("s", stringPattern.getNameAsString());
assertTrue(recordPattern.getPatternList().get(1).isRecordPatternExpr());
RecordPatternExpr boxPattern = recordPattern.getPatternList().get(1).asRecordPatternExpr();
assertEquals("Box", boxPattern.getTypeAsString());
assertEquals(1, boxPattern.getPatternList().size());
assertTrue(boxPattern.getPatternList().get(0).isTypePatternExpr());
TypePatternExpr integerPattern = boxPattern.getPatternList().get(0).asTypePatternExpr();
assertEquals("Integer", integerPattern.getTypeAsString());
assertEquals("i", integerPattern.getNameAsString());
}
/**
* Credit to @Kimmmey in https://github.com/javaparser/javaparser/issues/4440 for the
* example code.
*/
@Test
void testSwitchExprUnaryMinus() {
Statement stmt =
parseStatement("int i = switch (x) {\n" + " case 0 -> 0;\n" + " default -> -1;\n" + "};");
VariableDeclarator declarator =
(VariableDeclarator) stmt.getChildNodes().get(0).getChildNodes().get(0);
SwitchExpr switchExpr = declarator.getInitializer().get().asSwitchExpr();
assertEquals("0", switchExpr.getEntry(0).getLabels().get(0).toString());
assertEquals("0;", switchExpr.getEntry(0).getStatements().get(0).toString());
assertTrue(switchExpr.getEntry(1).getLabels().isEmpty());
assertTrue(switchExpr.getEntry(1).isDefault());
assertEquals("-1;", switchExpr.getEntry(1).getStatements().get(0).toString());
}
/**
* Credit to @Kimmmey in https://github.com/javaparser/javaparser/issues/4440 for the
* example code.
*/
@Test
void testSwitchExprUnaryNot() {
Statement stmt = parseStatement(
"boolean b = switch (x) {\n" + " case 0 -> true;\n" + " default -> !false;\n" + "};");
VariableDeclarator declarator =
(VariableDeclarator) stmt.getChildNodes().get(0).getChildNodes().get(0);
SwitchExpr switchExpr = declarator.getInitializer().get().asSwitchExpr();
assertEquals("0", switchExpr.getEntry(0).getLabels().get(0).toString());
assertEquals("true;", switchExpr.getEntry(0).getStatements().get(0).toString());
assertTrue(switchExpr.getEntry(1).getLabels().isEmpty());
assertTrue(switchExpr.getEntry(1).isDefault());
assertEquals("!false;", switchExpr.getEntry(1).getStatements().get(0).toString());
}
/**
* Credit to @Kimmmey in https://github.com/javaparser/javaparser/issues/4440 for the
* example code.
*/
@Test
void testSwitchExprWithBinaryExpr() {
Statement stmt = parseStatement("int i = switch (x) {\n" + " case 1 -> 1;\n"
+ " case 2, 3 -> 1 + 2;\n"
+ " default -> 1;\n"
+ "};");
VariableDeclarator declarator =
(VariableDeclarator) stmt.getChildNodes().get(0).getChildNodes().get(0);
SwitchExpr switchExpr = declarator.getInitializer().get().asSwitchExpr();
assertEquals("1", switchExpr.getEntry(0).getLabels().get(0).toString());
assertEquals("1;", switchExpr.getEntry(0).getStatements().get(0).toString());
assertEquals("2", switchExpr.getEntry(1).getLabels().get(0).toString());
assertEquals("3", switchExpr.getEntry(1).getLabels().get(1).toString());
assertEquals("1 + 2;", switchExpr.getEntry(1).getStatements().get(0).toString());
assertTrue(switchExpr.getEntry(2).getLabels().isEmpty());
assertTrue(switchExpr.getEntry(2).isDefault());
assertEquals("1;", switchExpr.getEntry(2).getStatements().get(0).toString());
}
@Test
void testSwitchExprWithAssignment() {
Statement stmt = parseStatement("{\n" + " int z;\n"
+ " int i = switch (x) {\n"
+ " case 1 -> z = 1;\n"
+ " default -> 1;\n"
+ " };\n"
+ "}");
VariableDeclarator declarator = (VariableDeclarator) stmt.getChildNodes()
.get(1)
.getChildNodes()
.get(0)
.getChildNodes()
.get(0);
SwitchExpr switchExpr = declarator.getInitializer().get().asSwitchExpr();
assertEquals("1", switchExpr.getEntry(0).getLabels().get(0).toString());
assertEquals("z = 1;", switchExpr.getEntry(0).getStatements().get(0).toString());
assertTrue(switchExpr.getEntry(1).getLabels().isEmpty());
assertTrue(switchExpr.getEntry(1).isDefault());
assertEquals("1;", switchExpr.getEntry(1).getStatements().get(0).toString());
}
@Test
void issue4455Test() {
SwitchExpr switchExpr = parseExpression(
"switch (column) {\n" + " case CustomDeployTableModel.ARTIFACT_NAME -> {}\n" + "}")
.asSwitchExpr();
assertEquals(Node.Parsedness.PARSED, switchExpr.getParsed());
SwitchEntry entry = switchExpr.getEntry(0);
Expression switchLabel = entry.getLabels().get(0);
assertEquals("CustomDeployTableModel.ARTIFACT_NAME", switchLabel.toString());
assertTrue(switchLabel.isFieldAccessExpr());
assertTrue(switchLabel.getRange().isPresent());
Range switchLabelRange = switchLabel.getRange().get();
assertEquals(2, switchLabelRange.begin.line);
assertEquals(10, switchLabelRange.begin.column);
assertEquals(2, switchLabelRange.end.line);
assertEquals(45, switchLabelRange.end.column);
}
@Test
void switchExprWithoutTokensStored() {
ParserConfiguration config = new ParserConfiguration();
config.setStoreTokens(false);
config.setLanguageLevel(ParserConfiguration.LanguageLevel.BLEEDING_EDGE);
JavaParser parser = new JavaParser(config);
ParseResult<SwitchExpr> result =
parser.parseExpression("switch (o) {\n" + " case Foo f -> f.get();\n" + "}");
assertTrue(result.isSuccessful());
assertTrue(result.getProblems().isEmpty());
SwitchEntry entry = result.getResult().get().getEntry(0);
assertEquals("Foo f", entry.getLabels().get(0).toString());
assertEquals("f.get();", entry.getStatements().get(0).toString());
}
@Test
void testRecordPatternWithPrimitiveType() {
SwitchExpr switchExpr =
parseExpression("switch (foo) { case Foo(int x) -> sink(x); }").asSwitchExpr();
assertEquals(Node.Parsedness.PARSED, switchExpr.getParsed());
SwitchEntry entry = switchExpr.getEntry(0);
Expression switchLabel = entry.getLabels().get(0);
assertEquals("Foo(int x)", switchLabel.toString());
assertTrue(switchLabel.isRecordPatternExpr());
RecordPatternExpr recordPattern = switchLabel.asRecordPatternExpr();
assertEquals("Foo", recordPattern.getType().toString());
assertEquals(1, recordPattern.getPatternList().size());
assertTrue(recordPattern.getPatternList().get(0).isTypePatternExpr());
TypePatternExpr innerType = recordPattern.getPatternList().get(0).asTypePatternExpr();
assertTrue(innerType.getType().isPrimitiveType());
}
}

View File

@@ -0,0 +1,200 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.TestParser.parseStatement;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class TextBlockLiteralExprTest {
@Test
void htmlExample() {
TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + " <html>\n"
+ " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ " </html>\n"
+ " \"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals(
" <html>\n" + " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ " </html>\n"
+ " ",
textBlock.getValue());
assertEquals(
asList("<html>", " <body>", " <p>Hello, world</p>", " </body>", "</html>", ""),
textBlock.stripIndentOfLines().collect(toList()));
assertEquals(
"<html>\n" + " <body>\n" + " <p>Hello, world</p>\n" + " </body>\n" + "</html>\n",
textBlock.stripIndent());
assertEquals(
"<html>\n" + " <body>\n" + " <p>Hello, world</p>\n" + " </body>\n" + "</html>\n",
textBlock.translateEscapes());
}
@Test
void htmlExampleWithEndAllToTheLeft() {
TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + " <html>\n"
+ " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ " </html>\n"
+ "\"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals(
" <html>\n" + " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ " </html>\n",
textBlock.translateEscapes());
}
@Test
void htmlExampleWithEndALittleToTheLeft() {
TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + " <html>\n"
+ " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ " </html>\n"
+ " \"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals(
" <html>\n" + " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ " </html>\n",
textBlock.translateEscapes());
}
@Test
void htmlExampleWithEndALittleToTheRight() {
TextBlockLiteralExpr textBlock = parseStatement("String html = \"\"\"\n" + " <html>\n"
+ " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ " </html>\n"
+ " \"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals(
"<html>\n" + " <body>\n" + " <p>Hello, world</p>\n" + " </body>\n" + "</html>\n",
textBlock.translateEscapes());
}
@Test
void itIsLegalToUseDoubleQuoteFreelyInsideATextBlock() {
parseStatement("String story = \"\"\"\n" + " \"When I use a word,\" Humpty Dumpty said,\n"
+ " in rather a scornful tone, \"it means just what I\n"
+ " choose it to mean - neither more nor less.\"\n"
+ " \"The question is,\" said Alice, \"whether you\n"
+ " can make words mean so many different things.\"\n"
+ " \"The question is,\" said Humpty Dumpty,\n"
+ " \"which is to be master - that's all.\"\n"
+ " \"\"\";");
}
@Test
void sequencesOfThreeDoubleQuotesNeedAtLeastOneEscaped() {
TextBlockLiteralExpr textBlock = parseStatement("String code = \n" + " \"\"\"\n"
+ " String text = \\\"\"\"\n"
+ " A text block inside a text block\n"
+ " \\\"\"\";\n"
+ " \"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals(
"String text = \"\"\"\n" + " A text block inside a text block\n" + "\"\"\";\n",
textBlock.translateEscapes());
}
@Test
void concatenatingTextBlocks() {
parseStatement("String code = \"public void print(Object o) {\" +\n" + " \"\"\"\n"
+ " System.out.println(Objects.toString(o));\n"
+ " }\n"
+ " \"\"\";");
}
@Test
void forceTrailingWhitespace() {
TextBlockLiteralExpr textBlock = parseStatement("String code = \"\"\"\n" + "The quick brown fox\\040\\040\n"
+ "jumps over the lazy dog\n"
+ "\"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals("The quick brown fox \n" + "jumps over the lazy dog\n", textBlock.translateEscapes());
}
@Test
void escapeLineTerminator() {
TextBlockLiteralExpr textBlock = parseStatement("String text = \"\"\"\n"
+ " Lorem ipsum dolor sit amet, consectetur adipiscing \\\n"
+ " elit, sed do eiusmod tempor incididunt ut labore \\\n"
+ " et dolore magna aliqua.\\\n"
+ " \"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals(
"Lorem ipsum dolor sit amet, consectetur adipiscing "
+ "elit, sed do eiusmod tempor incididunt ut labore "
+ "et dolore magna aliqua.",
textBlock.translateEscapes());
}
@Test
void escapeSpace() {
TextBlockLiteralExpr textBlock = parseStatement("String colors = \"\"\"\n" + " red \\s\n"
+ " green\\s\n"
+ " blue \\s\n"
+ " \"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals("red \n" + "green \n" + "blue \n", textBlock.translateEscapes());
}
@Test
void whiteSpaceLineShorterThanMiniumCommonPrefix() {
TextBlockLiteralExpr textBlock = parseStatement("String text = \"\"\" \n" + " Hello\n" + " World\"\"\";")
.findFirst(TextBlockLiteralExpr.class)
.get();
assertEquals("\nHello\n" + "World", textBlock.translateEscapes());
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import org.junit.jupiter.api.Test;
class ThisExprTest {
@Test
void justThis() {
Expression expr = parseExpression("this");
assertTrue(expr.isThisExpr());
}
@Test
void justThisName() {
JavaParser javaParser = new JavaParser(new ParserConfiguration().setStoreTokens(false));
ParseResult<Expression> parseResult = javaParser.parseExpression("this.c");
FieldAccessExpr fieldAccess = parseResult.getResult().get().asFieldAccessExpr();
assertEquals("c", fieldAccess.getName().asString());
}
@Test
void singleScopeThis() {
Expression expr = parseExpression("A.this");
Name className = expr.asThisExpr().getTypeName().get();
assertEquals("A", className.asString());
}
@Test
void singleScopeThisName() {
JavaParser javaParser = new JavaParser(new ParserConfiguration().setStoreTokens(false));
ParseResult<Expression> parseResult = javaParser.parseExpression("A.this.c");
FieldAccessExpr fieldAccess = parseResult.getResult().get().asFieldAccessExpr();
assertEquals("c", fieldAccess.getName().asString());
}
@Test
void multiScopeThis() {
Expression expr = parseExpression("a.B.this");
Name className = expr.asThisExpr().getTypeName().get();
assertEquals("a.B", className.asString());
}
@Test
void multiScopeThisName() {
JavaParser javaParser = new JavaParser(new ParserConfiguration().setStoreTokens(false));
ParseResult<Expression> parseResult = javaParser.parseExpression("a.B.this.c");
FieldAccessExpr fieldAccess = parseResult.getResult().get().asFieldAccessExpr();
assertEquals("c", fieldAccess.getName().asString());
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.imports;
import static com.github.javaparser.StaticJavaParser.parseImport;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.ImportDeclaration;
import org.junit.jupiter.api.Test;
class ImportDeclarationTest {
@Test
void singleTypeImportDeclaration() {
ImportDeclaration i = parseImport("import a.b.c.X;");
assertEquals("a.b.c.X", i.getNameAsString());
}
@Test
void typeImportOnDemandDeclaration() {
ImportDeclaration i = parseImport("import a.b.c.D.*;");
assertEquals("a.b.c.D", i.getName().toString());
assertEquals("D", i.getName().getIdentifier());
}
@Test
void singleStaticImportDeclaration() {
ImportDeclaration i = parseImport("import static a.b.c.X.def;");
assertEquals("a.b.c.X", i.getName().getQualifier().get().asString());
assertEquals("def", i.getName().getIdentifier());
}
@Test
void staticImportOnDemandDeclaration() {
ImportDeclaration i = parseImport("import static a.b.c.X.*;");
assertEquals("a.b.c.X", i.getNameAsString());
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.nodeTypes;
import static com.github.javaparser.ast.expr.Expression.EXCLUDE_ENCLOSED_EXPR;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest;
import org.junit.jupiter.api.Test;
class NodeWithArgumentsTest extends AbstractLexicalPreservingTest {
@Test
void testGetArgumentPosition() {
considerCode("" + "class Foo {\n"
+ " Map<Integer,String> map = new HashMap<>();\n"
+ " public String bar(int i) {\n"
+ " return map.put(((i)),((\"baz\")));\n"
+ " } \n"
+ "}");
MethodCallExpr mce = cu.findFirst(MethodCallExpr.class).get();
Expression arg0 = mce.getArgument(0);
Expression arg1 = mce.getArgument(1);
Expression innerExpr0 =
arg0.asEnclosedExpr().getInner().asEnclosedExpr().getInner();
Expression innerExpr1 =
arg1.asEnclosedExpr().getInner().asEnclosedExpr().getInner();
assertEquals(0, mce.getArgumentPosition(arg0)); // with no conversion
assertEquals(
0,
mce.getArgumentPosition(innerExpr0, EXCLUDE_ENCLOSED_EXPR)); // with a conversion skipping EnclosedExprs
assertEquals(1, mce.getArgumentPosition(arg1)); // with no conversion
assertEquals(
1,
mce.getArgumentPosition(innerExpr1, EXCLUDE_ENCLOSED_EXPR)); // with a conversion skipping EnclosedExprs
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.nodeTypes;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.stmt.ForStmt;
import com.github.javaparser.utils.TestParser;
import org.junit.jupiter.api.Test;
class NodeWithBodyTest {
@Test
void emptyStatementIsEmpty() {
ForStmt forStmt = TestParser.parseStatement("for(;;);").asForStmt();
assertTrue(forStmt.hasEmptyBody());
}
@Test
void emptyBlockIsEmpty() {
ForStmt forStmt = TestParser.parseStatement("for(;;){}").asForStmt();
assertTrue(forStmt.hasEmptyBody());
}
@Test
void simpleStatementIsNotEmpty() {
ForStmt forStmt = TestParser.parseStatement("for(;;)a=b;").asForStmt();
assertFalse(forStmt.hasEmptyBody());
}
@Test
void nonEmptyBlockIsNotEmpty() {
ForStmt forStmt = TestParser.parseStatement("for(;;){a=b;}").asForStmt();
assertFalse(forStmt.hasEmptyBody());
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.nodeTypes;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.comments.JavadocComment;
import com.github.javaparser.ast.comments.LineComment;
import org.junit.jupiter.api.Test;
class NodeWithJavadocTest {
@Test
void removeJavaDocNegativeCaseNoComment() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
assertFalse(decl.removeJavaDocComment());
}
@Test
void removeJavaDocNegativeCaseCommentNotJavaDoc() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.setComment(new LineComment("A comment"));
assertFalse(decl.removeJavaDocComment());
assertTrue(decl.getComment().isPresent());
}
@Test
void removeJavaDocPositiveCase() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.setComment(new JavadocComment("A comment"));
assertTrue(decl.removeJavaDocComment());
assertFalse(decl.getComment().isPresent());
}
@Test
void getJavadocOnMethodWithLineCommentShouldReturnEmptyOptional() {
MethodDeclaration method = new MethodDeclaration();
method.setLineComment("Lorem Ipsum.");
assertFalse(method.getJavadocComment().isPresent());
assertFalse(method.getJavadoc().isPresent());
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.nodeTypes;
import static com.github.javaparser.ast.Modifier.Keyword.*;
import static com.github.javaparser.ast.Modifier.createModifierList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.observer.AstObserverAdapter;
import com.github.javaparser.ast.observer.ObservableProperty;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Test;
class NodeWithModifiersTest {
@Test
void addModifierWorks() {
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.addModifier(PUBLIC);
assertEquals(createModifierList(PUBLIC), decl.getModifiers());
}
@Test
void addModifierTriggerNotification() {
List<String> changes = new LinkedList<>();
ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
decl.register(new AstObserverAdapter() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add("property " + property.name() + " is changed to " + newValue);
}
});
decl.addModifier(PUBLIC);
assertEquals(1, changes.size());
assertEquals("property MODIFIERS is changed to [public ]", changes.get(0));
}
@Test
void removeExistingModifier() {
NodeWithModifiers node = anythingWithModifiers(PUBLIC);
node.removeModifier(PUBLIC);
assertEquals(0, node.getModifiers().size());
}
@Test
void ignoreNotExistingModifiersOnRemove() {
NodeWithModifiers node = anythingWithModifiers(PUBLIC);
node.removeModifier(PRIVATE);
assertEquals(createModifierList(PUBLIC), node.getModifiers());
}
@Test
void keepModifiersThatShouldNotBeRemoved() {
NodeWithModifiers node = anythingWithModifiers(PUBLIC, STATIC, SYNCHRONIZED);
node.removeModifier(PUBLIC, PRIVATE, STATIC);
assertEquals(createModifierList(SYNCHRONIZED), node.getModifiers());
}
private NodeWithModifiers anythingWithModifiers(Modifier.Keyword... keywords) {
ClassOrInterfaceDeclaration foo = new ClassOrInterfaceDeclaration(new NodeList<>(), false, "Foo");
foo.addModifier(keywords);
return foo;
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.nodeTypes;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import org.junit.jupiter.api.Test;
class NodeWithOptionalScopeTest {
@Test
void commonExpressionWhichHaveInterfaceNodeWithOptionalScope() {
MethodCallExpr methodCallExpr = new MethodCallExpr(new NameExpr("A"), "call");
ObjectCreationExpr objectCreationExpr = new ObjectCreationExpr();
assertTrue(methodCallExpr.hasScope());
assertFalse(objectCreationExpr.hasScope());
}
@Test
void removeScope() {
MethodCallExpr methodCallExpr = new MethodCallExpr(new NameExpr("A"), "method");
methodCallExpr.removeScope();
assertFalse(methodCallExpr.hasScope());
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.nodeTypes;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static com.github.javaparser.utils.TestUtils.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.github.javaparser.ast.expr.FieldAccessExpr;
import com.github.javaparser.ast.expr.MethodCallExpr;
import org.junit.jupiter.api.Test;
class NodeWithTraversableScopeTest {
@Test
void traverse1() {
NodeWithTraversableScope expression = parseExpression("getAddress().name.startsWith(\"abc\")");
assertInstanceOf(MethodCallExpr.class, expression);
expression = (NodeWithTraversableScope) expression.traverseScope().get();
assertInstanceOf(FieldAccessExpr.class, expression);
expression = (NodeWithTraversableScope) expression.traverseScope().get();
assertInstanceOf(MethodCallExpr.class, expression);
assertFalse(expression.traverseScope().isPresent());
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.nodeTypes;
import static com.github.javaparser.StaticJavaParser.parseVariableDeclarationExpr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.type.PrimitiveType;
import org.junit.jupiter.api.Test;
class NodeWithVariablesTest {
@Test
void getCommonTypeWorksForNormalVariables() {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
assertEquals(PrimitiveType.intType(), declaration.getCommonType());
}
@Test
void getCommonTypeWorksForArrayTypes() {
parseVariableDeclarationExpr("int a[],b[]").getCommonType();
}
@Test
void getCommonTypeFailsOnArrayDifferences() {
assertThrows(AssertionError.class, () -> parseVariableDeclarationExpr("int a[],b[][]")
.getCommonType());
}
@Test
void getCommonTypeFailsOnDodgySetterUsage() {
assertThrows(AssertionError.class, () -> {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
declaration.getVariable(1).setType(String.class);
declaration.getCommonType();
});
}
@Test
void getCommonTypeFailsOnInvalidEmptyVariableList() {
assertThrows(AssertionError.class, () -> {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a");
declaration.getVariables().clear();
declaration.getCommonType();
});
}
@Test
void getElementTypeWorksForNormalVariables() {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
assertEquals(PrimitiveType.intType(), declaration.getElementType());
}
@Test
void getElementTypeWorksForArrayTypes() {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a[],b[]");
assertEquals(PrimitiveType.intType(), declaration.getElementType());
}
@Test
void getElementTypeIsOkayWithArrayDifferences() {
parseVariableDeclarationExpr("int a[],b[][]").getElementType();
}
@Test
void getElementTypeFailsOnDodgySetterUsage() {
assertThrows(AssertionError.class, () -> {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b");
declaration.getVariable(1).setType(String.class);
declaration.getElementType();
});
}
@Test
void getElementTypeFailsOnInvalidEmptyVariableList() {
assertThrows(AssertionError.class, () -> {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a");
declaration.getVariables().clear();
declaration.getElementType();
});
}
@Test
void setAllTypesWorks() {
VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int[] a[],b[][]");
declaration.setAllTypes(StaticJavaParser.parseType("Dog"));
assertEquals("Dog a, b", declaration.toString());
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.observer;
import static com.github.javaparser.StaticJavaParser.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.FieldDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class PropagatingAstObserverTest {
@Test
void verifyPropagation() {
String code = "class A { }";
CompilationUnit cu = parse(code);
List<String> changes = new ArrayList<>();
AstObserver observer = new PropagatingAstObserver() {
@Override
public void concretePropertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
changes.add(String.format(
"%s.%s changed from %s to %s",
observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue));
}
};
cu.registerForSubtree(observer);
assertEquals(Arrays.asList(), changes);
FieldDeclaration fieldDeclaration = cu.getClassByName("A").get().addField("String", "foo");
assertEquals(Arrays.asList(), changes);
assertTrue(fieldDeclaration.isRegistered(observer));
cu.getClassByName("A")
.get()
.getFieldByName("foo")
.get()
.getVariables()
.get(0)
.setName("Bar");
assertEquals(Arrays.asList("VariableDeclarator.name changed from foo to Bar"), changes);
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.stmt;
import static com.github.javaparser.utils.TestParser.parseStatement;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.expr.SimpleName;
import java.util.Optional;
import org.junit.jupiter.api.Test;
class BreakStmtTest {
@Test
void simpleBreak() {
BreakStmt statement = parseStatement("break;").asBreakStmt();
assertFalse(statement.getLabel().isPresent());
}
@Test
void breakWithLabel() {
BreakStmt statement = parseStatement("break hond;").asBreakStmt();
assertEquals("hond", statement.getLabel().get().asString());
}
@Test
void constructor_simpleBreakWithoutLabel() {
BreakStmt statement = new BreakStmt();
assertFalse(statement.getLabel().isPresent());
assertEquals("break;", statement.toString());
}
@Test
void constructor_simpleBreakWithLabel() {
BreakStmt statement = new BreakStmt("customLabel");
assertTrue(statement.getLabel().isPresent());
}
@Test
void constructor_simpleBreakWithSimpleNameLabel() {
SimpleName label = new SimpleName("customLabel");
BreakStmt statement = new BreakStmt(label);
assertTrue(statement.getLabel().isPresent());
assertEquals(label, statement.getLabel().get());
}
@Test
void removeLabel_shouldRemoveTheLabel() {
BreakStmt statement = new BreakStmt("customLabel");
assertTrue(statement.getLabel().isPresent());
statement.removeLabel();
assertFalse(statement.getLabel().isPresent());
}
@Test
void isBreakStmt_shouldBeTrue() {
assertTrue(new BreakStmt().isBreakStmt());
}
@Test
void asBreakStmt_shouldBeSame() {
BreakStmt breakStatement = new BreakStmt();
assertSame(breakStatement, breakStatement.asBreakStmt());
}
@Test
void toBreakStmt_shouldBePresentAndBeTheSame() {
BreakStmt breakStatement = new BreakStmt();
Optional<BreakStmt> optBreak = breakStatement.toBreakStmt();
assertTrue(optBreak.isPresent());
assertSame(breakStatement, optBreak.get());
}
@Test
void clone_shouldNotBeTheSameButShouldBeEquals() {
BreakStmt breakStatement = new BreakStmt();
BreakStmt clonedStatement = breakStatement.clone();
assertNotSame(breakStatement, clonedStatement);
assertEquals(breakStatement, clonedStatement);
}
@Test
void remove_whenLabelIsPassedAsArgumentItShouldBeRemoved() {
BreakStmt breakStatement = new BreakStmt("Label");
assertTrue(breakStatement.getLabel().isPresent());
SimpleName label = breakStatement.getLabel().get();
assertTrue(breakStatement.remove(label));
assertFalse(breakStatement.getLabel().isPresent());
}
@Test
void replace_testReplaceLabelWithNewOne() {
SimpleName originalLabel = new SimpleName("original");
SimpleName replacementLabel = new SimpleName("replacement");
BreakStmt breakStatement = new BreakStmt(originalLabel);
assertTrue(breakStatement.getLabel().isPresent());
assertSame(originalLabel, breakStatement.getLabel().get());
breakStatement.replace(originalLabel, replacementLabel);
assertTrue(breakStatement.getLabel().isPresent());
assertSame(replacementLabel, breakStatement.getLabel().get());
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.stmt;
import static com.github.javaparser.StaticJavaParser.parseStatement;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.PrimitiveType;
import org.junit.jupiter.api.Test;
class ForEachStmtTest {
@Test
void nonFinalPrimitive() {
ForEachStmt statement = parseStatement("for (int i : ints) {}").asForEachStmt();
assertFalse(statement.hasFinalVariable());
assertEquals(PrimitiveType.intType(), statement.getVariableDeclarator().getType());
assertEquals("i", statement.getVariableDeclarator().getName().getIdentifier());
}
@Test
void finalNonPrimitive() {
ForEachStmt statement = parseStatement("for (final Object o : objs) {}").asForEachStmt();
assertTrue(statement.hasFinalVariable());
assertEquals(
new ClassOrInterfaceType(null, "Object"),
statement.getVariableDeclarator().getType());
assertEquals("o", statement.getVariableDeclarator().getName().getIdentifier());
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.stmt;
import static com.github.javaparser.StaticJavaParser.parseStatement;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class IfElseStmtTest {
@Test
void issue1247withElseSingleStmt() {
IfStmt ifStmt = parseStatement("if (cond) doSomething(); else doSomethingElse();")
.asIfStmt();
assertFalse(ifStmt.hasElseBlock());
assertTrue(ifStmt.hasElseBranch());
assertFalse(ifStmt.hasCascadingIfStmt());
}
@Test
void issue1247withElseBlockStmt() {
IfStmt ifStmt = parseStatement("if (cond) doSomething(); else { doSomethingElse(); }")
.asIfStmt();
assertTrue(ifStmt.hasElseBlock());
assertTrue(ifStmt.hasElseBranch());
assertFalse(ifStmt.hasCascadingIfStmt());
}
@Test
void issue1247withElseSingleStmtWhichIsAnIf() {
IfStmt ifStmt = parseStatement("if (cond1) doSomething(); else if (cond2) doSomethingElse();")
.asIfStmt();
assertFalse(ifStmt.hasElseBlock());
assertTrue(ifStmt.hasElseBranch());
assertTrue(ifStmt.hasCascadingIfStmt());
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.stmt;
import static com.github.javaparser.StaticJavaParser.parseStatement;
import static com.github.javaparser.ast.stmt.SwitchEntry.Type.EXPRESSION;
import static com.github.javaparser.ast.stmt.SwitchEntry.Type.STATEMENT_GROUP;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.NullLiteralExpr;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class SwitchStmtTest {
private static final ParserConfiguration.LanguageLevel storedLanguageLevel =
StaticJavaParser.getParserConfiguration().getLanguageLevel();
@BeforeAll
public static void setLanguageLevel() {
StaticJavaParser.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.BLEEDING_EDGE);
}
@AfterAll
public static void resetLanguageLevel() {
StaticJavaParser.getParserConfiguration().setLanguageLevel(storedLanguageLevel);
}
@Test
void classicSwitch() {
SwitchStmt switchStmt = parseStatement("switch (day) {\n" + " case TUESDAY: System.out.println(7); break;\n"
+ " case FRIDAY: System.out.println(8); break;\n"
+ " default: System.out.println(-1); \n"
+ "}")
.asSwitchStmt();
assertEquals(STATEMENT_GROUP, switchStmt.getEntry(0).getType());
assertEquals(STATEMENT_GROUP, switchStmt.getEntry(1).getType());
assertEquals(STATEMENT_GROUP, switchStmt.getEntry(2).getType());
assertEquals(new NodeList<>(), switchStmt.getEntry(2).getLabels());
assertFalse(switchStmt.getEntry(0).isDefault());
assertFalse(switchStmt.getEntry(1).isDefault());
assertTrue(switchStmt.getEntry(2).isDefault());
}
@Test
void jep325Example1() {
SwitchStmt switchStmt = parseStatement("switch (day) {\n" +
// " case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);\n" +
" case TUESDAY -> System.out.println(7);\n"
+
// " case THURSDAY, SATURDAY -> System.out.println(8);\n" +
" case WEDNESDAY -> System.out.println(9);\n"
+ "}")
.asSwitchStmt();
assertEquals(EXPRESSION, switchStmt.getEntry(0).getType());
}
@Test
void jep441Example1() {
SwitchStmt switchStmt = parseStatement(
"switch (day) {\n" + " case null, default -> System.out.println(-1); \n" + "}")
.asSwitchStmt();
assertTrue(switchStmt.getEntry(0).isDefault());
assertInstanceOf(
NullLiteralExpr.class, switchStmt.getEntry(0).getLabels().get(0));
}
@Test
void issue4455Test() {
SwitchStmt switchStmt = parseStatement(
"switch (column) {\n" + " case CustomDeployTableModel.ARTIFACT_NAME:\n" + "}")
.asSwitchStmt();
assertEquals(Node.Parsedness.PARSED, switchStmt.getParsed());
SwitchEntry entry = switchStmt.getEntry(0);
Expression switchLabel = entry.getLabels().get(0);
assertEquals("CustomDeployTableModel.ARTIFACT_NAME", switchLabel.toString());
assertTrue(switchLabel.isFieldAccessExpr());
}
@Test
void issue4607Test() {
SwitchStmt switchStmt = parseStatement("switch (o) { case String s when s.length() == 1 -> 0; }")
.asSwitchStmt();
assertEquals(switchStmt.toString(), switchStmt.clone().toString());
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.stmt;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParseStart;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.expr.FieldAccessExpr;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import org.junit.jupiter.api.Test;
class TryStmtTest {
@Test
void simpleTest() {
TryStmt tryStmt = parse9("try(Reader x = new FileReader()){}");
assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
}
@Test
void multipleTest() {
TryStmt tryStmt = parse9("try(Reader x = new FileReader(); Reader x = new FileReader()){}");
assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
}
@Test
void modifiersTest() {
TryStmt tryStmt = parse9("try(final @A Reader x = new FileReader()){}");
assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
}
@Test
void simpleVariable() {
TryStmt tryStmt = parse9("try(a){}");
assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0));
}
@Test
void twoSimpleVariables() {
TryStmt tryStmt = parse9("try(a;b){}");
assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0));
assertInstanceOf(NameExpr.class, tryStmt.getResources().get(1));
}
@Test
void complexVariable() {
TryStmt tryStmt = parse9("try(a.b.c){}");
assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0));
}
@Test
void superAccess() {
TryStmt tryStmt = parse9("try(super.a){}");
assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0));
}
@Test
void outerClassAccess() {
TryStmt tryStmt = parse9("try(X.this.a){}");
assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0));
}
@Test
void varTestJava10() {
TryStmt tryStmt = parse10("try(var x = new FileReader()){}");
assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
}
@Test
void varTestJava11() {
TryStmt tryStmt = parse11("try(var x = new FileReader()){}");
assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0));
}
private <T> T parse9(String code) {
JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9));
ParseResult<Statement> result = parser.parse(ParseStart.STATEMENT, provider(code));
assertTrue(result.isSuccessful(), result.toString());
return (T) result.getResult().get();
}
private <T> T parse10(String code) {
JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10));
ParseResult<Statement> result = parser.parse(ParseStart.STATEMENT, provider(code));
assertTrue(result.isSuccessful(), result.toString());
return (T) result.getResult().get();
}
private <T> T parse11(String code) {
JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_11));
ParseResult<Statement> result = parser.parse(ParseStart.STATEMENT, provider(code));
assertTrue(result.isSuccessful(), result.toString());
return (T) result.getResult().get();
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.stmt;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_12;
import static com.github.javaparser.utils.TestParser.parseCompilationUnit;
import static com.github.javaparser.utils.TestParser.parseStatement;
import static com.github.javaparser.utils.TestUtils.assertEqualsStringIgnoringEol;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.*;
import org.junit.jupiter.api.Test;
class YieldStmtTest {
@Test
void yield() {
YieldStmt statement = parseStatement("yield 12*12;").asYieldStmt();
assertEquals(BinaryExpr.class, statement.getExpression().getClass());
}
@Test
void yield2() {
YieldStmt statement;
statement = parseStatement("yield (2 + 2);").asYieldStmt();
assertEquals(EnclosedExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield ((2 + 2) * 3);").asYieldStmt();
assertEquals(EnclosedExpr.class, statement.getExpression().getClass());
}
@Test
void yieldMethodCall() {
YieldStmt statement;
statement = parseStatement("yield a();").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield a(5, arg);").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield a.b();").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield a.b(5, arg);").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield this.b();").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield this.b(5, arg);").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield Clazz.this.b();").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield Clazz.this.b(5, arg);").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
}
@Test
void yieldAssignment() {
YieldStmt statement = parseStatement("yield (x = 5);").asYieldStmt();
assertEquals(EnclosedExpr.class, statement.getExpression().getClass());
}
@Test
void yieldConditional() {
YieldStmt statement = parseStatement("yield x ? 5 : 6;").asYieldStmt();
assertEquals(ConditionalExpr.class, statement.getExpression().getClass());
}
@Test
void threadYieldShouldNotBreak() {
parseStatement("Thread.yield();").asExpressionStmt().getExpression().asMethodCallExpr();
}
@Test
void keywordShouldNotInterfereWithIdentifiers() {
CompilationUnit compilationUnit =
parseCompilationUnit(JAVA_12, "class yield { yield yield(yield yield){yield();} }");
assertEqualsStringIgnoringEol(
"class yield {\n" + "\n"
+ " yield yield(yield yield) {\n"
+ " yield();\n"
+ " }\n"
+ "}\n",
compilationUnit.toString());
}
@Test
void keywordShouldNotInterfereWithIdentifiers2() {
CompilationUnit compilationUnit = parseCompilationUnit("enum X { yield, }");
assertEqualsStringIgnoringEol("enum X {\n" + "\n" + " yield\n" + "}\n", compilationUnit.toString());
}
@Test
void keywordShouldNotInterfereWithIdentifiers3() {
YieldStmt statement;
statement = parseStatement("yield yield;").asYieldStmt();
assertEquals(NameExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield Clazz.yield();").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
statement = parseStatement("yield yield.yield();").asYieldStmt();
assertEquals(MethodCallExpr.class, statement.getExpression().getClass());
}
}

View File

@@ -0,0 +1,212 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.type;
import static com.github.javaparser.StaticJavaParser.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.expr.ArrayCreationExpr;
import com.github.javaparser.ast.expr.MarkerAnnotationExpr;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.printer.ConcreteSyntaxModel;
import com.github.javaparser.utils.LineSeparator;
import org.junit.jupiter.api.Test;
class ArrayTypeTest {
@Test
void getFieldDeclarationWithArrays() {
FieldDeclaration fieldDeclaration =
parseBodyDeclaration("@C int @A[] @B[] a @X[] @Y[];").asFieldDeclaration();
ArrayType arrayType1 = fieldDeclaration.getVariable(0).getType().asArrayType();
ArrayType arrayType2 = arrayType1.getComponentType().asArrayType();
ArrayType arrayType3 = arrayType2.getComponentType().asArrayType();
ArrayType arrayType4 = arrayType3.getComponentType().asArrayType();
PrimitiveType elementType = arrayType4.getComponentType().asPrimitiveType();
assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X")));
assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y")));
assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A")));
assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT);
assertThat(fieldDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(fieldDeclaration);
}
@Test
void getVariableDeclarationWithArrays() {
ExpressionStmt variableDeclarationStatement =
parseStatement("@C int @A[] @B[] a @X[] @Y[];").asExpressionStmt();
VariableDeclarationExpr variableDeclarationExpr =
variableDeclarationStatement.getExpression().asVariableDeclarationExpr();
ArrayType arrayType1 = variableDeclarationExpr.getVariable(0).getType().asArrayType();
ArrayType arrayType2 = arrayType1.getComponentType().asArrayType();
ArrayType arrayType3 = arrayType2.getComponentType().asArrayType();
ArrayType arrayType4 = arrayType3.getComponentType().asArrayType();
PrimitiveType elementType = arrayType4.getComponentType().asPrimitiveType();
assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X")));
assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y")));
assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A")));
assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT);
assertThat(variableDeclarationExpr.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(variableDeclarationExpr);
}
@Test
void getMethodDeclarationWithArrays() {
MethodDeclaration methodDeclaration =
parseBodyDeclaration("@C int @A[] a() @B[] {}").asMethodDeclaration();
ArrayType arrayType1 = methodDeclaration.getType().asArrayType();
ArrayType arrayType2 = arrayType1.getComponentType().asArrayType();
Type elementType = arrayType2.getComponentType();
assertThat(elementType).isInstanceOf(PrimitiveType.class);
assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A")));
assertThat(methodDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
assertThat(methodDeclaration.getType().getParentNode().get()).isSameAs(methodDeclaration);
}
@Test
void getParameterWithArrays() {
MethodDeclaration methodDeclaration =
parseBodyDeclaration("void a(@C int @A[] a @B[]) {}").asMethodDeclaration();
Parameter parameter = methodDeclaration.getParameter(0);
ArrayType outerArrayType = parameter.getType().asArrayType();
ArrayType innerArrayType = outerArrayType.getComponentType().asArrayType();
PrimitiveType elementType = innerArrayType.getComponentType().asPrimitiveType();
assertThat(elementType).isInstanceOf(PrimitiveType.class);
assertThat(outerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
assertThat(innerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A")));
assertThat(parameter.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
assertThat(parameter.getType().getParentNode().get()).isSameAs(parameter);
}
@Test
void setVariableDeclarationWithArrays() {
ExpressionStmt variableDeclarationStatement =
parseStatement("@C int @A[] @B[] a @X[] @Y[];").asExpressionStmt();
VariableDeclarationExpr variableDeclarationExpr =
variableDeclarationStatement.getExpression().asVariableDeclarationExpr();
variableDeclarationExpr.getVariable(0).setType(new ArrayType(new ArrayType(PrimitiveType.intType())));
assertEquals("@C" + LineSeparator.SYSTEM + "int[][] a;", variableDeclarationStatement.toString());
}
@Test
void setFieldDeclarationWithArrays() {
FieldDeclaration fieldDeclaration =
parseBodyDeclaration("int[][] a[][];").asFieldDeclaration();
fieldDeclaration.getVariable(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob"))));
assertEquals("Blob[][] a;", fieldDeclaration.toString());
}
@Test
void setMethodDeclarationWithArrays() {
MethodDeclaration method = parseBodyDeclaration("int[][] a()[][] {}").asMethodDeclaration();
method.setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob"))));
assertEquals("Blob[][] a() {" + LineSeparator.SYSTEM + "}", method.toString());
}
@Test
void fieldDeclarationWithArraysHasCorrectOrigins() {
FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[] a[];").asFieldDeclaration();
Type outerType = fieldDeclaration.getVariables().get(0).getType();
assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getOrigin());
assertEquals(
ArrayType.Origin.TYPE,
outerType.asArrayType().getComponentType().asArrayType().getOrigin());
}
@Test
void methodDeclarationWithArraysHasCorrectOrigins() {
MethodDeclaration method = (MethodDeclaration) parseBodyDeclaration("int[] a()[] {}");
Type outerType = method.getType();
assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getOrigin());
assertEquals(
ArrayType.Origin.TYPE,
outerType.asArrayType().getComponentType().asArrayType().getOrigin());
}
@Test
void setParameterWithArrays() {
MethodDeclaration method =
parseBodyDeclaration("void a(int[][] a[][]) {}").asMethodDeclaration();
method.getParameter(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob"))));
assertEquals("void a(Blob[][] a) {" + LineSeparator.SYSTEM + "}", method.toString());
}
@Test
void getArrayCreationType() {
ArrayCreationExpr expr = parseExpression("new int[]");
ArrayType outerType = expr.createdType().asArrayType();
Type innerType = outerType.getComponentType();
assertThat(innerType).isEqualTo(expr.getElementType());
}
@Test
void ellipsisCanHaveAnnotationsToo() {
Parameter p = parseParameter("int[]@X...a[]");
assertThat(p.getVarArgsAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X")));
assertEquals("int[][]@X ... a", p.toString());
assertEquals("int[][]@X... a", ConcreteSyntaxModel.genericPrettyPrint(p));
}
@Test
void arrayLevel() {
FieldDeclaration fd1 = parseBodyDeclaration("int[] a;").asFieldDeclaration();
assertEquals(1, fd1.getVariable(0).getType().getArrayLevel());
FieldDeclaration fd2 = parseBodyDeclaration("int[][] a;").asFieldDeclaration();
assertEquals(2, fd2.getVariable(0).getType().getArrayLevel());
}
@Test
void range() {
Type type = parseType("Long[][]");
assertEquals(8, type.getRange().get().end.column);
}
}

View File

@@ -0,0 +1,139 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.type;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ClassOrInterfaceTypeTest {
@Test
void testSetName() {
ClassOrInterfaceType classOrInterfaceType = new ClassOrInterfaceType();
assertNotEquals("A", classOrInterfaceType.getName().toString());
classOrInterfaceType.setName("A");
assertEquals("A", classOrInterfaceType.getName().toString());
}
@Test
void testNestedClass() {
ClassOrInterfaceType classA = new ClassOrInterfaceType();
classA.setName("A");
ClassOrInterfaceType classB = new ClassOrInterfaceType(classA, "B");
assertEquals("A.B", classB.getNameWithScope());
}
@Test
void testWithGeneric() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
ClassOrInterfaceType classB = new ClassOrInterfaceType(classA, new SimpleName("B"), new NodeList<>(classA));
assertTrue(classB.getTypeArguments().isPresent());
assertEquals(1, classB.getTypeArguments().get().size());
assertEquals(classA, classB.getTypeArguments().get().get(0));
assertEquals("A.B", classB.getNameWithScope());
assertEquals("A.B<A>", classB.asString());
}
@Test
void testWithAnnotations() {
AnnotationExpr annotationExpr = StaticJavaParser.parseAnnotation("@Override");
ClassOrInterfaceType classA =
new ClassOrInterfaceType(null, new SimpleName("A"), null, new NodeList<>(annotationExpr));
assertEquals(1, classA.getAnnotations().size());
assertEquals(annotationExpr, classA.getAnnotation(0));
}
@Test
void testResolveWithoutCompilationUnit() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
Assertions.assertThrows(IllegalStateException.class, classA::resolve);
}
@Test
void testToDescriptorWithoutCompilationUnit() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
Assertions.assertThrows(IllegalStateException.class, classA::toDescriptor);
}
@Test
void testToClassOrInterfaceType() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
Optional<ClassOrInterfaceType> newClass = classA.toClassOrInterfaceType();
assertTrue(newClass.isPresent());
assertSame(classA, newClass.get());
}
@Test
void testIfClassOrInterfaceTypeIsCalled() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
classA.ifClassOrInterfaceType(classOrInterfaceType -> assertSame(classA, classOrInterfaceType));
}
@Test
void testAsClassOrInterfaceTypeIsTheSame() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
assertTrue(classA.isClassOrInterfaceType());
assertEquals(classA, classA.asClassOrInterfaceType());
}
@Test
void testCloneClass() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
assertEquals(classA, classA.clone());
}
@Test
void testMetaModel() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
assertEquals(JavaParserMetaModel.classOrInterfaceTypeMetaModel, classA.getMetaModel());
}
@Test
void testAcceptVoidVisitor() {
ClassOrInterfaceType classA = new ClassOrInterfaceType(null, "A");
classA.accept(
new VoidVisitorAdapter<Object>() {
@Override
public void visit(ClassOrInterfaceType classOrInterfaceType, Object object) {
super.visit(classOrInterfaceType, object);
assertEquals(classA, classOrInterfaceType);
}
},
null);
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.type;
import static com.github.javaparser.ParseStart.VARIABLE_DECLARATION_EXPR;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.RAW;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.StaticJavaParser.parseType;
import static com.github.javaparser.StaticJavaParser.parseVariableDeclarationExpr;
import static org.junit.jupiter.api.Assertions.*;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseProblemException;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.validator.language_level_validations.Java5Validator;
import org.junit.jupiter.api.Test;
class TypeTest {
@Test
void asString() {
assertEquals("int", typeAsString("int x"));
assertEquals("List<Long>", typeAsString("List<Long> x"));
assertEquals("String", typeAsString("@A String x"));
assertEquals("List<? extends Object>", typeAsString("List<? extends Object> x"));
}
@Test
void primitiveTypeArgumentDefaultValidator() {
assertThrows(ParseProblemException.class, () -> typeAsString("List<long> x;"));
}
@Test
void primitiveTypeArgumentLenientValidator() {
ParserConfiguration config = new ParserConfiguration().setLanguageLevel(RAW);
config.getProcessors()
.add(() -> new Java5Validator() {
{
remove(noPrimitiveGenericArguments);
}
}.processor());
ParseResult<VariableDeclarationExpr> result =
new JavaParser(config).parse(VARIABLE_DECLARATION_EXPR, provider("List<long> x"));
assertTrue(result.isSuccessful());
VariableDeclarationExpr decl = result.getResult().get();
assertEquals("List<long>", decl.getVariable(0).getType().asString());
}
private String typeAsString(String s) {
return parseVariableDeclarationExpr(s).getVariable(0).getType().asString();
}
@Test
void arrayType() {
Type type = parseType("int[]");
assertTrue(type.isArrayType());
ArrayType arrayType = type.asArrayType();
final ArrayType[] s = new ArrayType[1];
type.ifArrayType(t -> s[0] = t);
assertNotNull(s[0]);
}
@Test
void issue1251() {
final Type type = parseType("TypeUtilsTest<String>.Tester");
assertEquals("TypeUtilsTest<String>.Tester", type.toString());
}
}

View File

@@ -0,0 +1,136 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.CLASS_BODY;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_10;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class Java10ValidatorTest {
public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10));
@Test
void varAllowedInLocalVariableDeclaration() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a = 5;"));
assertNoProblems(result);
}
@Test
void varAllowedInForEach() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a : as){}"));
assertNoProblems(result);
}
@Test
void varAllowedInOldFor() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a = 5;a<9;a++){}"));
assertNoProblems(result);
}
@Test
void varAllowedInTryWithResources() {
ParseResult<Statement> result =
javaParser.parse(STATEMENT, provider("try(var f = new FileReader(\"\")){ }catch (Exception e){ }"));
assertNoProblems(result);
}
@Test
void varNotAllowedInCast() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int a = (var)20;"));
assertNoProblems(result);
}
@Test
void varNotAllowedInField() {
ParseResult<BodyDeclaration<?>> result = javaParser.parse(CLASS_BODY, provider("var a = 20;"));
assertProblems(result, "(line 1,col 1) \"var\" is not allowed here.");
}
@Test
void varNotAllowedInTypeArguments() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("new X<var>();"));
assertProblems(result, "(line 1,col 7) \"var\" is not allowed here.");
}
@Test
void varNotAllowedInLambdaParameters() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("x((var x) -> null);"));
assertProblems(result, "(line 1,col 4) \"var\" is not allowed here.");
}
@Test
void emptyInitializerNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a;"));
assertProblems(result, "(line 1,col 1) \"var\" needs an initializer.");
}
@Test
void multipleVariablesNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=1, b=2;"));
assertProblems(result, "(line 1,col 1) \"var\" only takes a single variable.");
}
@Test
void nullVariablesNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=null;"));
assertProblems(result, "(line 1,col 1) \"var\" cannot infer type from just null.");
}
@Test
void extraBracketPairsNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var d[] = new int[4];"));
assertProblems(result, "(line 1,col 5) \"var\" cannot have extra array brackets.");
}
@Test
void arrayDimensionBracketsNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a={ 6 };"));
assertProblems(result, "(line 1,col 1) \"var\" cannot infer array types.");
}
// This is pretty hard to impossible to implement correctly with just the AST.
@Disabled
@Test
void selfReferenceNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=a;"));
assertProblems(result, "");
}
// Can be implemented once https://github.com/javaparser/javaparser/issues/1434 is implemented.
@Disabled
@Test
void polyExpressionAsInitializerNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=new ArrayList<>();"));
assertProblems(result, "");
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_11;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java11ValidatorTest {
public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_11));
@Test
void varAllowedInLocalVariableDeclaration() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("x((var x, var y) -> x+y);"));
assertNoProblems(result);
}
@Test
void switchExpressionNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int a = switch(x){};"));
assertProblems(
result,
"(line 1,col 9) Switch expressions are not supported. Pay attention that this feature is supported starting from 'JAVA_12' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void multiLabelCaseNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case 3,4,5: ;}"));
assertProblems(
result,
"(line 1,col 11) Only one label allowed in a switch-case. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_12_PREVIEW;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java12ValidatorTest {
public static final JavaParser javaParser =
new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_12_PREVIEW));
@Test
void expressionsInLabelsNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case 3+4+5: ;}"));
assertNoProblems(result);
}
@Test
void switchExpressionNotAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int a = switch(x){};"));
assertNoProblems(result);
}
@Test
void multiLabelCaseAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case 3,4,5: ;}"));
assertNoProblems(result);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_13_PREVIEW;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java13ValidatorTest {
public static final JavaParser javaParser =
new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_13_PREVIEW));
@Test
void yieldAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case 3: yield 6;}"));
assertNoProblems(result);
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_14_PREVIEW;
import static com.github.javaparser.Providers.provider;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.utils.TestUtils;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class Java14PreviewValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_14_PREVIEW));
/**
* Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release).
* The introduction of records means that they are no longer able to be used as identifiers.
*/
@Nested
class Record {
@Nested
class RecordAsTypeIdentifierForbidden {
@Test
void recordUsedAsClassIdentifier() {
String s = "public class record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertProblems(
result,
"(line 1,col 14) 'record' is a restricted identifier and cannot be used for type declarations");
}
@Test
void recordUsedAsEnumIdentifier() {
String s = "public enum record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertProblems(
result,
"(line 1,col 13) 'record' is a restricted identifier and cannot be used for type declarations");
}
@Test
void recordUsedAsRecordIdentifier() {
String s = "public record record() {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertProblems(
result,
"(line 1,col 15) 'record' is a restricted identifier and cannot be used for type declarations");
}
}
@Nested
class RecordUsedAsIdentifierAllowedAsFieldDeclarations {
@Test
void recordUsedAsFieldIdentifierInClass() {
String s = "class X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
@Test
void recordUsedAsFieldIdentifierInInterface() {
String s = "interface X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
}
@Nested
class RecordDeclarationPermitted {
@Test
void recordDeclaration() {
String s = "record X() { }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
}
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParseStart.EXPRESSION;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_14;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.utils.TestUtils;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class Java14ValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_14));
// TODO: Confirm FORBIDDEN - pattern matching instanceof
// TODO: Confirm PERMITTED - text blocks permitted
@Nested
class SwitchExpr {
@Test
void switchExprAllowed() {
ParseResult<Expression> result =
javaParser.parse(EXPRESSION, provider("switch(x){case 3 -> System.out.println(0);}"));
assertNoProblems(result);
}
@Test
void noSwitchDefaultCaseAllowed() {
ParseResult<Expression> result =
javaParser.parse(EXPRESSION, provider("switch(x){case null, default -> System.out.println(0);}"));
assertProblems(
result,
"(line 1,col 11) Switch case null, default not supported. Pay attention that this feature is supported starting from 'JAVA_21' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void noSwitchPatternAllowed() {
ParseResult<Expression> result =
javaParser.parse(EXPRESSION, provider("switch(x){case String s -> System.out.println(0);}"));
assertProblems(
result,
"(line 1,col 11) Switch patterns not supported. Pay attention that this feature is supported starting from 'JAVA_21' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
}
/**
* Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release).
* The introduction of records means that they are no longer able to be used as identifiers.
*/
@Nested
class Record {
@Nested
class RecordAsIdentifierPermitted {
@Test
void recordUsedAsClassName() {
String s = "public class record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
@Test
void recordUsedAsFieldName() {
String s = "class X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
}
@Nested
class RecordDeclarationForbidden {
@Test
void recordDeclaration() {
String s = "record X() { }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
assertProblems(
result,
"(line 1,col 1) Record Declarations are not supported. Pay attention that this feature is supported starting from 'JAVA_14' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
}
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_15_PREVIEW;
import static com.github.javaparser.Providers.provider;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.utils.TestUtils;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class Java15PreviewValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_15_PREVIEW));
/**
* Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release).
* The introduction of records means that they are no longer able to be used as identifiers.
*/
@Nested
class Record {
@Nested
class RecordAsTypeIdentifierForbidden {
@Test
void recordUsedAsClassIdentifier() {
String s = "public class record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertProblems(
result,
"(line 1,col 14) 'record' is a restricted identifier and cannot be used for type declarations");
}
@Test
void recordUsedAsEnumIdentifier() {
String s = "public enum record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertProblems(
result,
"(line 1,col 13) 'record' is a restricted identifier and cannot be used for type declarations");
}
@Test
void recordUsedAsRecordIdentifier() {
String s = "public record record() {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertProblems(
result,
"(line 1,col 15) 'record' is a restricted identifier and cannot be used for type declarations");
}
}
@Nested
class RecordUsedAsIdentifierAllowedAsFieldDeclarations {
@Test
void recordUsedAsFieldIdentifierInClass() {
String s = "class X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
@Test
void recordUsedAsFieldIdentifierInInterface() {
String s = "interface X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
}
@Nested
class RecordDeclarationPermitted {
@Test
void recordDeclaration() {
String s = "record X() { }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
}
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_15;
import static com.github.javaparser.Providers.provider;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.utils.TestUtils;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class Java15ValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_15));
// TODO: Confirm PERMITTED - text blocks
/**
* Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release).
* The introduction of records means that they are no longer able to be used as identifiers.
*/
@Nested
class Record {
@Nested
class RecordAsIdentifierPermitted {
@Test
void recordUsedAsClassName() {
String s = "public class record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
@Test
void recordUsedAsFieldName() {
String s = "class X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertNoProblems(result);
}
}
@Nested
class RecordDeclarationForbidden {
@Test
void recordDeclaration() {
String s = "record X() { }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
TestUtils.assertProblems(
result,
"(line 1,col 1) Record Declarations are not supported. Pay attention that this feature is supported starting from 'JAVA_14' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
}
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_16_PREVIEW;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParserConfiguration;
class Java16PreviewValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_16_PREVIEW));
}

View File

@@ -0,0 +1,140 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_16;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class Java16ValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_16));
@Test
void localInterface() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + "interface I{}}}"));
assertNoProblems(result);
}
@Nested
class Yield {
@Test
void yieldAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case 3: yield 6;}"));
assertNoProblems(result);
}
}
@Nested
class PatternMatching {
@Test
void patternMatchingAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("if (a instanceof String s) {}"));
assertNoProblems(result);
}
@Test
void recordPatternsForbidden() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("if (a instanceof Box(String s)) {}"));
assertProblems(
result,
"(line 1,col 18) Record patterns are not supported. Pay attention that this feature is supported starting from 'JAVA_21' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
}
/**
* Records are available within Java 14 (preview), Java 15 (2nd preview), and Java 16 (release).
* The introduction of records means that they are no longer able to be used as identifiers.
*/
@Nested
class Record {
@Nested
class RecordAsTypeIdentifierForbidden {
@Test
void recordUsedAsClassIdentifier() {
String s = "public class record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
assertProblems(
result,
"(line 1,col 14) 'record' is a restricted identifier and cannot be used for type declarations");
}
@Test
void recordUsedAsEnumIdentifier() {
String s = "public enum record {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
assertProblems(
result,
"(line 1,col 13) 'record' is a restricted identifier and cannot be used for type declarations");
}
@Test
void recordUsedAsRecordIdentifier() {
String s = "public record record() {}";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
assertProblems(
result,
"(line 1,col 15) 'record' is a restricted identifier and cannot be used for type declarations");
}
}
@Nested
class RecordUsedAsIdentifierAllowedAsFieldDeclarations {
@Test
void recordUsedAsFieldIdentifierInClass() {
String s = "class X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
assertNoProblems(result);
}
@Test
void recordUsedAsFieldIdentifierInInterface() {
String s = "interface X { int record; }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
assertNoProblems(result);
}
}
@Nested
class RecordDeclarationPermitted {
@Test
void recordDeclaration() {
String s = "record X() { }";
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(s));
assertNoProblems(result);
}
}
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_17;
import static com.github.javaparser.Providers.provider;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.utils.TestUtils;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class Java17ValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_17));
@Nested
class Sealed {
@Test
void sealedAllowed() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("sealed class X permits Y, Z {}"));
TestUtils.assertNoProblems(result);
}
@Test
void nonSealedAllowed() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("non-sealed class X {}"));
TestUtils.assertNoProblems(result);
}
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_18;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParserConfiguration;
class Java18ValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_18));
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_19;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParserConfiguration;
class Java19ValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_19));
}

View File

@@ -0,0 +1,132 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.*;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_0;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java1_0ValidatorTest {
public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_0));
@Test
void tryWithoutResources() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(X x=new Y()){}"));
assertProblems(
result,
"(line 1,col 1) Try has no finally and no catch. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.",
"(line 1,col 1) Catch with resource is not supported. Pay attention that this feature is supported starting from 'JAVA_7' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void classExtendingMoreThanOne() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X extends Y, Z {}"));
assertProblems(result, "(line 1,col 20) A class cannot extend more than one other class.");
}
@Test
void interfaceUsingImplements() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("interface X implements Y {}"));
assertProblems(result, "(line 1,col 24) An interface cannot implement other interfaces.");
}
@Test
void interfaceWithInitializer() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {{}}"));
assertProblems(result, "(line 1,col 14) An interface cannot have initializers.");
}
@Test
void defaultInClass() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X {default void a(){};}"));
assertProblems(result, "(line 1,col 10) 'default' is not allowed here.");
}
@Test
void leftHandAssignmentCannotBeAConditional() {
ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("(1==2)=3"));
assertProblems(result, "(line 1,col 1) Illegal left hand side of an assignment.");
}
@Test
void leftHandAssignmentCannotBeEmptyBraces() {
ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("()=3"));
assertProblems(
result,
"(line 1,col 1) Illegal left hand side of an assignment.",
"(line 1,col 1) Lambdas are not supported. Pay attention that this feature is supported starting from 'JAVA_8' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void leftHandAssignmentCanBeInBraces() {
ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("(i) += (i) += 1"));
assertNoProblems(result);
}
@Test
void noInnerClasses() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}"));
assertProblems(
result,
"(line 1,col 9) inner classes or interfaces are not supported. Pay attention that this feature is supported starting from 'JAVA_1_1' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void noReflection() {
ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class"));
assertProblems(
result,
"(line 1,col 1) Reflection is not supported. Pay attention that this feature is supported starting from 'JAVA_1_1' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void noForEach() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(X x : xs){}"));
assertProblems(
result,
"(line 1,col 1) For-each loops are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void labelBreakAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case 3: break bla;}"));
assertNoProblems(result);
}
@Test
void emptyBreakAllowed() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case 3: break;}"));
assertNoProblems(result);
}
}

View File

@@ -0,0 +1,325 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.*;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_1;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java1_1ValidatorTest {
public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_1));
public static final String allModifiers =
"public protected private abstract static final transient volatile synchronized native strictfp transitive default ";
@Test
void topClass() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "class X{}"));
assertProblems(
result,
"(line 1,col 1) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 1) Can have only one of 'final', 'abstract'.",
"(line 1,col 1) 'transient' is not allowed here.",
"(line 1,col 1) 'default' is not allowed here.",
"(line 1,col 1) 'volatile' is not allowed here.",
"(line 1,col 1) 'strictfp' is not allowed here.",
"(line 1,col 1) 'private' is not allowed here.",
"(line 1,col 1) 'protected' is not allowed here.",
"(line 1,col 1) 'synchronized' is not allowed here.",
"(line 1,col 1) 'native' is not allowed here.",
"(line 1,col 1) 'transitive' is not allowed here.",
"(line 1,col 1) 'static' is not allowed here.");
}
@Test
void nestedClass() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "class I{}}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void localClass() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "class I{}}}"));
assertProblems(
result,
"(line 1,col 20) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 20) Can have only one of 'final', 'abstract'.",
"(line 1,col 20) 'transient' is not allowed here.",
"(line 1,col 20) 'volatile' is not allowed here.",
"(line 1,col 20) 'default' is not allowed here.",
"(line 1,col 20) 'synchronized' is not allowed here.",
"(line 1,col 20) 'native' is not allowed here.",
"(line 1,col 20) 'transitive' is not allowed here.",
"(line 1,col 20) 'strictfp' is not allowed here.",
"(line 1,col 20) 'static' is not allowed here.",
"(line 1,col 20) 'public' is not allowed here.",
"(line 1,col 20) 'private' is not allowed here.",
"(line 1,col 20) 'protected' is not allowed here.");
}
@Test
void topInterface() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "interface X{}"));
assertProblems(
result,
"(line 1,col 1) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 1) Can have only one of 'final', 'abstract'.",
"(line 1,col 1) 'transient' is not allowed here.",
"(line 1,col 1) 'volatile' is not allowed here.",
"(line 1,col 1) 'default' is not allowed here.",
"(line 1,col 1) 'strictfp' is not allowed here.",
"(line 1,col 1) 'synchronized' is not allowed here.",
"(line 1,col 1) 'native' is not allowed here.",
"(line 1,col 1) 'transitive' is not allowed here.",
"(line 1,col 1) 'static' is not allowed here.",
"(line 1,col 1) 'final' is not allowed here.",
"(line 1,col 1) 'private' is not allowed here.",
"(line 1,col 1) 'protected' is not allowed here.");
}
@Test
void nestedInterface() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "interface I{}}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'final' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void constructor() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "X(){};}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'final' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'abstract' is not allowed here.",
"(line 1,col 9) 'static' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void constructorParameter() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{X(" + allModifiers + " int i){};}"));
assertProblems(
result,
"(line 1,col 11) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 11) Can have only one of 'final', 'abstract'.",
"(line 1,col 11) 'transient' is not allowed here.",
"(line 1,col 11) 'volatile' is not allowed here.",
"(line 1,col 11) 'synchronized' is not allowed here.",
"(line 1,col 11) 'native' is not allowed here.",
"(line 1,col 11) 'strictfp' is not allowed here.",
"(line 1,col 11) 'default' is not allowed here.",
"(line 1,col 11) 'abstract' is not allowed here.",
"(line 1,col 11) 'static' is not allowed here.",
"(line 1,col 11) 'transitive' is not allowed here.",
"(line 1,col 11) 'private' is not allowed here.",
"(line 1,col 11) 'public' is not allowed here.",
"(line 1,col 11) 'protected' is not allowed here.");
}
@Test
void classMethod() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int x(){};}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void interfaceMethod() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}"));
assertProblems(
result,
"(line 1,col 13) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 13) Can have only one of 'final', 'abstract'.",
"(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.",
"(line 1,col 13) 'transient' is not allowed here.",
"(line 1,col 13) 'strictfp' is not allowed here.",
"(line 1,col 13) 'volatile' is not allowed here.",
"(line 1,col 13) 'default' is not allowed here.",
"(line 1,col 13) 'transitive' is not allowed here.",
"(line 1,col 13) 'private' is not allowed here.",
"(line 1,col 13) 'static' is not allowed here.");
}
@Test
void methodParameter() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{int x(" + allModifiers + " int i){};}"));
assertProblems(
result,
"(line 1,col 15) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 15) Can have only one of 'final', 'abstract'.",
"(line 1,col 15) 'transient' is not allowed here.",
"(line 1,col 15) 'volatile' is not allowed here.",
"(line 1,col 15) 'synchronized' is not allowed here.",
"(line 1,col 15) 'native' is not allowed here.",
"(line 1,col 15) 'strictfp' is not allowed here.",
"(line 1,col 15) 'abstract' is not allowed here.",
"(line 1,col 15) 'default' is not allowed here.",
"(line 1,col 15) 'static' is not allowed here.",
"(line 1,col 15) 'transitive' is not allowed here.",
"(line 1,col 15) 'private' is not allowed here.",
"(line 1,col 15) 'public' is not allowed here.",
"(line 1,col 15) 'protected' is not allowed here.");
}
@Test
void field() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int i;}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'abstract' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void localVariable() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){" + allModifiers + "int i;}}"));
assertProblems(
result,
"(line 1,col 17) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 17) Can have only one of 'final', 'abstract'.",
"(line 1,col 17) 'transient' is not allowed here.",
"(line 1,col 17) 'volatile' is not allowed here.",
"(line 1,col 17) 'synchronized' is not allowed here.",
"(line 1,col 17) 'native' is not allowed here.",
"(line 1,col 17) 'default' is not allowed here.",
"(line 1,col 17) 'strictfp' is not allowed here.",
"(line 1,col 17) 'abstract' is not allowed here.",
"(line 1,col 17) 'static' is not allowed here.",
"(line 1,col 17) 'transitive' is not allowed here.",
"(line 1,col 17) 'private' is not allowed here.",
"(line 1,col 17) 'public' is not allowed here.",
"(line 1,col 17) 'protected' is not allowed here.");
}
@Test
void catchParameter() {
ParseResult<CompilationUnit> result = javaParser.parse(
COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}"));
assertProblems(
result,
"(line 1,col 29) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 29) Can have only one of 'final', 'abstract'.",
"(line 1,col 29) 'transient' is not allowed here.",
"(line 1,col 29) 'volatile' is not allowed here.",
"(line 1,col 29) 'synchronized' is not allowed here.",
"(line 1,col 29) 'native' is not allowed here.",
"(line 1,col 29) 'default' is not allowed here.",
"(line 1,col 29) 'strictfp' is not allowed here.",
"(line 1,col 29) 'abstract' is not allowed here.",
"(line 1,col 29) 'static' is not allowed here.",
"(line 1,col 29) 'transitive' is not allowed here.",
"(line 1,col 29) 'private' is not allowed here.",
"(line 1,col 29) 'public' is not allowed here.",
"(line 1,col 29) 'protected' is not allowed here.");
}
@Test
void innerClasses() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}"));
assertNoProblems(result);
}
@Test
void localInterface() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "interface I{}}}"));
assertProblems(
result,
"(line 1,col 20) There is no such thing as a local interface. Pay attention that this feature is supported starting from 'JAVA_16' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void reflection() {
ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class"));
assertNoProblems(result);
}
@Test
void strictfpAllowedAsIdentifier() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int strictfp;"));
assertNoProblems(result);
}
}

View File

@@ -0,0 +1,308 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_2;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java1_2ValidatorTest {
public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_2));
private final String allModifiers =
"public protected private abstract static final transient volatile synchronized native strictfp transitive default ";
@Test
void topClass() {
ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "class X{}"));
assertProblems(
result,
"(line 1,col 1) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 1) Can have only one of 'final', 'abstract'.",
"(line 1,col 1) Can have only one of 'native', 'strictfp'.",
"(line 1,col 1) 'transient' is not allowed here.",
"(line 1,col 1) 'default' is not allowed here.",
"(line 1,col 1) 'volatile' is not allowed here.",
"(line 1,col 1) 'private' is not allowed here.",
"(line 1,col 1) 'protected' is not allowed here.",
"(line 1,col 1) 'synchronized' is not allowed here.",
"(line 1,col 1) 'native' is not allowed here.",
"(line 1,col 1) 'transitive' is not allowed here.",
"(line 1,col 1) 'static' is not allowed here.");
}
@Test
void nestedClass() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "class I{}}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) Can have only one of 'native', 'strictfp'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void localClass() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "class I{}}}"));
assertProblems(
result,
"(line 1,col 20) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 20) Can have only one of 'final', 'abstract'.",
"(line 1,col 20) Can have only one of 'native', 'strictfp'.",
"(line 1,col 20) 'transient' is not allowed here.",
"(line 1,col 20) 'volatile' is not allowed here.",
"(line 1,col 20) 'default' is not allowed here.",
"(line 1,col 20) 'synchronized' is not allowed here.",
"(line 1,col 20) 'native' is not allowed here.",
"(line 1,col 20) 'transitive' is not allowed here.",
"(line 1,col 20) 'static' is not allowed here.",
"(line 1,col 20) 'public' is not allowed here.",
"(line 1,col 20) 'private' is not allowed here.",
"(line 1,col 20) 'protected' is not allowed here.");
}
@Test
void topInterface() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "interface X{}"));
assertProblems(
result,
"(line 1,col 1) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 1) Can have only one of 'final', 'abstract'.",
"(line 1,col 1) Can have only one of 'native', 'strictfp'.",
"(line 1,col 1) 'transient' is not allowed here.",
"(line 1,col 1) 'volatile' is not allowed here.",
"(line 1,col 1) 'default' is not allowed here.",
"(line 1,col 1) 'synchronized' is not allowed here.",
"(line 1,col 1) 'native' is not allowed here.",
"(line 1,col 1) 'transitive' is not allowed here.",
"(line 1,col 1) 'static' is not allowed here.",
"(line 1,col 1) 'final' is not allowed here.",
"(line 1,col 1) 'private' is not allowed here.",
"(line 1,col 1) 'protected' is not allowed here.");
}
@Test
void nestedInterface() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "interface I{}}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) Can have only one of 'native', 'strictfp'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'final' is not allowed here.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void constructor() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "X(){};}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) Can have only one of 'native', 'strictfp'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'final' is not allowed here.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'abstract' is not allowed here.",
"(line 1,col 9) 'static' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void constructorParameter() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{X(" + allModifiers + " int i){};}"));
assertProblems(
result,
"(line 1,col 11) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 11) Can have only one of 'final', 'abstract'.",
"(line 1,col 11) Can have only one of 'native', 'strictfp'.",
"(line 1,col 11) 'transient' is not allowed here.",
"(line 1,col 11) 'volatile' is not allowed here.",
"(line 1,col 11) 'synchronized' is not allowed here.",
"(line 1,col 11) 'native' is not allowed here.",
"(line 1,col 11) 'strictfp' is not allowed here.",
"(line 1,col 11) 'default' is not allowed here.",
"(line 1,col 11) 'abstract' is not allowed here.",
"(line 1,col 11) 'static' is not allowed here.",
"(line 1,col 11) 'transitive' is not allowed here.",
"(line 1,col 11) 'private' is not allowed here.",
"(line 1,col 11) 'public' is not allowed here.",
"(line 1,col 11) 'protected' is not allowed here.");
}
@Test
void classMethod() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int x(){};}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) Can have only one of 'native', 'strictfp'.",
"(line 1,col 9) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.",
"(line 1,col 9) 'transient' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'volatile' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void interfaceMethod() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}"));
assertProblems(
result,
"(line 1,col 13) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 13) Can have only one of 'final', 'abstract'.",
"(line 1,col 13) Can have only one of 'native', 'strictfp'.",
"(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.",
"(line 1,col 13) 'transient' is not allowed here.",
"(line 1,col 13) 'volatile' is not allowed here.",
"(line 1,col 13) 'default' is not allowed here.",
"(line 1,col 13) 'transitive' is not allowed here.",
"(line 1,col 13) 'private' is not allowed here.",
"(line 1,col 13) 'static' is not allowed here.");
}
@Test
void methodParameter() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{int x(" + allModifiers + " int i){};}"));
assertProblems(
result,
"(line 1,col 15) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 15) Can have only one of 'final', 'abstract'.",
"(line 1,col 15) Can have only one of 'native', 'strictfp'.",
"(line 1,col 15) 'transient' is not allowed here.",
"(line 1,col 15) 'volatile' is not allowed here.",
"(line 1,col 15) 'synchronized' is not allowed here.",
"(line 1,col 15) 'native' is not allowed here.",
"(line 1,col 15) 'strictfp' is not allowed here.",
"(line 1,col 15) 'abstract' is not allowed here.",
"(line 1,col 15) 'default' is not allowed here.",
"(line 1,col 15) 'static' is not allowed here.",
"(line 1,col 15) 'transitive' is not allowed here.",
"(line 1,col 15) 'private' is not allowed here.",
"(line 1,col 15) 'public' is not allowed here.",
"(line 1,col 15) 'protected' is not allowed here.");
}
@Test
void field() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int i;}"));
assertProblems(
result,
"(line 1,col 9) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 9) Can have only one of 'final', 'abstract'.",
"(line 1,col 9) Can have only one of 'native', 'strictfp'.",
"(line 1,col 9) 'synchronized' is not allowed here.",
"(line 1,col 9) 'native' is not allowed here.",
"(line 1,col 9) 'strictfp' is not allowed here.",
"(line 1,col 9) 'default' is not allowed here.",
"(line 1,col 9) 'abstract' is not allowed here.",
"(line 1,col 9) 'transitive' is not allowed here.");
}
@Test
void localVariable() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){" + allModifiers + "int i;}}"));
assertProblems(
result,
"(line 1,col 17) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 17) Can have only one of 'final', 'abstract'.",
"(line 1,col 17) Can have only one of 'native', 'strictfp'.",
"(line 1,col 17) 'transient' is not allowed here.",
"(line 1,col 17) 'volatile' is not allowed here.",
"(line 1,col 17) 'synchronized' is not allowed here.",
"(line 1,col 17) 'native' is not allowed here.",
"(line 1,col 17) 'default' is not allowed here.",
"(line 1,col 17) 'strictfp' is not allowed here.",
"(line 1,col 17) 'abstract' is not allowed here.",
"(line 1,col 17) 'static' is not allowed here.",
"(line 1,col 17) 'transitive' is not allowed here.",
"(line 1,col 17) 'private' is not allowed here.",
"(line 1,col 17) 'public' is not allowed here.",
"(line 1,col 17) 'protected' is not allowed here.");
}
@Test
void catchParameter() {
ParseResult<CompilationUnit> result = javaParser.parse(
COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}"));
assertProblems(
result,
"(line 1,col 29) Can have only one of 'public', 'protected', 'private'.",
"(line 1,col 29) Can have only one of 'final', 'abstract'.",
"(line 1,col 29) Can have only one of 'native', 'strictfp'.",
"(line 1,col 29) 'transient' is not allowed here.",
"(line 1,col 29) 'volatile' is not allowed here.",
"(line 1,col 29) 'synchronized' is not allowed here.",
"(line 1,col 29) 'native' is not allowed here.",
"(line 1,col 29) 'default' is not allowed here.",
"(line 1,col 29) 'strictfp' is not allowed here.",
"(line 1,col 29) 'abstract' is not allowed here.",
"(line 1,col 29) 'static' is not allowed here.",
"(line 1,col 29) 'transitive' is not allowed here.",
"(line 1,col 29) 'private' is not allowed here.",
"(line 1,col 29) 'public' is not allowed here.",
"(line 1,col 29) 'protected' is not allowed here.");
}
@Test
void strictfpNotAllowedAsIdentifier() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int strictfp;"));
assertProblems(result, "(line 1,col 5) 'strictfp' cannot be used as an identifier as it is a keyword.");
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.STATEMENT;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_3;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java1_3ValidatorTest {
public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_3));
@Test
void noAssert() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;"));
assertProblems(
result,
"(line 1,col 1) 'assert' keyword is not supported. Pay attention that this feature is supported starting from 'JAVA_1_4' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParseStart.*;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_1_4;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.utils.TestUtils.assertNoProblems;
import static com.github.javaparser.utils.TestUtils.assertProblems;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.stmt.Statement;
import org.junit.jupiter.api.Test;
class Java1_4ValidatorTest {
public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_4));
@Test
void yesAssert() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;"));
assertNoProblems(result);
}
@Test
void noGenerics() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b;}"));
assertProblems(
result,
"(line 1,col 1) Generics are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.",
"(line 1,col 12) Generics are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void noAnnotations() {
ParseResult<CompilationUnit> result =
javaParser.parse(COMPILATION_UNIT, provider("@Abc @Def() @Ghi(a=3) @interface X{}"));
assertProblems(
result,
"(line 1,col 13) Annotations are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.",
"(line 1,col 1) Annotations are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.",
"(line 1,col 6) Annotations are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void novarargs() {
ParseResult<Parameter> result = javaParser.parse(PARAMETER, provider("String... x"));
assertProblems(
result,
"(line 1,col 1) Varargs are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void noforeach() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(X x: xs){}"));
assertProblems(
result,
"(line 1,col 1) For-each loops are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void staticImport() {
ParseResult<CompilationUnit> result = javaParser.parse(
COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;"));
assertProblems(
result,
"(line 1,col 1) Static imports are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.",
"(line 1,col 17) Static imports are not supported. Pay attention that this feature is supported starting from 'JAVA_5' language level. If you need that feature the language level must be configured in the configuration before parsing the source files.");
}
@Test
void enumAllowedAsIdentifier() {
ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int enum;"));
assertNoProblems(result);
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.validator;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_20;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParserConfiguration;
class Java20ValidatorTest {
private final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_20));
}

Some files were not shown because too many files have changed in this diff Show More