diff options
Diffstat (limited to 'javaparser-testing/src/test/java/com/github/javaparser/ast')
54 files changed, 4646 insertions, 0 deletions
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java new file mode 100644 index 000000000..ec17e39b7 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.JavaParser; +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot; +import static org.junit.Assert.assertEquals; + +public class CompilationUnitTest { + @Test + public 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 + public 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(expected = RuntimeException.class) + public void testGetSourceRootWithBadPackageDeclaration() throws IOException { + 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 + public 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 + public 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 = JavaParser.parse(testFile); + + assertEquals("PrimaryType", cu.getPrimaryTypeName().get()); + } + + @Test + public void testNoPrimaryTypeName() { + CompilationUnit cu = JavaParser.parse("class PrimaryType{}"); + + assertEquals(false, cu.getPrimaryTypeName().isPresent()); + } + @Test + public 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 = JavaParser.parse(testFile); + + assertEquals("PrimaryType", cu.getPrimaryType().get().getNameAsString()); + } + + @Test + public 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 = JavaParser.parse(testFile); + + assertEquals(false, cu.getPrimaryType().isPresent()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java new file mode 100644 index 000000000..91163650a --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.ast.expr.SimpleName; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +public class DataKeyTest { + public static final DataKey<String> ABC = new DataKey<String>() { + }; + public static final DataKey<List<String>> LISTY = new DataKey<List<String>>() { + }; + public static final DataKey<List<String>> DING = new DataKey<List<String>>() { + }; + + @Test + public 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.getData(DING)).isNull(); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java new file mode 100644 index 000000000..8e4d568bd --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java @@ -0,0 +1,329 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.JavaParser; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.expr.Name; +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 org.junit.Test; + +import java.util.Arrays; +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.List; + +import static com.github.javaparser.ast.NodeList.nodeList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class NodeListTest { + + 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)); + } + }; + } + + private FieldDeclaration createIntField(String name) { + return new FieldDeclaration(EnumSet.noneOf(Modifier.class), PrimitiveType.intType(), name); + } + + @Test + public void addAllWithoutIndex() { + List<String> changes = new LinkedList<>(); + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = JavaParser.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 + public void addAllWithIndex() { + List<String> changes = new LinkedList<>(); + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = JavaParser.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 + public void clear() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = JavaParser.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 + public void set() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = JavaParser.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 + public void removeNode() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().remove(cd.getFieldByName("c").get()); + assertEquals(Arrays.asList("'int c;' REMOVAL in list at 2"), changes); + } + + @Test + public void removeFirstNode() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeFirst(); + assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0"), changes); + assertEquals(cd.getMembers().size(), 4); + + for (int i = 3; i >= 0; i--) { + assertTrue(cd.getMembers().removeFirst() != null); + assertEquals(cd.getMembers().size(), i); + } + + assertEquals(cd.getMembers().size(), 0); + } + + @Test + public void removeLastNode() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeLast(); + assertEquals(Arrays.asList("'int e;' REMOVAL in list at 4"), changes); + assertEquals(cd.getMembers().size(), 4); + + for (int i = 3; i >= 0; i--) { + assertTrue(cd.getMembers().removeLast() != null); + assertEquals(cd.getMembers().size(), i); + } + + assertEquals(cd.getMembers().size(), 0); + } + + @Test + public void removeObject() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().remove("hi"); + assertEquals(Arrays.asList(), changes); + } + + @Test + public void removeAll() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.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())); + assertEquals(Arrays.asList("'int b;' REMOVAL in list at 1", + "'int d;' REMOVAL in list at 2"), changes); + } + + @Test + public void retainAll() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.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())); + assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0", + "'int c;' REMOVAL in list at 1", + "'int e;' REMOVAL in list at 2"), changes); + } + + @Test + public void replaceAll() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = JavaParser.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; + }); + assertEquals(Arrays.asList("'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"), changes); + } + + @Test + public void removeIf() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int longName; int c; }"; + CompilationUnit cu = JavaParser.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); + assertEquals(Arrays.asList("'int longName;' REMOVAL in list at 1"), changes); + } + + @Test + public 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")); + + assertEquals(true, replaced); + assertEquals(3, list.size()); + assertEquals("a", list.get(0).asString()); + assertEquals("z", list.get(1).asString()); + assertEquals("c", list.get(2).asString()); + } + + @Test + public void toStringTest() { + final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + assertEquals("[abc, bcd, cde]", list.toString()); + } + + @Test + public void addFirst() { + final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + list.addFirst(new Name("xxx")); + + assertEquals("[xxx, abc, bcd, cde]", list.toString()); + } + + @Test + public void addLast() { + final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + list.addLast(new Name("xxx")); + + assertEquals("[abc, bcd, cde, xxx]", list.toString()); + } + + @Test + public 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("[abc, xxx, bcd, cde]", list.toString()); + } + + @Test + public 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("[abc, bcd, xxx, cde]", list.toString()); + } + + @Test + public 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("[xxx, abc, bcd, cde]", list.toString()); + } + + @Test + public 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("[abc, bcd, cde, xxx]", list.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java new file mode 100644 index 000000000..5ce116de6 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.*; +import org.junit.Test; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public 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 + public void packageProtectedClassShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("class A { }"); + } + + @Test + public void packageProtectedInterfaceShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("interface A { }"); + } + + @Test + public void packageProtectedEnumShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("enum A { }"); + } + + @Test + public void packageProtectedAnnotationShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("@interface A { }"); + } + + @Test + public void packageProtectedFieldShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { int i; }"); + } + + @Test + public void packageProtectedMethodShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { void foo() {} }"); + } + + @Test + public void packageProtectedConstructorShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { A() {} }"); + } + + private void ensureAllNodesHaveValidBeginPosition(final String code) throws IOException { + 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(String.format("There should be no node without a range: %s (class: %s)", + n, n.getClass().getCanonicalName()), n.getRange()); + 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() + ")"); + } + }); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java new file mode 100644 index 000000000..3201b2910 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java @@ -0,0 +1,414 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 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.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +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 org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.JavaParser.parseExpression; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.*; + +public class NodeTest { + + @Test + public 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); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("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"), changes); + } + + @Test + public 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); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + } + + @Test + public 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); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("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"), changes); + + cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0"); + assertEquals(Arrays.asList("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"), changes); + } + + @Test + public 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); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("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"), changes); + + cu.getClassByName("MyCoolClass").get() + .addField("int", "bar") + .getVariables().get(0).setInitializer("0"); + assertEquals(Arrays.asList("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"), changes); + } + + @Test + public 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(); + assertEquals(Arrays.asList("removing [int p] from index 0"), changes); + } + + @Test + public 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 + assertEquals(false, cu.getClassByName("A").get().getName().remove()); + assertEquals(Arrays.asList(), changes); + } + + @Test + public 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); + + assertEquals(true, cu.getClassByName("A").get().getMethodsByName("foo").get(0).getBody().get().remove()); + assertEquals(Arrays.asList("setting [BODY] to null"), changes); + } + + @Test + public void removeOrphanCommentPositiveCase() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A"); + Comment c = new LineComment("A comment"); + decl.addOrphanComment(c); + assertEquals(1, decl.getOrphanComments().size()); + assertTrue(decl == c.getParentNode().get()); + assertTrue(decl.removeOrphanComment(c)); + assertEquals(0, decl.getOrphanComments().size()); + assertFalse(c.getParentNode().isPresent()); + } + + @Test + public void removeOrphanCommentNegativeCase() { + ClassOrInterfaceDeclaration aClass = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A"); + FieldDeclaration aField = new FieldDeclaration(EnumSet.noneOf(Modifier.class), 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 + public void hasJavaDocCommentPositiveCaseWithSetJavaDocComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setJavadocComment("A comment"); + assertEquals(true, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentPositiveCaseWithSetComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new JavadocComment("A comment")); + assertEquals(true, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentNegativeCaseNoComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + assertEquals(false, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentNegativeCaseLineComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new LineComment("foo")); + assertEquals(false, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentNegativeCaseBlockComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new BlockComment("foo")); + assertEquals(false, decl.hasJavaDocComment()); + } + + @Test + public 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", EOL), cu.toString()); + } + + @Test + public 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", EOL)); + // remove the second swapped=false + Node target = unit.getChildNodes().get(0).getChildNodes().get(1).getChildNodes().get(2).getChildNodes().get(2); + target.remove(); + // This will throw an exception if the parents are bad. + System.out.println(unit.toString()); + } + + @Test + public 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 + public 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.findParent(FieldDeclaration.class).get().toString()); + } + + @Test + public void cantFindCompilationUnit() { + VariableDeclarator x = new VariableDeclarator(); + assertFalse(x.findCompilationUnit().isPresent()); + } + + @Test + public void genericWalk() { + Expression e = parseExpression("1+1"); + StringBuilder b = new StringBuilder(); + e.walk(n -> b.append(n.toString())); + assertEquals("1 + 111", b.toString()); + } + + @Test + public 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 + public 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 + public void typeOnlyFindAll() { + Expression e = parseExpression("1+2+3"); + List<IntegerLiteralExpr> ints = e.findAll(IntegerLiteralExpr.class); + assertEquals("[1, 2, 3]", ints.toString()); + } + + @Test + public 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 + public 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 + public void typeOnlyFindFirst() { + Expression e = parseExpression("1+2+3"); + Optional<IntegerLiteralExpr> ints = e.findFirst(IntegerLiteralExpr.class); + assertEquals("Optional[1]", ints.toString()); + } + + @Test + public 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()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java new file mode 100644 index 000000000..45d7725bc --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import org.junit.Test; + +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 com.github.javaparser.utils.Utils.EOL; +import static org.assertj.core.api.Assertions.assertThat; + +public class ParseResultTest { + private final JavaParser javaParser = new JavaParser(new ParserConfiguration()); + + @Test + public 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.getTokens().isPresent()).isTrue(); + + assertThat(result.toString()).isEqualTo("Parsing successful"); + } + + @Test + public 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\" \"provides\" \"requires\" \"strictfp\" \"to\" \"transitive\" \"uses\" \"with\" <IDENTIFIER>"); + assertThat(result.getTokens().isPresent()).isTrue(); + + assertThat(result.toString()).startsWith("Parsing failed:" + EOL + "(line 1,col 1) Parse error."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java new file mode 100644 index 000000000..4e93efce6 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java @@ -0,0 +1,32 @@ +package com.github.javaparser.ast; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.JavaParser.parsePackageDeclaration; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ReplaceNodeTest { + @Test + public 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", EOL), cu.toString()); + } + + @Test + public 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", EOL), cu.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java new file mode 100644 index 000000000..e133b501b --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class AnnotationMemberDeclarationTest { + + @Test + public void whenSettingNameTheParentOfNameIsAssigned() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + assertTrue(name.getParentNode().isPresent()); + assertTrue(decl == name.getParentNode().get()); + } + + @Test + public void removeDefaultValueWhenNoDefaultValueIsPresent() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + + decl.removeDefaultValue(); + + assertFalse(decl.getDefaultValue().isPresent()); + } + + @Test + public 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()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java new file mode 100644 index 000000000..52c77f13c --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java @@ -0,0 +1,60 @@ +package com.github.javaparser.ast.body; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ClassOrInterfaceDeclarationTest { + @Test + public void staticNestedClass() { + CompilationUnit cu = JavaParser.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 + public void nestedInterface() { + CompilationUnit cu = JavaParser.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 + public void nonStaticNestedClass() { + CompilationUnit cu = JavaParser.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 + public void topClass() { + CompilationUnit cu = JavaParser.parse("class X{}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get(); + + assertFalse(y.isInnerClass()); + assertFalse(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + public void localClass() { + MethodDeclaration method= (MethodDeclaration)JavaParser.parseBodyDeclaration("void x(){class X{};}"); + ClassOrInterfaceDeclaration x = method.findFirst(ClassOrInterfaceDeclaration.class).get(); + + assertFalse(x.isInnerClass()); + assertFalse(x.isNestedType()); + assertTrue(x.isLocalClassDeclaration()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java new file mode 100644 index 000000000..34d3b6254 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java @@ -0,0 +1,23 @@ +package com.github.javaparser.ast.body; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.CLASS_BODY; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ConstructorDeclarationTest { + @Test + public void acceptsSuper() { + ConstructorDeclaration cons = new ConstructorDeclaration("Cons"); + cons.createBody().addStatement("super();"); + + assertEquals(String.format("public Cons() {%1$s" + + " super();%1$s" + + "}", EOL), cons.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java new file mode 100644 index 000000000..0e263a481 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java @@ -0,0 +1,24 @@ +package com.github.javaparser.ast.body; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parse; +import static org.junit.Assert.assertEquals; + +public class FieldDeclarationTest { + @Test + public 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()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java new file mode 100644 index 000000000..1cbab66ad --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java @@ -0,0 +1,87 @@ +package com.github.javaparser.ast.body; + +import org.junit.Ignore; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseBodyDeclaration; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; + +public class MethodDeclarationTest { + @Test + public void annotationsAllowedAfterGenericsAndBeforeReturnType() { + parseBodyDeclaration("public <T> @Abc String method() {return null;}"); + } + + @Test + public void annotationsAllowedBeforeGenerics() { + parseBodyDeclaration("public @Abc <T> String method() {return null;}"); + } + + @Test + public 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 + public void explicitReceiverParameters2() { + MethodDeclaration method = parseBodyDeclaration("void x(A this) { }").asMethodDeclaration(); + assertEquals("this", method.getReceiverParameter().get().getNameAsString()); + } + + @Test + public void explicitReceiverParameters3() { + MethodDeclaration method = parseBodyDeclaration("void x(A that) { }").asMethodDeclaration(); + assertFalse(method.getReceiverParameter().isPresent()); + } + + @Test + public void signaturesEqual() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(String z);").asMethodDeclaration(); + assertEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public 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 + public 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 + public void signaturesDifferentName() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int y(String z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signaturesDifferentTypes() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(int z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signaturesDifferentVarargs() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int z);").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(int... z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signatureToString() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int z, String q);").asMethodDeclaration(); + assertEquals("x(int, String)", method1.getSignature().toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java new file mode 100644 index 000000000..946b76ac1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.expr.Name; +import org.junit.Test; + +import java.util.EnumSet; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.JavaParser.parseName; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class CommentTest { + + @Test + public void removeOrphanComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), 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 + public void removeAssociatedComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A"); + Comment c = new LineComment("A comment"); + decl.setComment(c); + assertEquals(true, decl.getComment().isPresent()); + assertTrue(c.remove()); + assertEquals(false, decl.getComment().isPresent()); + } + + @Test + public void cannotRemoveCommentNotUsedAnywhere() { + Comment c = new LineComment("A comment"); + assertFalse(c.remove()); + } + + @Test + public void unicodeEscapesArePreservedInComments() { + CompilationUnit cu = parse("// xxx\\u2122xxx"); + Comment comment = cu.getAllContainedComments().get(0); + assertEquals(" xxx\\u2122xxx", comment.getContent()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java new file mode 100644 index 000000000..55e87f5e5 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java @@ -0,0 +1,12 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class AssignExprTest { + @Test + public void convertOperator() { + assertEquals(BinaryExpr.Operator.PLUS, AssignExpr.Operator.PLUS.toBinaryOperator().get()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java new file mode 100644 index 000000000..9975ef307 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java @@ -0,0 +1,12 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class BinaryExprTest { + @Test + public void convertOperator() { + assertEquals(AssignExpr.Operator.PLUS, BinaryExpr.Operator.PLUS.toAssignOperator().get()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java new file mode 100644 index 000000000..9c5464394 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java @@ -0,0 +1,37 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; + +public class DoubleLiteralExprTest { + @Test + public void test1() { + float x = 0x0.00_00_02p-126f; + parseExpression("0x0.00_00_02p-126f"); + } + + @Test + public void test2() { + double x = 0x0.000_000_000_000_1p-1_022; + parseExpression("0x0.000_000_000_000_1p-1_022"); + } + + @Test + public void test3() { + double a = 0x1.p+1; + parseExpression("0x1.p+1"); + } + + @Test + public void test4() { + double a = 0x.0p0; + parseExpression("0x.0p0"); + } + + @Test + public void test5() { + double x = 0x0_0.0_0p-1_0; + parseExpression("0x0_0.0_0p-1_0"); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java new file mode 100644 index 000000000..0d8a5b9a7 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java @@ -0,0 +1,15 @@ +package com.github.javaparser.ast.expr; + +import com.github.javaparser.JavaParser; +import org.junit.Test; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +public class InstanceOfExprTest { + @Test + public void annotationsOnTheType() { + InstanceOfExpr expr = JavaParser.parseExpression("s instanceof @A @DA String"); + + assertThat(expr.getType().getAnnotations()).containsExactly(new MarkerAnnotationExpr("A"), new MarkerAnnotationExpr("DA")); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java new file mode 100644 index 000000000..082906b15 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java @@ -0,0 +1,41 @@ +package com.github.javaparser.ast.expr; + +import com.github.javaparser.TokenRange; +import com.github.javaparser.ast.Node; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static org.junit.Assert.*; + +public class LambdaExprTest { + @Test + public void lambdaRange1(){ + Expression expression = parseExpression("x -> y"); + assertRange("x", "y", expression); + } + + @Test + public 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 + public void getExpressionBody(){ + LambdaExpr lambdaExpr = parseExpression("x -> y").asLambdaExpr(); + assertEquals("Optional[y]", lambdaExpr.getExpressionBody().toString()); + } + + @Test + public void getNoExpressionBody(){ + LambdaExpr lambdaExpr = parseExpression("x -> {y;}").asLambdaExpr(); + assertEquals("Optional.empty", lambdaExpr.getExpressionBody().toString()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java new file mode 100644 index 000000000..1b9dfef1a --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java @@ -0,0 +1,166 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 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 com.github.javaparser.JavaParser; +import org.assertj.core.data.Percentage; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static org.assertj.core.api.Assertions.assertThat; + +@SuppressWarnings("OctalInteger") +public class LiteralStringValueExprTest { + + @Test + public 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 + public 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 + public 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 + public 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 + public 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 + public 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\'"); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java new file mode 100644 index 000000000..258576420 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java @@ -0,0 +1,22 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static java.util.Optional.empty; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MethodCallExprTest { + + @Test + public 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()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java new file mode 100644 index 000000000..6f0643ba4 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java @@ -0,0 +1,114 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.utils.TestUtils.assertExpressionValid; +import static org.junit.Assert.assertTrue; + +public class MethodReferenceExprTest { + + @Test + public void methodReferenceExprHasAlwaysAScope() { + assertTrue(new MethodReferenceExpr().getScope() != null); + } + + @Test + public void reference1() { + assertExpressionValid("String::length"); + } + + @Test + public void reference2() { + assertExpressionValid("System::currentTimeMillis // static method"); + } + + @Test + public void reference3() { + assertExpressionValid("List<String>::size // explicit type arguments for generic type"); + } + + @Test + public void reference4() { + assertExpressionValid("List::size // inferred type arguments for generic type"); + } + + @Test + public void reference5() { + assertExpressionValid("int[]::clone"); + } + + @Test + public void reference6() { + assertExpressionValid("T::tvarMember"); + } + + @Test + public void reference7() { + assertExpressionValid("System.out::println"); + } + + @Test + public void reference8() { + assertExpressionValid("\"abc\"::length"); + } + + @Test + public void reference9() { + assertExpressionValid("foo[x]::bar"); + } + + @Test + public void reference10() { + assertExpressionValid("(test ? list.replaceAll(String::trim) : list) :: iterator"); + } + + @Test + public void reference10Annotated1() { + assertExpressionValid("(test ? list.replaceAll(@A String::trim) : list) :: iterator"); + } + + @Test + public void reference11() { + assertExpressionValid("String::valueOf // overload resolution needed"); + } + + @Test + public void reference12() { + assertExpressionValid("Arrays::sort // type arguments inferred from context"); + } + + @Test + public void reference13() { + assertExpressionValid("Arrays::<String>sort // explicit type arguments"); + } + + @Test + public void reference14() { + assertExpressionValid("ArrayList<String>::new // constructor for parameterized type"); + } + + @Test + public void reference15() { + assertExpressionValid("ArrayList::new // inferred type arguments"); + } + + @Test + public void reference16() { + assertExpressionValid("Foo::<Integer>new // explicit type arguments"); + } + + @Test + public void reference17() { + assertExpressionValid("Bar<String>::<Integer>new // generic class, generic constructor"); + } + + @Test + public void reference18() { + assertExpressionValid("Outer.Inner::new // inner class constructor"); + } + + @Test + public void reference19() { + assertExpressionValid("int[]::new // array creation"); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java new file mode 100644 index 000000000..6df3a6833 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 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 com.github.javaparser.ParseProblemException; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.Utils.EOL; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.junit.Assert.assertEquals; + +public class NameTest { + @Test + public void outerNameExprIsTheRightMostIdentifier() { + Name name = parseName("a.b.c"); + assertEquals("c", name.getIdentifier()); + } + + @Test + public void parsingAndUnparsingWorks() { + Name name = parseName("a.b.c"); + assertEquals("a.b.c", name.asString()); + } + + @Test(expected = ParseProblemException.class) + public void parsingEmptyNameThrowsException() { + parseName(""); + } + + @Test + public void nameCanHaveAnnotationsInside() { + Name name = parseName("a.@A b. @C c"); + assertEquals("a.b.c", name.asString()); + assertThat(name.getAnnotations()).containsExactly(new MarkerAnnotationExpr("C")); + assertThat(name.getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("A")); + + assertEquals("a.@A b.@C c", name.toString()); + assertEquals("a.@A b.@C c", ConcreteSyntaxModel.genericPrettyPrint(name)); + } + + @Test + public void importName() { + ImportDeclaration importDeclaration = parseImport("import java.@Abc util.List;"); + + assertThat(importDeclaration.getName().getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("Abc")); + + assertEquals("import java.@Abc util.List;" + EOL, importDeclaration.toString()); + assertEquals("import java.@Abc util.List;" + EOL, ConcreteSyntaxModel.genericPrettyPrint(importDeclaration)); + } + + @Test + public void packageName() { + CompilationUnit cu = parse("package @Abc p1.p2;"); + + assertThat(cu.getPackageDeclaration().get().getName().getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("Abc")); + + assertEquals("package @Abc p1.p2;" + EOL + EOL, cu.toString()); + assertEquals("package @Abc p1.p2;" + EOL + EOL, ConcreteSyntaxModel.genericPrettyPrint(cu)); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java new file mode 100644 index 000000000..f7e028563 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 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 org.junit.Test; + +import static com.github.javaparser.JavaParser.parseSimpleName; +import static junit.framework.TestCase.assertEquals; + +public class SimpleNameTest { + + @Test + public void defaultConstructorSetsIdentifierToEmpty() { + assertEquals("empty", new SimpleName().getIdentifier()); + } + + @Test(expected = AssertionError.class) + public void identifierMustNotBeEmpty() { + new SimpleName(""); + } + + @Test(expected = AssertionError.class) + public void identifierMustNotBeNull() { + new SimpleName(null); + } + + @Test + public void unicodeEscapesArePreservedInIdentifiers() { + SimpleName name = parseSimpleName("xxx\\u2122xxx"); + assertEquals("xxx\\u2122xxx", name.asString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java new file mode 100644 index 000000000..50a9bfcfa --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java @@ -0,0 +1,14 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static org.junit.Assert.*; + +public class StringLiteralExprTest { + @Test + public void unicodeEscapesArePreservedInStrings() { + StringLiteralExpr omega = parseExpression("\"xxx\\u03a9xxx\""); + assertEquals("xxx\\u03a9xxx", omega.getValue()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java new file mode 100644 index 000000000..ca821fbe9 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.JavaParser; +import com.github.javaparser.ast.ImportDeclaration; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ImportDeclarationTest { + @Test + public void singleTypeImportDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import a.b.c.X;"); + assertEquals("a.b.c.X", i.getNameAsString()); + } + + @Test + public void typeImportOnDemandDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import a.b.c.D.*;"); + assertEquals("a.b.c.D", i.getName().toString()); + assertEquals("D", i.getName().getIdentifier()); + } + + @Test + public void singleStaticImportDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import static a.b.c.X.def;"); + assertEquals("a.b.c.X", i.getName().getQualifier().get().asString()); + assertEquals("def", i.getName().getIdentifier()); + } + + @Test + public void staticImportOnDemandDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import static a.b.c.X.*;"); + assertEquals("a.b.c.X", i.getNameAsString()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java new file mode 100644 index 000000000..37728e76b --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 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 com.github.javaparser.ast.Modifier; +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.Test; + +import java.util.EnumSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class NodeWithJavadocTest { + + @Test + public void removeJavaDocNegativeCaseNoComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + assertEquals(false, decl.removeJavaDocComment()); + } + + @Test + public void removeJavaDocNegativeCaseCommentNotJavaDoc() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new LineComment("A comment")); + assertEquals(false, decl.removeJavaDocComment()); + assertTrue(decl.getComment().isPresent()); + } + + @Test + public void removeJavaDocPositiveCase() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new JavadocComment("A comment")); + assertEquals(true, decl.removeJavaDocComment()); + assertFalse(decl.getComment().isPresent()); + } + + @Test + public void getJavadocOnMethodWithLineCommentShouldReturnEmptyOptional() { + MethodDeclaration method = new MethodDeclaration(); + method.setLineComment("Lorem Ipsum."); + + assertFalse(method.getJavadocComment().isPresent()); + assertFalse(method.getJavadoc().isPresent()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java new file mode 100644 index 000000000..20c302dd0 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 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 com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +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 com.github.javaparser.ast.observer.AstObserverAdapter; +import com.github.javaparser.ast.observer.ObservableProperty; +import org.junit.Test; + +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.*; + +public class NodeWithModifiersTest { + + @Test + public void addModifierWorks() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.addModifier(Modifier.PUBLIC); + assertEquals(EnumSet.of(Modifier.PUBLIC), decl.getModifiers()); + } + + @Test + public void addModifierTriggerNotification() { + List<String> changes = new LinkedList<>(); + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + 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(Modifier.PUBLIC); + assertEquals(1, changes.size()); + assertEquals("property MODIFIERS is changed to [PUBLIC]", changes.get(0)); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java new file mode 100644 index 000000000..ad7e8bd7e --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java @@ -0,0 +1,28 @@ +package com.github.javaparser.ast.nodeTypes; + +import com.github.javaparser.ast.expr.*; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class NodeWithOptionalScopeTest { + + @Test + public void commonExpressionWhichHaveInterfaceNodeWithOptionalScope() { + NodeWithOptionalScope methodCallExpr = new MethodCallExpr(new NameExpr("A"), "call"); + NodeWithOptionalScope objectCreationExpr = new ObjectCreationExpr(); + + assertTrue(methodCallExpr.getScope().isPresent()); + assertFalse(objectCreationExpr.getScope().isPresent()); + } + + @Test + public void removeScope() { + MethodCallExpr methodCallExpr = new MethodCallExpr(new NameExpr("A"), "method"); + + methodCallExpr.removeScope(); + + assertFalse(methodCallExpr.getScope().isPresent()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java new file mode 100644 index 000000000..59aaf4e63 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java @@ -0,0 +1,23 @@ +package com.github.javaparser.ast.nodeTypes; + +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.MethodCallExpr; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static org.junit.Assert.assertFalse; + +public class NodeWithTraversableScopeTest { + @Test + public 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()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java new file mode 100644 index 000000000..b736333c1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.JavaParser; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static org.junit.Assert.assertEquals; + +public class NodeWithVariablesTest { + + @Test + public void getCommonTypeWorksForNormalVariables() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + assertEquals(PrimitiveType.intType(), declaration.getCommonType()); + } + + @Test + public void getCommonTypeWorksForArrayTypes() { + parseVariableDeclarationExpr("int a[],b[]").getCommonType(); + } + + @Test(expected = AssertionError.class) + public void getCommonTypeFailsOnArrayDifferences() { + parseVariableDeclarationExpr("int a[],b[][]").getCommonType(); + } + + @Test(expected = AssertionError.class) + public void getCommonTypeFailsOnDodgySetterUsage() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + declaration.getVariable(1).setType(String.class); + declaration.getCommonType(); + } + + @Test(expected = AssertionError.class) + public void getCommonTypeFailsOnInvalidEmptyVariableList() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a"); + declaration.getVariables().clear(); + declaration.getCommonType(); + } + + @Test + public void getElementTypeWorksForNormalVariables() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + assertEquals(PrimitiveType.intType(), declaration.getElementType()); + } + + @Test + public void getElementTypeWorksForArrayTypes() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a[],b[]"); + assertEquals(PrimitiveType.intType(), declaration.getElementType()); + } + + @Test + public void getElementTypeIsOkayWithArrayDifferences() { + parseVariableDeclarationExpr("int a[],b[][]").getElementType(); + } + + @Test(expected = AssertionError.class) + public void getElementTypeFailsOnDodgySetterUsage() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + declaration.getVariable(1).setType(String.class); + declaration.getElementType(); + } + + @Test(expected = AssertionError.class) + public void getElementTypeFailsOnInvalidEmptyVariableList() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a"); + declaration.getVariables().clear(); + declaration.getElementType(); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java new file mode 100644 index 000000000..b590f32ab --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.FieldDeclaration; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class PropagatingAstObserverTest { + @Test + public void verifyPropagation() { + String code = "class A { }"; + CompilationUnit cu = JavaParser.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); + assertEquals(true, 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); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java new file mode 100644 index 000000000..5e5976ab8 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java @@ -0,0 +1,21 @@ +package com.github.javaparser.ast.stmt; + +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.NameExpr; +import org.junit.Test; + +public class BlockStmtTest { + @Test + public void issue748AddingIdenticalStatementsDoesParentingRight() { + BlockStmt blockStmt = new BlockStmt(); + Expression exp = new NameExpr("x"); + MethodCallExpr expression = new MethodCallExpr(exp, "y"); + + blockStmt.addStatement(expression); + blockStmt.addStatement(expression.clone()); + // This fails when the issue exists: + String s = blockStmt.toString(); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java new file mode 100644 index 000000000..5775bd049 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java @@ -0,0 +1,37 @@ +package com.github.javaparser.ast.stmt; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.NameExpr; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class IfElseStmtTest { + + @Test + public void issue1247withElseSingleStmt() { + IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond) doSomething(); else doSomethingElse();"); + assertEquals(false, ifStmt.hasElseBlock()); + assertEquals(true, ifStmt.hasElseBranch()); + assertEquals(false, ifStmt.hasCascadingIfStmt()); + } + + @Test + public void issue1247withElseBlockStmt() { + IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond) doSomething(); else { doSomethingElse(); }"); + assertEquals(true, ifStmt.hasElseBlock()); + assertEquals(true, ifStmt.hasElseBranch()); + assertEquals(false, ifStmt.hasCascadingIfStmt()); + } + + @Test + public void issue1247withElseSingleStmtWhichIsAnIf() { + IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond1) doSomething(); else if (cond2) doSomethingElse();"); + assertEquals(false, ifStmt.hasElseBlock()); + assertEquals(true, ifStmt.hasElseBranch()); + assertEquals(true, ifStmt.hasCascadingIfStmt()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java new file mode 100644 index 000000000..1a63b21f7 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java @@ -0,0 +1,81 @@ +package com.github.javaparser.ast.stmt; + +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 com.github.javaparser.ast.validator.Java9Validator; +import org.junit.Test; + +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.Assert.assertTrue; + +public class TryStmtTest { + @Test + public void simpleTest() { + TryStmt tryStmt = parse9("try(Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + } + + @Test + public void multipleTest() { + TryStmt tryStmt = parse9("try(Reader x = new FileReader(); Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void modifiersTest() { + TryStmt tryStmt = parse9("try(final @A Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void simpleVariable() { + TryStmt tryStmt = parse9("try(a){}"); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void twoSimpleVariables() { + TryStmt tryStmt = parse9("try(a;b){}"); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0)); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(1)); + + } + + @Test + public void complexVariable() { + TryStmt tryStmt = parse9("try(a.b.c){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void superAccess() { + TryStmt tryStmt = parse9("try(super.a){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void outerClassAccess() { + TryStmt tryStmt = parse9("try(X.this.a){}"); + assertInstanceOf(FieldAccessExpr.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.toString(), result.isSuccessful()); + return (T) result.getResult().get(); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java new file mode 100644 index 000000000..3fdee8e43 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java @@ -0,0 +1,188 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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 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.Name; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.Utils.EOL; +import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +public class ArrayTypeTest { + @Test + public 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("A"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y"))); + + assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT); + assertThat(fieldDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(fieldDeclaration); + } + + @Test + public 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("A"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y"))); + + assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT); + assertThat(variableDeclarationExpr.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(variableDeclarationExpr); + } + + @Test + public 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("A"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(methodDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(methodDeclaration.getType().getParentNode().get()).isSameAs(methodDeclaration); + } + + @Test + public 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("A"))); + assertThat(innerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(parameter.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(parameter.getType().getParentNode().get()).isSameAs(parameter); + } + + @Test + public 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 int[][] a;", variableDeclarationStatement.toString()); + } + + @Test + public void setFieldDeclarationWithArrays() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[][] a[][];").asFieldDeclaration(); + fieldDeclaration.getVariable(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("Blob[][] a;", fieldDeclaration.toString()); + } + + @Test + public void setMethodDeclarationWithArrays() { + MethodDeclaration method = parseBodyDeclaration("int[][] a()[][] {}").asMethodDeclaration(); + method.setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("Blob[][] a() {" + EOL + "}", method.toString()); + } + + @Test + public void fieldDeclarationWithArraysHasCorrectOrigins() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[] a[];").asFieldDeclaration(); + + Type outerType = fieldDeclaration.getVariables().get(0).getType(); + assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getOrigin()); + assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getComponentType().asArrayType().getOrigin()); + } + + @Test + public void methodDeclarationWithArraysHasCorrectOrigins() { + MethodDeclaration method = (MethodDeclaration) parseBodyDeclaration("int[] a()[] {}"); + + Type outerType = method.getType(); + assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getOrigin()); + assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getComponentType().asArrayType().getOrigin()); + } + + @Test + public 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) {" + EOL + "}", method.toString()); + } + + @Test + public void getArrayCreationType() { + ArrayCreationExpr expr = parseExpression("new int[]"); + ArrayType outerType = expr.createdType().asArrayType(); + Type innerType = outerType.getComponentType(); + assertThat(innerType).isEqualTo(expr.getElementType()); + } + + @Test + public 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)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java new file mode 100644 index 000000000..17244f383 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java @@ -0,0 +1,68 @@ +package com.github.javaparser.ast.type; + +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.Java5Validator; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseType; +import static com.github.javaparser.JavaParser.parseVariableDeclarationExpr; +import static com.github.javaparser.ParseStart.VARIABLE_DECLARATION_EXPR; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static org.junit.Assert.*; + +public class TypeTest { + @Test + public 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(expected = ParseProblemException.class) + public void primitiveTypeArgumentDefaultValidator() { + typeAsString("List<long> x;"); + } + + @Test + public void primitiveTypeArgumentLenientValidator() { + ParserConfiguration config = new ParserConfiguration() + .setLanguageLevel(RAW); + config.getPostProcessors().add(new Java5Validator() {{ + remove(noPrimitiveGenericArguments); + }}.postProcessor()); + + 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 + public 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 + public void issue1251() { + final Type type = parseType("TypeUtilsTest<String>.Tester"); + assertEquals("TypeUtilsTest<String>.Tester", type.toString()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java new file mode 100644 index 000000000..8c2b93568 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java @@ -0,0 +1,108 @@ +package com.github.javaparser.ast.validator; + +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.Ignore; +import org.junit.Test; + +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; + +public class Java10ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10)); + + @Test + public void varAllowedInLocalVariableDeclaration() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a = 5;")); + assertNoProblems(result); + } + + @Test + public void varAllowedInForEach() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a : as){}")); + assertNoProblems(result); + } + + @Test + public void varAllowedInOldFor() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a = 5;a<9;a++){}")); + assertNoProblems(result); + } + + @Test + public void varNotAllowedInCast() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int a = (var)20;")); + assertNoProblems(result); + } + + @Test + public void varNotAllowedInTryWithResources() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(var f = new FileReader(\"\")){ }catch (Exception e){ }")); + assertProblems(result, "(line 1,col 5) \"var\" is not allowed here."); + } + + @Test + public 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 + public void varNotAllowedInTypeArguments() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("new X<var>();")); + assertProblems(result, "(line 1,col 7) \"var\" is not allowed here."); + } + + @Test + public 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 + public void emptyInitializerNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a;")); + assertProblems(result, "(line 1,col 1) \"var\" needs an initializer."); + } + + @Test + public 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 + public 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 + public void arrayDimensionBracketsNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=new String[]{};")); + assertProblems(result, "(line 1,col 1) \"var\" cannot infer array types."); + } + + // This is pretty hard to impossible to implement correctly with just the AST. + @Ignore + @Test + public 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. + @Ignore + @Test + public void polyExpressionAsInitializerNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=new ArrayList<>();")); + assertProblems(result, ""); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java new file mode 100644 index 000000000..1e1f8c0f8 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java @@ -0,0 +1,22 @@ +package com.github.javaparser.ast.validator; + +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.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_11_PREVIEW; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; + +public class Java11ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_11_PREVIEW)); + + @Test + public void varAllowedInLocalVariableDeclaration() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("x((var x, var y) -> x+y);")); + assertNoProblems(result); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java new file mode 100644 index 000000000..7160bcfb9 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java @@ -0,0 +1,98 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.ArrayCreationExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; +import static org.junit.Assert.assertEquals; + +public class Java1_0ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_0)); + + @Test + public void tryWithoutResources() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(X x=new Y()){}")); + assertProblems(result, + "(line 1,col 1) Catch with resource is not supported.", + "(line 1,col 1) Try has no finally and no catch."); + } + + @Test + public 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 + public 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 + public void interfaceWithInitializer() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {{}}")); + assertProblems(result, "(line 1,col 14) An interface cannot have initializers."); + } + + @Test + public 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 + public 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 + public 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."); + } + + @Test + public void leftHandAssignmentCanBeInBraces() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("(i) += (i) += 1")); + assertNoProblems(result); + } + + @Test + public 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."); + } + + @Test + public void noReflection() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class")); + assertProblems(result, "(line 1,col 1) Reflection is not supported."); + } + + @Test + public void nonEmptyList() { + ArrayCreationExpr expr = new ArrayCreationExpr(PrimitiveType.booleanType()); + List<Problem> problems= new ArrayList<>(); + new Java1_0Validator().accept(expr, new ProblemReporter(problems::add)); + assertEquals("ArrayCreationExpr.levels can not be empty.", problems.get(0).getMessage()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java new file mode 100644 index 000000000..6331d9ab1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java @@ -0,0 +1,292 @@ +package com.github.javaparser.ast.validator; + +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.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.EXPRESSION; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public void catchParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}")); + assertProblems(result, + "(line 1,col 144) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 144) Can have only one of 'final', 'abstract'.", + "(line 1,col 144) 'transient' is not allowed here.", + "(line 1,col 144) 'volatile' is not allowed here.", + "(line 1,col 144) 'synchronized' is not allowed here.", + "(line 1,col 144) 'native' is not allowed here.", + "(line 1,col 144) 'default' is not allowed here.", + "(line 1,col 144) 'strictfp' is not allowed here.", + "(line 1,col 144) 'abstract' is not allowed here.", + "(line 1,col 144) 'static' is not allowed here.", + "(line 1,col 144) 'transitive' is not allowed here.", + "(line 1,col 144) 'private' is not allowed here.", + "(line 1,col 144) 'public' is not allowed here.", + "(line 1,col 144) 'protected' is not allowed here." + ); + } + + @Test + public void innerClasses() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}")); + assertNoProblems(result); + } + + @Test + public 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." + ); + } + + @Test + public void reflection() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class")); + assertNoProblems(result); + } + + @Test + public void strictfpAllowedAsIdentifier() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int strictfp;")); + assertNoProblems(result); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java new file mode 100644 index 000000000..3ae7018fe --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java @@ -0,0 +1,275 @@ +package com.github.javaparser.ast.validator; + +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.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public 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 + public void catchParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}")); + assertProblems(result, + "(line 1,col 144) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 144) Can have only one of 'final', 'abstract'.", + "(line 1,col 144) Can have only one of 'native', 'strictfp'.", + "(line 1,col 144) 'transient' is not allowed here.", + "(line 1,col 144) 'volatile' is not allowed here.", + "(line 1,col 144) 'synchronized' is not allowed here.", + "(line 1,col 144) 'native' is not allowed here.", + "(line 1,col 144) 'default' is not allowed here.", + "(line 1,col 144) 'strictfp' is not allowed here.", + "(line 1,col 144) 'abstract' is not allowed here.", + "(line 1,col 144) 'static' is not allowed here.", + "(line 1,col 144) 'transitive' is not allowed here.", + "(line 1,col 144) 'private' is not allowed here.", + "(line 1,col 144) 'public' is not allowed here.", + "(line 1,col 144) 'protected' is not allowed here." + ); + } + + @Test + public 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."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java new file mode 100644 index 000000000..b10114abf --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java @@ -0,0 +1,22 @@ +package com.github.javaparser.ast.validator; + +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.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java1_3ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_3)); + + @Test + public void noAssert() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;")); + assertProblems(result, "(line 1,col 1) 'assert' keyword is not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java new file mode 100644 index 000000000..ed0be99fe --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java @@ -0,0 +1,70 @@ +package com.github.javaparser.ast.validator; + +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.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java1_4ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_4)); + + @Test + public void yesAssert() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;")); + assertNoProblems(result); + } + + @Test + public void noGenerics() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b;}")); + assertProblems(result, + "(line 1,col 12) Generics are not supported.", + "(line 1,col 1) Generics are not supported." + ); + } + + @Test + public void noAnnotations() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("@Abc @Def() @Ghi(a=3) @interface X{}")); + assertProblems(result, + "(line 1,col 6) Annotations are not supported.", + "(line 1,col 13) Annotations are not supported.", + "(line 1,col 1) Annotations are not supported." + ); + } + + @Test + public void novarargs() { + ParseResult<Parameter> result = javaParser.parse(PARAMETER, provider("String... x")); + assertProblems(result, "(line 1,col 1) Varargs are not supported."); + } + + @Test + public 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."); + } + + @Test + public 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 17) Static imports are not supported.", + "(line 1,col 1) Static imports are not supported."); + } + + @Test + public void enumAllowedAsIdentifier() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int enum;")); + assertNoProblems(result); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java new file mode 100644 index 000000000..315167fda --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java @@ -0,0 +1,155 @@ +package com.github.javaparser.ast.validator; + +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.CompilationUnit; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java5ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_5)); + + @Test + public void genericsWithoutDiamond() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b = new ArrayList<>();}")); + assertProblems(result, "(line 1,col 33) The diamond operator is not supported."); + } + + @Test + public void topAnnotationDeclaration() { + 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) 'synchronized' is not allowed here.", + "(line 1,col 1) 'default' 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 + public void nestedAnnotationDeclaration() { + 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 + public void annotationMember() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("@interface X{" + allModifiers + "int x();}")); + assertProblems(result, + "(line 1,col 14) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 14) Can have only one of 'final', 'abstract'.", + "(line 1,col 14) Can have only one of 'native', 'strictfp'.", + "(line 1,col 14) 'transient' is not allowed here.", + "(line 1,col 14) 'volatile' is not allowed here.", + "(line 1,col 14) 'final' is not allowed here.", + "(line 1,col 14) 'synchronized' is not allowed here.", + "(line 1,col 14) 'default' is not allowed here.", + "(line 1,col 14) 'native' is not allowed here.", + "(line 1,col 14) 'protected' is not allowed here.", + "(line 1,col 14) 'private' is not allowed here.", + "(line 1,col 14) 'strictfp' is not allowed here.", + "(line 1,col 14) 'static' is not allowed here.", + "(line 1,col 14) 'transitive' is not allowed here." + ); + } + + @Test + public void topEnum() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "enum 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) 'synchronized' is not allowed here.", + "(line 1,col 1) 'default' 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) 'abstract' 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 + public void nestedEnum() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "enum 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) 'abstract' 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 + public void varargs() { + ParseResult<Parameter> result = javaParser.parse(PARAMETER, provider("String... x")); + assertNoProblems(result); + } + + @Test + public void foreach() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(X x: xs){}")); + assertNoProblems(result); + } + + @Test + public void staticImport() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;")); + assertNoProblems(result); + } + + @Test + public void noPrimitiveTypeArguments() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X extends Y<int> {}")); + assertProblems(result, "(line 1,col 17) Type arguments may not be primitive."); + } + + @Test + public void enumAllowedAsIdentifier() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int enum;")); + assertProblems(result, "(line 1,col 5) 'enum' cannot be used as an identifier as it is a keyword."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java new file mode 100644 index 000000000..d066abe07 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java @@ -0,0 +1,42 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.EXPRESSION; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java6ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_6)); + + @Test + public void noStringsInSwitch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case \"abc\": ;}")); + assertProblems(result, "(line 1,col 16) Strings in switch statements are not supported."); + } + + @Test + public void nobinaryIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("0b01")); + assertProblems(result, "(line 1,col 1) Binary literal values are not supported."); + } + + @Test + public void noUnderscoresInIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("1_000_000")); + assertProblems(result, "(line 1,col 1) Underscores in literal values are not supported."); + } + + @Test + public void noMultiCatch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}")); + assertProblems(result, "(line 1,col 12) Multi-catch is not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java new file mode 100644 index 000000000..a2a03f837 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java @@ -0,0 +1,107 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.UnionType; +import org.junit.Test; + +import java.util.*; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.EXPRESSION; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java7ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_7)); + + @Test + public void generics() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b = new ArrayList<>();}")); + assertNoProblems(result); + } + + @Test + public void defaultMethodWithoutBody() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}")); + assertProblems(result, "(line 1,col 14) 'default' is not allowed here."); + } + + @Test + public void tryWithoutAnything() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}")); + assertProblems(result, "(line 1,col 1) Try has no finally, no catch, and no resources."); + } + + @Test + public void tryWithResourceVariableDeclaration() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(Reader r = new Reader()){}")); + assertNoProblems(result); + } + + @Test + public void tryWithResourceReference() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(a.b.c){}")); + assertProblems(result, "(line 1,col 1) Try with resources only supports variable declarations."); + } + + @Test + public void stringsInSwitch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case \"abc\": ;}")); + assertNoProblems(result); + } + + @Test + public void binaryIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("0b01")); + assertNoProblems(result); + } + + @Test + public void underscoresInIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("1_000_000")); + assertNoProblems(result); + } + + @Test + public void multiCatch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}")); + assertNoProblems(result); + } + + @Test + public void multiCatchWithoutElements() { + UnionType unionType = new UnionType(); + + List<Problem> problems = new ArrayList<>(); + new Java7Validator().accept(unionType, new ProblemReporter(problems::add)); + + assertProblems(problems, "UnionType.elements can not be empty."); + } + + @Test + public void multiCatchWithOneElement() { + UnionType unionType = new UnionType(); + unionType.getElements().add(new ClassOrInterfaceType()); + + List<Problem> problems = new ArrayList<>(); + new Java7Validator().accept(unionType, new ProblemReporter(problems::add)); + + assertProblems(problems, "Union type (multi catch) must have at least two elements."); + } + + @Test + public void noLambdas() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a(() -> 1);")); + assertProblems(result, "(line 1,col 3) Lambdas are not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java new file mode 100644 index 000000000..216fb5b13 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java @@ -0,0 +1,82 @@ +package com.github.javaparser.ast.validator; + +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.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java8ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_8)); + + @Test + public void localInterface() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X {void a(){interface I{}};}")); + assertProblems(result, "(line 1,col 19) There is no such thing as a local interface."); + } + + @Test + public void lambdaParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ a((" + allModifiers + " Integer x) -> 10);}}")); + assertProblems(result, + "(line 1,col 21) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 21) Can have only one of 'final', 'abstract'.", + "(line 1,col 21) Can have only one of 'native', 'strictfp'.", + "(line 1,col 21) 'transient' is not allowed here.", + "(line 1,col 21) 'volatile' is not allowed here.", + "(line 1,col 21) 'synchronized' is not allowed here.", + "(line 1,col 21) 'strictfp' is not allowed here.", + "(line 1,col 21) 'default' is not allowed here.", + "(line 1,col 21) 'native' is not allowed here.", + "(line 1,col 21) 'strictfp' is not allowed here.", + "(line 1,col 21) 'abstract' is not allowed here.", + "(line 1,col 21) 'static' is not allowed here.", + "(line 1,col 21) 'transitive' is not allowed here.", + "(line 1,col 21) 'private' is not allowed here.", + "(line 1,col 21) 'public' is not allowed here.", + "(line 1,col 21) 'protected' is not allowed here." + ); + } + + @Test + public 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) 'transitive' is not allowed here.", + "(line 1,col 13) 'private' is not allowed here." + ); + } + + @Test + public void defaultMethodWithoutBody() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}")); + assertProblems(result, "(line 1,col 14) 'default' methods must have a body."); + } + + @Test + public void lambdas() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a(() -> 1);")); + assertNoProblems(result); + } + + @Test + public void noModules() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}")); + assertProblems(result, "(line 1,col 1) Modules are not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java new file mode 100644 index 000000000..911f6a984 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java @@ -0,0 +1,79 @@ +package com.github.javaparser.ast.validator; + +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.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java9ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + + @Test + public void underscoreIdentifiers() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a.b._.c.d = act(_, _ -> _);")); + assertProblems(result, + "(line 1,col 5) '_' is a reserved keyword.", + "(line 1,col 17) '_' is a reserved keyword.", + "(line 1,col 20) '_' is a reserved keyword.", + "(line 1,col 25) '_' is a reserved keyword." + ); + } + + @Test + public void moduleRequires() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("module x{requires " + allModifiers + " a;}")); + assertProblems(result, + "(line 1,col 10) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 10) Can have only one of 'final', 'abstract'.", + "(line 1,col 10) Can have only one of 'native', 'strictfp'.", + "(line 1,col 10) 'transient' is not allowed here.", + "(line 1,col 10) 'volatile' is not allowed here.", + "(line 1,col 10) 'final' is not allowed here.", + "(line 1,col 10) 'synchronized' is not allowed here.", + "(line 1,col 10) 'default' is not allowed here.", + "(line 1,col 10) 'native' is not allowed here.", + "(line 1,col 10) 'private' is not allowed here.", + "(line 1,col 10) 'protected' is not allowed here.", + "(line 1,col 10) 'strictfp' is not allowed here.", + "(line 1,col 10) 'abstract' is not allowed here.", + "(line 1,col 10) 'public' is not allowed here." + ); + } + + @Test + public 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) 'transitive' is not allowed here." + ); + } + + @Test + public void modules() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}")); + assertNoProblems(result); + } + + @Test + public void tryWithResourceReference() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(a.b.c){}")); + assertNoProblems(result); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java new file mode 100644 index 000000000..e59661170 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.type.Type; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.Iterator; + +import static com.github.javaparser.JavaParser.*; +import static org.junit.Assert.assertEquals; + +public class CloneVisitorTest { + CompilationUnit cu; + + @Before + public void setUp() { + cu = new CompilationUnit(); + } + + @After + public void teardown() { + cu = null; + } + + @Test + public void cloneJavaDocTest() { + NodeList<BodyDeclaration<?>> bodyDeclarationList = new NodeList<>(); + bodyDeclarationList.add(new AnnotationMemberDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new ConstructorDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new EnumConstantDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new FieldDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new InitializerDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new MethodDeclaration().setJavadocComment("javadoc")); + + NodeList<TypeDeclaration<?>> typeDeclarationList = new NodeList<>(); + AnnotationDeclaration annotationDeclaration = new AnnotationDeclaration(); + annotationDeclaration.setName("nnotationDeclarationTest"); + typeDeclarationList.add(annotationDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration2 = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration2.setName("emptyTypeDeclarationTest"); + typeDeclarationList.add(classOrInterfaceDeclaration2.setJavadocComment("javadoc")); + + EnumDeclaration enumDeclaration = new EnumDeclaration(); + enumDeclaration.setName("enumDeclarationTest"); + typeDeclarationList.add(enumDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration.setName("classOrInterfaceDeclarationTest"); + typeDeclarationList.add(classOrInterfaceDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration1 = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration1.setName("emptyTypeDeclarationTest1"); + typeDeclarationList.add(classOrInterfaceDeclaration2.setMembers(bodyDeclarationList)); + + cu.setTypes(typeDeclarationList); + CompilationUnit cuClone = (CompilationUnit) new CloneVisitor().visit(cu, null); + + NodeList<TypeDeclaration<?>> typeDeclarationListClone = cuClone.getTypes(); + Iterator<TypeDeclaration<?>> typeItr = typeDeclarationListClone.iterator(); + TypeDeclaration<?> typeDeclaration; + while (typeItr.hasNext()) { + typeDeclaration = typeItr.next(); + if (typeDeclaration.getMembers() == null) { + assertEquals(typeDeclaration.getComment().get().getContent(), " javadoc"); + } else { + Iterator<BodyDeclaration<?>> bodyItr = typeDeclaration.getMembers().iterator(); + while (bodyItr.hasNext()) { + BodyDeclaration<?> bodyDeclaration = bodyItr.next(); + assertEquals(bodyDeclaration.getComment().get().getContent(), " javadoc"); + } + } + } + } + + @Test + public void cloneAnnotationOnWildcardTypeArgument() { + Type type = parseType("List<@C ? extends Object>").clone(); + assertEquals("List<@C ? extends Object>", type.toString()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java new file mode 100644 index 000000000..679fb1d62 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java @@ -0,0 +1,24 @@ +package com.github.javaparser.ast.visitor; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class HashCodeVisitorTest { + @Test + public void testEquals() { + CompilationUnit p1 = JavaParser.parse("class X { }"); + CompilationUnit p2 = JavaParser.parse("class X { }"); + assertEquals(p1.hashCode(), p2.hashCode()); + } + + @Test + public void testNotEquals() { + CompilationUnit p1 = JavaParser.parse("class X { }"); + CompilationUnit p2 = JavaParser.parse("class Y { }"); + assertNotEquals(p1.hashCode(), p2.hashCode()); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java new file mode 100644 index 000000000..ada0c6f98 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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.visitor; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.BodyDeclaration; +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.StringLiteralExpr; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ModifierVisitorTest { + @Test + public void makeSureParentListsCanBeModified() { + NodeList<StringLiteralExpr> list = new NodeList<>(); + list.add(new StringLiteralExpr("t")); + list.add(new StringLiteralExpr("a")); + list.add(new StringLiteralExpr("b")); + list.add(new StringLiteralExpr("c")); + + list.accept(new ModifierVisitor<Void>() { + @Override + public Visitable visit(final StringLiteralExpr n, final Void arg) { + String v = n.getValue(); + + list.addFirst(new StringLiteralExpr("extra " + v)); + list.remove(new StringLiteralExpr("t")); + + if (v.equals("a")) { + return new StringLiteralExpr("x"); + } + if (v.equals("b")) { + return null; + } + + return n; + } + }, null); + + assertEquals("extra c", list.get(0).getValue()); + assertEquals("extra b", list.get(1).getValue()); + assertEquals("extra a", list.get(2).getValue()); + assertEquals("extra t", list.get(3).getValue()); + assertEquals("x", list.get(4).getValue()); + assertEquals("c", list.get(5).getValue()); + assertEquals(6, list.size()); + } + + @Test + public void binaryExprReturnsLeftExpressionWhenRightSideIsRemoved() { + Expression expression = parseExpression("1+2"); + Visitable result = expression.accept(new ModifierVisitor<Void>() { + public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) { + if (integerLiteralExpr.getValue().equals("1")) { + return null; + } + return integerLiteralExpr; + } + }, null); + assertEquals("2", result.toString()); + } + + @Test + public void binaryExprReturnsRightExpressionWhenLeftSideIsRemoved() { + final Expression expression = parseExpression("1+2"); + final Visitable result = expression.accept(new ModifierVisitor<Void>() { + public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) { + if (integerLiteralExpr.getValue().equals("2")) { + return null; + } + return integerLiteralExpr; + } + }, null); + assertEquals("1", result.toString()); + } + + @Test + public void fieldDeclarationCantSurviveWithoutVariables() { + final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("int x=1;"); + + final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() { + public Visitable visit(VariableDeclarator x, Void arg) { + return null; + } + }, null); + + assertEquals(null, result); + } + + @Test + public void variableDeclarationCantSurviveWithoutVariables() { + final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("void x() {int x=1;}"); + + final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() { + public Visitable visit(VariableDeclarator x, Void arg) { + return null; + } + }, null); + + assertEquals("void x() {" + EOL + "}", result.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java new file mode 100644 index 000000000..1e2cdf810 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java @@ -0,0 +1,54 @@ +/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 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.visitor;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+
+public class NoCommentEqualsVisitorTest {
+
+ @Test
+ public void testEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class X { }");
+ assertTrue(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+
+ @Test
+ public void testEqualsWithDifferentComments() {
+ CompilationUnit p1 = JavaParser.parse("/* a */ class X { /** b */} //c");
+ CompilationUnit p2 = JavaParser.parse("/* b */ class X { } //c");
+ assertTrue(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+
+ @Test
+ public void testNotEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class Y { }");
+ assertFalse(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java new file mode 100644 index 000000000..506566984 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java @@ -0,0 +1,34 @@ +package com.github.javaparser.ast.visitor;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+public class NoCommentHashCodeVisitorTest {
+
+ @Test
+ public void testEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class X { }");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ }
+
+ @Test
+ public void testEqualsWithDifferentComments() {
+ CompilationUnit p1 = JavaParser.parse("/* a */ class X { /** b */} //c");
+ CompilationUnit p2 = JavaParser.parse("/* b */ class X { } //c");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ assertEquals(p1.getComments().size(), 3);
+ assertEquals(p2.getComments().size(), 2);
+ }
+
+ @Test
+ public void testNotEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class Y { }");
+ assertNotEquals(p1.hashCode(), p2.hashCode());
+ }
+}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java new file mode 100644 index 000000000..53d375336 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 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.visitor; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.ArrayInitializerExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol; +import static org.junit.Assert.assertEquals; + +public class TreeVisitorTest { + @Test + public void isValidBreadthFirstTraversal() { + Expression expression = JavaParser.parseExpression("(2+3)+(4+5)"); + + StringBuilder result = new StringBuilder(); + + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }; + + visitor.visitBreadthFirst(expression); + assertEquals("<(2 + 3) + (4 + 5)> <(2 + 3)> <(4 + 5)> <2 + 3> <4 + 5> <2> <3> <4> <5> ", result.toString()); + } + + @Test + public void issue743ConcurrentModificationProblem() { + Expression expression = JavaParser.parseExpression("new int[]{1,2,3,4}"); + + StringBuilder result = new StringBuilder(); + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + result.append("<").append(node).append("> "); + } + }; + visitor.visitPreOrder(expression); + System.out.println(result); + } + + @Test + public void isValidPreOrderTraversal() { + StringBuilder result = new StringBuilder(); + new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }.visitPreOrder(JavaParser.parseExpression("(2+3)+(4+5)")); + assertEquals("<(2 + 3) + (4 + 5)> <(2 + 3)> <2 + 3> <2> <3> <(4 + 5)> <4 + 5> <4> <5> ", result.toString()); + } + + @Test + public void isValidPostOrderTraversal() { + StringBuilder result = new StringBuilder(); + new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }.visitPostOrder(JavaParser.parseExpression("(2+3)+(4+5)")); + assertEquals("<2> <3> <2 + 3> <(2 + 3)> <4> <5> <4 + 5> <(4 + 5)> <(2 + 3) + (4 + 5)> ", result.toString()); + } + + @Test + public void preOrderConcurrentModificationIsOk() { + new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + } + }.visitPreOrder(JavaParser.parseExpression("new int[]{1,2,3,4}")); + } + + @Test + public void postOrderConcurrentModificationIsOk() { + new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + } + }.visitPostOrder(JavaParser.parseExpression("new int[]{1,2,3,4}")); + } + + @Test + public void parents() { + CompilationUnit cu = JavaParser.parse("class X{int x=1;}"); + SimpleName x = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariable(0).getName(); + + Node.ParentsVisitor visitor = new Node.ParentsVisitor(x); + assertEquals("x = 1", visitor.next().toString()); + assertEquals("int x = 1;", visitor.next().toString()); + assertEqualsNoEol("class X {\n" + + "\n" + + " int x = 1;\n" + + "}", visitor.next().toString()); + assertEqualsNoEol("class X {\n" + + "\n" + + " int x = 1;\n" + + "}\n", visitor.next().toString()); + assertEquals(false, visitor.hasNext()); + } + + @Test + public void isValidDirectChildrenTraversal() { + Expression expression = JavaParser.parseExpression("(2+3)+(4+5)"); + + StringBuilder result = new StringBuilder(); + + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }; + + visitor.visitDirectChildren(expression); + assertEquals("<(2 + 3)> <(4 + 5)> ", result.toString()); + } +} |