diff options
Diffstat (limited to 'org.eclipse.jdt.core.tests.model')
28 files changed, 4770 insertions, 336 deletions
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverter15Test.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverter15Test.java index 45021b9ee..90b92ba51 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverter15Test.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverter15Test.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -47,7 +47,7 @@ public class ASTConverter15Test extends ConverterTestSetup { } static { -// TESTS_NUMBERS = new int[] { 340 }; +// TESTS_NUMBERS = new int[] { 342, 343 }; // TESTS_RANGE = new int[] { 325, -1 }; // TESTS_NAMES = new String[] {"test0204"}; } @@ -10915,4 +10915,81 @@ public class ASTConverter15Test extends ConverterTestSetup { assertEquals("Wrong size", "@goto", ((TagElement) tags.get(1)).getTagName()); checkSourceRange((TagElement) tags.get(1), "@goto new position", contents); } + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=300734 + public void test341() throws JavaModelException { + String contents = + "public class Bug300734 {\n" + + " public void foo(String x) {\n" + + " x.getClass();\n" + + " x.getClass();\n" + + " }\n" + + "}"; + this.workingCopy = getWorkingCopy("/Converter15/src/Bug300734.java", true/*resolve*/); + CompilationUnit unit= (CompilationUnit) buildAST( + contents, + this.workingCopy, + true, + false, + true); + MethodDeclaration methodDeclaration = (MethodDeclaration) getASTNode(unit, 0, 0); + IMethodBinding methodBinding1 = ((MethodInvocation) ((ExpressionStatement) methodDeclaration.getBody().statements().get(0)).getExpression()).resolveMethodBinding(); + IMethodBinding methodBinding2 = ((MethodInvocation) ((ExpressionStatement) methodDeclaration.getBody().statements().get(1)).getExpression()).resolveMethodBinding(); + assertTrue("Bindings differ", methodBinding1 == methodBinding2); + } + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304122 + public void test342() throws JavaModelException { + String contents = + "@Deprecated\n" + + "public class X<T> {\n" + + " X<String> field;\n" + + "}"; + this.workingCopy = getWorkingCopy("/Converter15/src/X.java", true/*resolve*/); + CompilationUnit unit= (CompilationUnit) buildAST( + contents, + this.workingCopy, + true, + true, + true); + TypeDeclaration typeDeclaration = (TypeDeclaration) getASTNode(unit, 0); + ITypeBinding binding = typeDeclaration.resolveBinding(); + IAnnotationBinding[] annotations = binding.getAnnotations(); + assertEquals("Wrong size", 1, annotations.length); + FieldDeclaration fieldDeclaration = (FieldDeclaration) getASTNode(unit, 0, 0); + binding = fieldDeclaration.getType().resolveBinding(); + annotations = binding.getAnnotations(); + assertEquals("Wrong size", 1, annotations.length); + } + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304122 + public void test343() throws JavaModelException { + String contents = + "public class X {\n" + + " @Deprecated\n" + + " <T> Object foo(T t) {\n" + + " return t;\n" + + " }\n" + + " public static Object bar() {\n" + + " return new X().<String>foo(\"Hello\");\n" + + " }\n" + + "}"; + this.workingCopy = getWorkingCopy("/Converter15/src/X.java", true/*resolve*/); + CompilationUnit unit= (CompilationUnit) buildAST( + contents, + this.workingCopy, + true, + true, + true); + MethodDeclaration methodDeclaration = (MethodDeclaration) getASTNode(unit, 0, 0); + IMethodBinding binding = methodDeclaration.resolveBinding(); + IAnnotationBinding[] annotations = binding.getAnnotations(); + assertEquals("Wrong size", 1, annotations.length); + methodDeclaration = (MethodDeclaration) getASTNode(unit, 0, 1); + ReturnStatement statement = (ReturnStatement) methodDeclaration.getBody().statements().get(0); + MethodInvocation expression = (MethodInvocation) statement.getExpression(); + binding = expression.resolveMethodBinding(); + annotations = binding.getAnnotations(); + assertEquals("Wrong size", 1, annotations.length); + binding = binding.getMethodDeclaration(); + annotations = binding.getAnnotations(); + assertEquals("Wrong size", 1, annotations.length); + } }
\ No newline at end of file diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverterTestAST3_2.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverterTestAST3_2.java index 9237c91ec..a4a823d68 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverterTestAST3_2.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverterTestAST3_2.java @@ -122,7 +122,7 @@ public class ASTConverterTestAST3_2 extends ConverterTestSetup { static { // TESTS_NAMES = new String[] {"test0602"}; // TESTS_RANGE = new int[] { 713, -1 }; -// TESTS_NUMBERS = new int[] { 718 }; +// TESTS_NUMBERS = new int[] { 653 }; } public static Test suite() { return buildModelTestSuite(ASTConverterTestAST3_2.class); @@ -5287,7 +5287,7 @@ public class ASTConverterTestAST3_2 extends ConverterTestSetup { String source = "public class A {public boolean foo() {}}"; parser.setSource(source.toCharArray()); parser.setProject(getJavaProject("Converter")); - parser.setUnitName("A"); + parser.setUnitName("A.java"); parser.setResolveBindings(true); ASTNode node = parser.createAST(null); assertEquals("not a compilation unit", ASTNode.COMPILATION_UNIT, node.getNodeType()); //$NON-NLS-1$ @@ -8067,6 +8067,8 @@ public class ASTConverterTestAST3_2 extends ConverterTestSetup { FieldAccess fieldAccess = (FieldAccess) expression; IVariableBinding variableBinding = fieldAccess.resolveFieldBinding(); assertNotNull("No variable binding", variableBinding); + IMethodBinding resolveMethodBinding = invocation.resolveMethodBinding(); + assertNotNull("No binding", resolveMethodBinding); } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/BatchASTCreationTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/BatchASTCreationTests.java index 69c8da0a0..7b39f3763 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/BatchASTCreationTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/BatchASTCreationTests.java @@ -32,8 +32,11 @@ import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; +import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.core.tests.util.Util; public class BatchASTCreationTests extends AbstractASTTests { @@ -104,10 +107,10 @@ public class BatchASTCreationTests extends AbstractASTTests { // All specified tests which do not belong to the class are skipped... static { // TESTS_PREFIX = "testBug86380"; -// TESTS_NAMES = new String[] { "test056" }; -// TESTS_NUMBERS = new int[] { 78, 79, 80 }; +// TESTS_NAMES = new String[] { "test072a" }; +// TESTS_NUMBERS = new int[] { 72 }; // TESTS_RANGE = new int[] { 83304, -1 }; - } + } public void setUpSuite() throws Exception { super.setUpSuite(); @@ -1692,7 +1695,7 @@ public class BatchASTCreationTests extends AbstractASTTests { * is not null * (regression test for bug 129804 Local variable bindings from ASTParser#createASTs(.., String[], .., ..) have no declaring method) */ - public void _test072() throws CoreException { + public void test072() throws CoreException { IVariableBinding[] bindings = createVariableBindings( new String[] { "/P/X.java", @@ -1710,6 +1713,49 @@ public class BatchASTCreationTests extends AbstractASTTests { "LX;.m()V", bindings[0].getDeclaringMethod()); } + //https://bugs.eclipse.org/bugs/show_bug.cgi?id=152060 + public void test072a() throws CoreException, IOException { + try { + IJavaProject project = createJavaProject("P072a", new String[] {"src"}, Util.getJavaClassLibs(), "bin", "1.5"); + createFile("/P072a/src/X.java", + "public class X {\n" + + " void m() {\n" + + " Object o;\n" + + " }\n" + + "}"); + final ICompilationUnit compilationUnits[] = new ICompilationUnit[1]; + compilationUnits[0] = getCompilationUnit("P072a", "src", "", "X.java"); + ASTParser parser = ASTParser.newParser(AST.JLS3); + parser.setResolveBindings(true); + parser.setProject(project); + final String[] keys = new String[] { "LX;.m()V#o" }; + final ASTNode[] nodes = new ASTNode[1]; + BindingRequestor bindingRequestor = new BindingRequestor() { + public void acceptAST(ICompilationUnit source, CompilationUnit ast) { + if (compilationUnits[0].equals(source)) { + nodes[0] = ast; + } + } + }; + parser.createASTs( + compilationUnits, + keys, + bindingRequestor, + null); + IBinding[] bindings = bindingRequestor.getBindings(keys); + IBinding binding = bindings[0]; + assertNotNull("Should not be null", binding); + assertEquals("Not a type binding", IBinding.VARIABLE, binding.getKind()); + MethodDeclaration declaration = ((TypeDeclaration)((CompilationUnit) nodes[0]).types().get(0)).getMethods()[0]; + VariableDeclarationFragment fragment = (VariableDeclarationFragment) ((VariableDeclarationStatement) declaration.getBody().statements().get(0)).fragments().get(0); + IVariableBinding resolveBinding = fragment.resolveBinding(); + assertTrue("Not equals", binding.isEqualTo(resolveBinding)); + assertNotNull("No java element", resolveBinding.getJavaElement()); + assertNotNull("No java element", binding.getJavaElement()); + } finally { + deleteProject("P072a"); + } + } // https://bugs.eclipse.org/bugs/show_bug.cgi?id=159631 public void test073() throws CoreException, IOException { @@ -1936,30 +1982,30 @@ public void test079() throws CoreException, IOException { " }\n" + " public void extra() {\n" + " }\n" + - "}"); + "}"); ICompilationUnit compilationUnits[] = new ICompilationUnit[1]; compilationUnits[0] = getCompilationUnit("P079", "src", "test", "Test.java"); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setResolveBindings(true); parser.setProject(project); - final IBinding[] bindings = new IBinding[1]; + final IBinding[] bindings = new IBinding[1]; final String key = "Ltest/Test~ExtraIterator<>;"; parser.createASTs( - compilationUnits, - new String[] { - key - }, - new ASTRequestor() { - public void acceptAST(ICompilationUnit source, CompilationUnit localAst) { - // do nothing - } - public void acceptBinding(String bindingKey, IBinding binding) { - if (key.equals(bindingKey)) { - bindings[0] = binding; - } - } - }, - null); + compilationUnits, + new String[] { + key + }, + new ASTRequestor() { + public void acceptAST(ICompilationUnit source, CompilationUnit localAst) { + // do nothing + } + public void acceptBinding(String bindingKey, IBinding binding) { + if (key.equals(bindingKey)) { + bindings[0] = binding; + } + } + }, + null); IBinding binding = bindings[0]; assertNotNull("Should not be null", binding); assertEquals("Not a type binding", IBinding.TYPE, binding.getKind()); diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterBugsTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterBugsTests.java index ab0587225..678bc405d 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterBugsTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterBugsTests.java @@ -15,10 +15,12 @@ import java.util.Map; import junit.framework.Test; import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jdt.core.formatter.IndentManipulation; import org.eclipse.jdt.internal.formatter.DefaultCodeFormatter; import org.eclipse.jdt.internal.formatter.DefaultCodeFormatterOptions; +import org.eclipse.jdt.internal.formatter.align.Alignment; public class FormatterBugsTests extends FormatterRegressionTests { @@ -65,6 +67,573 @@ public void setUpSuite() throws Exception { } /** + * @bug 27079: [formatter] Tags for disabling/enabling code formatter (feature) + * @test Ensure that the formatter does not format code between specific javadoc comments + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=27079" + */ +public void testBug027079a() throws JavaModelException { + String source = + "public class X01 {\n" + + "\n" + + "/* disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/* enable-formatter */\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X01 {\n" + + "\n" + + " /* disable-formatter */\n" + + " void foo() {\n" + + " // unformatted comment\n" + + " }\n" + + "\n" + + " /* enable-formatter */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079a1() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X01 {\n" + + "\n" + + "/* disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/* enable-formatter */\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X01 {\n" + + "\n" + + "/* disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/* enable-formatter */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079a2() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X01 {\n" + + "\n" + + "/** disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/** enable-formatter */\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X01 {\n" + + "\n" + + "/** disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/** enable-formatter */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079a3() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X01 {\n" + + "\n" + + "// disable-formatter\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "// enable-formatter\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X01 {\n" + + "\n" + + "// disable-formatter\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "// enable-formatter\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079a4() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X01 {\n" + + "\n" + + "// disable-formatter\n" + + "void foo( ) { \n" + + " // unformatted comment \n" + + "}\n" + + "// enable-formatter \n" + + "void bar( ) { \n" + + " // formatted comment \n" + + " /* disable-formatter *//* unformatted comment *//* enable-formatter */\n" + + "}\n" + "}\n"; + formatSource(source, + "public class X01 {\n" + + "\n" + + "// disable-formatter\n" + + "void foo( ) { \n" + + " // unformatted comment \n" + + "}\n" + + "// enable-formatter \n" + + " void bar() {\n" + + " // formatted comment\n" + + " /* disable-formatter *//* unformatted comment *//* enable-formatter */\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079b() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X02 {\n" + + "void foo() {\n" + + "/* disable-formatter */\n" + + " /* unformatted comment */\n" + + " String test1= \"this\"+\n" + + " \"is\"+\n" + + " \"a specific\"+\n" + + " \"line wrapping \";\n" + + "\n" + + "/* enable-formatter */\n" + + " /* formatted comment */\n" + + " String test2= \"this\"+\n" + + " \"is\"+\n" + + " \"a specific\"+\n" + + " \"line wrapping \";\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X02 {\n" + + " void foo() {\n" + + "/* disable-formatter */\n" + + " /* unformatted comment */\n" + + " String test1= \"this\"+\n" + + " \"is\"+\n" + + " \"a specific\"+\n" + + " \"line wrapping \";\n" + + "\n" + + "/* enable-formatter */\n" + + " /* formatted comment */\n" + + " String test2 = \"this\" + \"is\" + \"a specific\" + \"line wrapping \";\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079c() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X03 {\n" + + "void foo() {\n" + + "/* disable-formatter */\n" + + " bar(\n" + + " /** unformatted comment */\n" + + " \"this\" ,\n" + + " \"is\",\n" + + " \"a specific\",\n" + + " \"line wrapping \"\n" + + " );\n" + + "\n" + + "/* enable-formatter */\n" + + " bar(\n" + + " /** formatted comment */\n" + + " \"this\" ,\n" + + " \"is\",\n" + + " \"a specific\",\n" + + " \"line wrapping \"\n" + + " );\n" + + "}\n" + + "void bar(String... str) {}\n" + + "}\n"; + formatSource(source, + "public class X03 {\n" + + " void foo() {\n" + + "/* disable-formatter */\n" + + " bar(\n" + + " /** unformatted comment */\n" + + " \"this\" ,\n" + + " \"is\",\n" + + " \"a specific\",\n" + + " \"line wrapping \"\n" + + " );\n" + + "\n" + + "/* enable-formatter */\n" + + " bar(\n" + + " /** formatted comment */\n" + + " \"this\", \"is\", \"a specific\", \"line wrapping \");\n" + + " }\n" + + "\n" + + " void bar(String... str) {\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079c2() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X03b {\n" + + "void foo() {\n" + + " bar(\n" + + "// disable-formatter\n" + + " /** unformatted comment */\n" + + " \"this\" ,\n" + + " \"is\",\n" + + " \"a specific\",\n" + + " \"line wrapping \"\n" + + "// enable-formatter\n" + + " );\n" + + " bar(\n" + + " /** formatted comment */\n" + + " \"this\" ,\n" + + " \"is\",\n" + + " \"a specific\",\n" + + " \"line wrapping \"\n" + + " );\n" + + "}\n" + + "void bar(String... str) {}\n" + + "}\n"; + formatSource(source, + "public class X03b {\n" + + " void foo() {\n" + + " bar(\n" + + "// disable-formatter\n" + + " /** unformatted comment */\n" + + " \"this\" ,\n" + + " \"is\",\n" + + " \"a specific\",\n" + + " \"line wrapping \"\n" + + "// enable-formatter\n" + + " );\n" + + " bar(\n" + + " /** formatted comment */\n" + + " \"this\", \"is\", \"a specific\", \"line wrapping \");\n" + + " }\n" + + "\n" + + " void bar(String... str) {\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079d() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X04 {\r\n" + + "\r\n" + + "/* disable-formatter */\r\n" + + "void foo( ) { \r\n" + + " // unformatted comment \r\n" + + "}\r\n" + + "/* enable-formatter */\r\n" + + "void bar( ) { \r\n" + + " // formatted comment \r\n" + + "}\r\n" + + "}\r\n"; + formatSource(source, + "public class X04 {\n" + + "\n" + + "/* disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment \n" + + "}\n" + + "/* enable-formatter */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n", + CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, + 0 /* indentation level */, + 0 /* offset */, + -1 /* length (all) */, + "\n", + true/*repeat*/); +} +public void testBug027079d2() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X04b {\n" + + "\n" + + "/* disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment \n" + + "}\n" + + "/* enable-formatter */\n" + + "void bar( ) { \n" + + " // formatted comment \n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X04b {\r\n" + + "\r\n" + + "/* disable-formatter */\r\n" + + "void foo( ) { \r\n" + + " // unformatted comment \r\n" + + "}\r\n" + + "/* enable-formatter */\r\n" + + " void bar() {\r\n" + + " // formatted comment\r\n" + + " }\r\n" + + "}\r\n", + CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, + 0 /* indentation level */, + 0 /* offset */, + -1 /* length (all) */, + "\r\n", + true/*repeat*/); +} +public void testBug027079d3() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X04c {\r\n" + + "\r\n" + + "/* disable-formatter */\r\n" + + "void foo( ) { \r\n" + + " // unformatted comment \r\n" + + "}\r\n" + + "/* enable-formatter */\r\n" + + "void bar( ) { \r\n" + + " // formatted comment \r\n" + + "}\r\n" + + "}\r\n"; + formatSource(source, + "public class X04c {\r\n" + + "\r\n" + + "/* disable-formatter */\r\n" + + "void foo( ) { \r\n" + + " // unformatted comment \r\n" + + "}\r\n" + + "/* enable-formatter */\r\n" + + " void bar() {\r\n" + + " // formatted comment\r\n" + + " }\r\n" + + "}\r\n", + CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, + 0 /* indentation level */, + 0 /* offset */, + -1 /* length (all) */, + "\r\n", + true/*repeat*/); +} +public void testBug027079d4() throws JavaModelException { + this.formatterPrefs.disabling_tag = "disable-formatter".toCharArray(); + this.formatterPrefs.enabling_tag = "enable-formatter".toCharArray(); + String source = + "public class X04d {\n" + + "\n" + + "/* disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment \n" + + "}\n" + + "/* enable-formatter */\n" + + "void bar( ) { \n" + + " // formatted comment \n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X04d {\n" + + "\n" + + "/* disable-formatter */\n" + + "void foo( ) { \n" + + " // unformatted comment \n" + + "}\n" + + "/* enable-formatter */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n", + CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, + 0 /* indentation level */, + 0 /* offset */, + -1 /* length (all) */, + "\n", + true/*repeat*/); +} +public void testBug027079e() throws JavaModelException { + this.formatterPrefs.disabling_tag = "format: off".toCharArray(); + this.formatterPrefs.enabling_tag = "format: on".toCharArray(); + String source = + "public class X05 {\n" + + "\n" + + "/* format: off */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/* format: on */\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X05 {\n" + + "\n" + + "/* format: off */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/* format: on */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079f() throws JavaModelException { + this.formatterPrefs.disabling_tag = "format: off".toCharArray(); + this.formatterPrefs.enabling_tag = "format: on".toCharArray(); + String source = + "public class X06 {\n" + + "\n" + + "// format: off\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "// format: on\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X06 {\n" + + "\n" + + "// format: off\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "// format: on\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079f2() throws JavaModelException { + this.formatterPrefs.disabling_tag = "format: off".toCharArray(); + this.formatterPrefs.enabling_tag = "format: on".toCharArray(); + String source = + "public class X06b {\n" + + "\n" + + "/** format: off */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/** format: on */\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X06b {\n" + + "\n" + + "/** format: off */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "/** format: on */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079f3() throws JavaModelException { + this.formatterPrefs.disabling_tag = " format: off ".toCharArray(); + this.formatterPrefs.enabling_tag = " format: on ".toCharArray(); + String source = + "public class X06c {\n" + + "\n" + + "/* format: off */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "// format: on \n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X06c {\n" + + "\n" + + "/* format: off */\n" + + "void foo( ) { \n" + + " // unformatted comment\n" + + "}\n" + + "// format: on \n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} +public void testBug027079f4() throws JavaModelException { + this.formatterPrefs.disabling_tag = " format: off ".toCharArray(); + this.formatterPrefs.enabling_tag = " format: on ".toCharArray(); + String source = + "public class X06d {\n" + + "\n" + + "/* format: off */\n" + + "void foo( ) { \n" + + " // formatted comment\n" + + "}\n" + + "/* format: on */\n" + + "void bar( ) { \n" + + " // formatted comment\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X06d {\n" + + "\n" + + " /* format: off */\n" + + " void foo() {\n" + + " // formatted comment\n" + + " }\n" + + "\n" + + " /* format: on */\n" + + " void bar() {\n" + + " // formatted comment\n" + + " }\n" + + "}\n" + ); +} + +/** * @bug 198074: [formatter] the code formatter doesn't respect my new lines * @test Ensure that the formatter keep line breaks wrapping set by users in the code * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=198074" @@ -581,6 +1150,360 @@ public void testBug252556() { } /** + * @bug 281655: [formatter] "Never join lines" does not work for annotations. + * @test Verify that "Never join lines" now works for annotations and also that + * element-value pairs are well wrapped using the new formatter option + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=281655" + */ +public void testBug281655() throws JavaModelException { + this.formatterPrefs.join_wrapped_lines = false; + String source = + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", \n" + + " activationConfig = { \n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + "propertyValue = \"0/10 * * * * ?\") \n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\",\n" + + " activationConfig = {\n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + " propertyValue = \"0/10 * * * * ?\")\n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug281655a() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_NO_ALIGNMENT; + String source = + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", \n" + + " activationConfig = { \n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + "propertyValue = \"0/10 * * * * ?\") \n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", activationConfig = { @ActivationConfigProperty(propertyName = \"cronTrigger\", propertyValue = \"0/10 * * * * ?\") })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug281655b() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_COMPACT_SPLIT; + String source = + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", \n" + + " activationConfig = { \n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + "propertyValue = \"0/10 * * * * ?\") \n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MessageDriven(\n" + + " mappedName = \"filiality/SchedulerMQService\",\n" + + " activationConfig = { @ActivationConfigProperty(\n" + + " propertyName = \"cronTrigger\", propertyValue = \"0/10 * * * * ?\") })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug281655c() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + String source = + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", \n" + + " activationConfig = { \n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + "propertyValue = \"0/10 * * * * ?\") \n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MessageDriven(\n" + + " mappedName = \"filiality/SchedulerMQService\",\n" + + " activationConfig = { @ActivationConfigProperty(\n" + + " propertyName = \"cronTrigger\", propertyValue = \"0/10 * * * * ?\") })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug281655d() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_ONE_PER_LINE_SPLIT; + String source = + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", \n" + + " activationConfig = { \n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + "propertyValue = \"0/10 * * * * ?\") \n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MessageDriven(\n" + + " mappedName = \"filiality/SchedulerMQService\",\n" + + " activationConfig = { @ActivationConfigProperty(\n" + + " propertyName = \"cronTrigger\",\n" + + " propertyValue = \"0/10 * * * * ?\") })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug281655e() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_NEXT_SHIFTED_SPLIT; + String source = + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", \n" + + " activationConfig = { \n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + "propertyValue = \"0/10 * * * * ?\") \n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MessageDriven(\n" + + " mappedName = \"filiality/SchedulerMQService\",\n" + + " activationConfig = { @ActivationConfigProperty(\n" + + " propertyName = \"cronTrigger\",\n" + + " propertyValue = \"0/10 * * * * ?\") })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug281655f() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_NEXT_PER_LINE_SPLIT; + String source = + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\", \n" + + " activationConfig = { \n" + + " @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + "propertyValue = \"0/10 * * * * ?\") \n" + + " })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MessageDriven(mappedName = \"filiality/SchedulerMQService\",\n" + + " activationConfig = { @ActivationConfigProperty(propertyName = \"cronTrigger\",\n" + + " propertyValue = \"0/10 * * * * ?\") })\n" + + "@RunAs(\"admin\")\n" + + "@ResourceAdapter(\"quartz-ra.rar\")\n" + + "@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\n" + + "public class X {\n" + + "}\n" + ); +} + +/** + * @bug 282030: [formatter] Java annotation formatting + * @test Verify that element-value pairs are well wrapped using the new formatter option + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=282030" + */ +public void testBug282030() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_COMPACT_SPLIT; + String source = + "@DeclareParents(value =\n" + + "\"com.apress.springrecipes.calculator.ArithmeticCalculatorImpl\", defaultImpl =\n" + + "MaxCalculatorImpl.class) \n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@DeclareParents(\n" + + " value = \"com.apress.springrecipes.calculator.ArithmeticCalculatorImpl\",\n" + + " defaultImpl = MaxCalculatorImpl.class)\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug282030a() throws JavaModelException { + String source = + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\", value3 = \"with several arguments\", value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n"; + formatSource(source, + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\", value3 = \"with several arguments\", value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n" + ); +} +public void testBug282030b() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_COMPACT_SPLIT; + String source = + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\", value3 = \"with several arguments\", value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n"; + formatSource(source, + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\",\n" + + " value3 = \"with several arguments\",\n" + + " value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n" + ); +} +public void testBug282030c() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + String source = + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\", value3 = \"with several arguments\", value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n"; + formatSource(source, + "@MyAnnot(\n" + + " value1 = \"this is an example\", value2 = \"of an annotation\",\n" + + " value3 = \"with several arguments\",\n" + + " value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n" + ); +} +public void testBug282030d() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_ONE_PER_LINE_SPLIT; + String source = + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\", value3 = \"with several arguments\", value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n"; + formatSource(source, + "@MyAnnot(\n" + + " value1 = \"this is an example\",\n" + + " value2 = \"of an annotation\",\n" + + " value3 = \"with several arguments\",\n" + + " value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n" + ); +} +public void testBug282030e() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_NEXT_SHIFTED_SPLIT; + String source = + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\", value3 = \"with several arguments\", value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n"; + formatSource(source, + "@MyAnnot(\n" + + " value1 = \"this is an example\",\n" + + " value2 = \"of an annotation\",\n" + + " value3 = \"with several arguments\",\n" + + " value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n" + ); +} +public void testBug282030f() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_NEXT_PER_LINE_SPLIT; + String source = + "@MyAnnot(value1 = \"this is an example\", value2 = \"of an annotation\", value3 = \"with several arguments\", value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n"; + formatSource(source, + "@MyAnnot(value1 = \"this is an example\",\n" + + " value2 = \"of an annotation\",\n" + + " value3 = \"with several arguments\",\n" + + " value4 = \"which may need to be wrapped\")\n" + + "public class Test {\n" + + "}\n" + ); +} +public void testBug282030g1() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_ONE_PER_LINE_SPLIT; + String source = + "@MyAnnot1(member1 = \"sample1\", member2 = \"sample2\")\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MyAnnot1(member1 = \"sample1\", member2 = \"sample2\")\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug282030g2() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_FORCE; + String source = + "@MyAnnot1(member1 = \"sample1\", member2 = \"sample2\")\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MyAnnot1(\n" + + " member1 = \"sample1\",\n" + + " member2 = \"sample2\")\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug282030h1() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_ONE_PER_LINE_SPLIT; + String source = + "@MyAnnot1(name = \"sample1\", \n" + + " value = { \n" + + " @MyAnnot2(name = \"sample2\",\n" + + "value = \"demo\") \n" + + " })\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MyAnnot1(name = \"sample1\", value = { @MyAnnot2(\n" + + " name = \"sample2\",\n" + + " value = \"demo\") })\n" + + "public class X {\n" + + "}\n" + ); +} +public void testBug282030h2() throws JavaModelException { + this.formatterPrefs.alignment_for_arguments_in_annotation = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_FORCE; + String source = + "@MyAnnot1(name = \"sample1\", \n" + + " value = { \n" + + " @MyAnnot2(name = \"sample2\",\n" + + "value = \"demo\") \n" + + " })\n" + + "public class X {\n" + + "}\n"; + formatSource(source, + "@MyAnnot1(\n" + + " name = \"sample1\",\n" + + " value = { @MyAnnot2(\n" + + " name = \"sample2\",\n" + + " value = \"demo\") })\n" + + "public class X {\n" + + "}\n" + ); +} + +/** * @bug 283467: [formatter] wrong indentation with 'Never join lines' selected * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=283467" */ @@ -622,6 +1545,252 @@ public void testBug283467() throws JavaModelException { } /** + * @bug 284789: [formatter] Does not line-break method declaration exception with parameters + * @test Verify that the new preference to split method declaration works properly + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=284789" + */ +public void testBug284789() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_COMPACT_SPLIT; + String source = + "public class Test {\n" + + "public synchronized List<FantasticallyWonderfulContainer<FantasticallyWonderfulClass>> getMeTheFantasticContainer() {\n" + + " return null;\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class Test {\n" + + " public synchronized\n" + + " List<FantasticallyWonderfulContainer<FantasticallyWonderfulClass>>\n" + + " getMeTheFantasticContainer() {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_01a() throws JavaModelException { + // default is no wrapping for method declaration + String source = + "class X01 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X01 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_01b() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_COMPACT_SPLIT; + String source = + "class X01 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X01 {\n" + + " public final synchronized java.lang.String\n" + + " a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_01c() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + String source = + "class X01 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X01 {\n" + + " public final synchronized\n" + + " java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_01d() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_ONE_PER_LINE_SPLIT; + String source = + "class X01 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X01 {\n" + + " public final synchronized\n" + + " java.lang.String\n" + + " a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_01e() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; + String source = + "class X01 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X01 {\n" + + " public final synchronized\n" + + " java.lang.String\n" + + " a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_01f() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_NEXT_PER_LINE_SPLIT; + String source = + "class X01 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X01 {\n" + + " public final synchronized java.lang.String\n" + + " a_method_which_have_a_very_long_name() {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_02a() throws JavaModelException { + // default is no wrapping for method declaration + String source = + "class X02 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name(String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X02 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name(\n" + + " String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_02b() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_COMPACT_SPLIT; + this.formatterPrefs.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT; + String source = + "class X02 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name(String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X02 {\n" + + " public final synchronized java.lang.String\n" + + " a_method_which_have_a_very_long_name(String first, String second,\n" + + " String third) {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_02c() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + this.formatterPrefs.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + String source = + "class X02 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name(String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X02 {\n" + + " public final synchronized\n" + + " java.lang.String a_method_which_have_a_very_long_name(\n" + + " String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_02d() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_ONE_PER_LINE_SPLIT; + this.formatterPrefs.alignment_for_parameters_in_method_declaration = Alignment.M_ONE_PER_LINE_SPLIT; + String source = + "class X02 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name(String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X02 {\n" + + " public final synchronized\n" + + " java.lang.String\n" + + " a_method_which_have_a_very_long_name(\n" + + " String first,\n" + + " String second,\n" + + " String third) {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_02e() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; + this.formatterPrefs.alignment_for_parameters_in_method_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; + String source = + "class X02 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name(String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X02 {\n" + + " public final synchronized\n" + + " java.lang.String\n" + + " a_method_which_have_a_very_long_name(\n" + + " String first,\n" + + " String second,\n" + + " String third) {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} +public void testBug284789_02f() throws JavaModelException { + this.formatterPrefs.alignment_for_method_declaration = Alignment.M_NEXT_PER_LINE_SPLIT; + this.formatterPrefs.alignment_for_parameters_in_method_declaration = Alignment.M_NEXT_PER_LINE_SPLIT; + String source = + "class X02 {\n" + + " public final synchronized java.lang.String a_method_which_have_a_very_long_name(String first, String second, String third) {\n" + + " return null;\n" + + " }\n" + + "}\n"; + formatSource(source, + "class X02 {\n" + + " public final synchronized java.lang.String\n" + + " a_method_which_have_a_very_long_name(String first,\n" + + " String second,\n" + + " String third) {\n" + + " return null;\n" + + " }\n" + + "}\n" + ); +} + +/** * @bug 285565: [formatter] wrong indentation with 'Never join lines' selected * @test Test to make sure that use either formatter or {@link IndentManipulation} * API methods an indentation set to zero does not thrown any exception. @@ -3928,4 +5097,280 @@ public void testBug298243() { "}\n"; formatSource(source); } + +/** + * @bug 302123: [formatter] AssertionFailedException occurs while formatting a source containing the specific javadoc comment... + * @test Verify that no exception occurs while formatting source including the specific comment + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=302123" + */ +public void testBug302123() { + String source = + "package test;\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s=\"X\"+/** ***/\"Y\";\n" + + " }\n" + + "\n" + + "}\n"; + formatSource(source, + "package test;\n" + + "\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s = \"X\" + /** ***/\n" + + " \"Y\";\n" + + " }\n" + + "\n" + + "}\n" + ); +} +public void testBug302123b() { + String source = + "package test;\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s=\"X\"+/** XXX ***/\"Y\";\n" + + " }\n" + + "\n" + + "}\n"; + formatSource(source, + "package test;\n" + + "\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s = \"X\" + /** XXX ***/\n" + + " \"Y\";\n" + + " }\n" + + "\n" + + "}\n" + ); +} +public void testBug302123c() { + String source = + "package test;\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s=\"X\"+/** ** XXX ** ***/\"Y\";\n" + + " }\n" + + "\n" + + "}\n"; + formatSource(source, + "package test;\n" + + "\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s = \"X\" + /** ** XXX ** ***/\n" + + " \"Y\";\n" + + " }\n" + + "\n" + + "}\n" + ); +} +public void testBug302123d() { + String source = + "package test;\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s=\"X\"+/**AAA *** BBB *** CCC***/\"Y\";\n" + + " }\n" + + "\n" + + "}\n"; + formatSource(source, + "package test;\n" + + "\n" + + "public class Test {\n" + + " public static void main(String[] args) {\n" + + " String s = \"X\" + /** AAA *** BBB *** CCC ***/\n" + + " \"Y\";\n" + + " }\n" + + "\n" + + "}\n" + ); +} + +/** + * @bug 302552: [formatter] Formatting qualified invocations can be broken when the Line Wrapping policy forces element to be on a new line + * @test Verify that wrapping policies forcing the first element to be on a new line are working again... + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=302552" + */ +public void testBug302552_LW0() { + this.formatterPrefs.page_width = 20; + this.formatterPrefs.alignment_for_selector_in_method_invocation = Alignment.M_NO_ALIGNMENT; + String source = + "class Sample2 {int foo(Some a) {return a.getFirst();}}\n"; + formatSource(source, + "class Sample2 {\n" + + " int foo(Some a) {\n" + + " return a.getFirst();\n" + + " }\n" + + "}\n" + ); +} +public void testBug302552_LW1() { + this.formatterPrefs.page_width = 20; + this.formatterPrefs.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT; + String source = + "class Sample2 {int foo(Some a) {return a.getFirst();}}\n"; + formatSource(source, + "class Sample2 {\n" + + " int foo(Some a) {\n" + + " return a.getFirst();\n" + + " }\n" + + "}\n" + ); +} +public void testBug302552_LW2() { + this.formatterPrefs.page_width = 20; + this.formatterPrefs.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + String source = + "class Sample2 {int foo(Some a) {return a.getFirst();}}\n"; + formatSource(source, + "class Sample2 {\n" + + " int foo(Some a) {\n" + + " return a\n" + + " .getFirst();\n" + + " }\n" + + "}\n" + ); +} +public void testBug302552_LW3() { + this.formatterPrefs.page_width = 20; + this.formatterPrefs.alignment_for_selector_in_method_invocation = Alignment.M_ONE_PER_LINE_SPLIT; + String source = + "class Sample2 {int foo(Some a) {return a.getFirst();}}\n"; + formatSource(source, + "class Sample2 {\n" + + " int foo(Some a) {\n" + + " return a\n" + + " .getFirst();\n" + + " }\n" + + "}\n" + ); +} +public void testBug302552_LW4() { + this.formatterPrefs.page_width = 20; + this.formatterPrefs.alignment_for_selector_in_method_invocation = Alignment.M_NEXT_SHIFTED_SPLIT; + String source = + "class Sample2 {int foo(Some a) {return a.getFirst();}}\n"; + formatSource(source, + "class Sample2 {\n" + + " int foo(Some a) {\n" + + " return a\n" + + " .getFirst();\n" + + " }\n" + + "}\n" + ); +} +public void testBug302552_LW5() { + this.formatterPrefs.page_width = 20; + this.formatterPrefs.alignment_for_selector_in_method_invocation = Alignment.M_NEXT_PER_LINE_SPLIT; + String source = + "class Sample2 {int foo(Some a) {return a.getFirst();}}\n"; + formatSource(source, + "class Sample2 {\n" + + " int foo(Some a) {\n" + + " return a.getFirst();\n" + + " }\n" + + "}\n" + ); +} + +/** + * @bug 304529: [formatter] NPE when either the disabling or the enabling tag is not defined + * @test Verify that having an empty disabling or enabling is now accepted by the formatter + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=304529" + */ +public void testBug304529() { + this.formatterPrefs.disabling_tag = "off".toCharArray(); + this.formatterPrefs.enabling_tag = null; + String source = + "/* off */\n" + + "public class X01 {\n" + + "void foo( ) { \n" + + " // unformatted area\n" + + "}\n" + + "}\n"; + formatSource(source); +} +public void testBug304529b() { + this.formatterPrefs.disabling_tag = null; + this.formatterPrefs.enabling_tag = "on".toCharArray(); + String source = + "/* on */\n" + + "public class X01 {\n" + + "void foo( ) { \n" + + " // formatted area\n" + + "}\n" + + "}\n"; + formatSource(source, + "/* on */\n" + + "public class X01 {\n" + + " void foo() {\n" + + " // formatted area\n" + + " }\n" + + "}\n" + ); +} +public void testBug304529c() { + this.formatterPrefs = null; + this.formatterOptions.put(DefaultCodeFormatterConstants.FORMATTER_DISABLING_TAG, "off"); + this.formatterOptions.put(DefaultCodeFormatterConstants.FORMATTER_ENABLING_TAG, ""); + String source = + "/* off */\n" + + "public class X01 {\n" + + "void foo( ) { \n" + + " // unformatted area\n" + + "}\n" + + "}\n"; + formatSource(source); +} +public void testBug304529d() { + this.formatterPrefs = null; + this.formatterOptions.put(DefaultCodeFormatterConstants.FORMATTER_DISABLING_TAG, ""); + this.formatterOptions.put(DefaultCodeFormatterConstants.FORMATTER_ENABLING_TAG, "on"); + String source = + "/* on */\n" + + "public class X01 {\n" + + "void foo( ) { \n" + + " // formatted area\n" + + "}\n" + + "}\n"; + formatSource(source, + "/* on */\n" + + "public class X01 {\n" + + " void foo() {\n" + + " // formatted area\n" + + " }\n" + + "}\n" + ); +} +public void testBug304529e() { + this.formatterPrefs = null; + this.formatterOptions.put(DefaultCodeFormatterConstants.FORMATTER_DISABLING_TAG, "off"); + this.formatterOptions.put(DefaultCodeFormatterConstants.FORMATTER_ENABLING_TAG, "on"); + String source = + "public class X01 {\n" + + "/* off */\n" + + "void foo( ) { \n" + + " // unformatted area\n" + + "}\n" + + "/* on */\n" + + "void bar( ) { \n" + + " // formatted area\n" + + "}\n" + + "}\n"; + formatSource(source, + "public class X01 {\n" + + "/* off */\n" + + "void foo( ) { \n" + + " // unformatted area\n" + + "}\n" + + "/* on */\n" + + " void bar() {\n" + + " // formatted area\n" + + " }\n" + + "}\n" + ); +} + } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsBugsTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsBugsTest.java index fa6a3ad27..6e1542e9f 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsBugsTest.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsBugsTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -2200,8 +2200,6 @@ public void testBug236230d() throws JavaModelException { " return null;\n" + " }\n" + "}\n"; - // TODO (frederic) line comment should be formatted when F_INCLUDE_COMMENTS - // flag will work for all snippet kinds formatSource(source, "/**\n" + " * Need a javadoc comment before to get the exception.\n" + @@ -2213,7 +2211,7 @@ public void testBug236230d() throws JavaModelException { " * If there is an authority, it is:\n" + " * \n" + " * <pre>\n" + - " * //class body snippet\n" + + " * // class body snippet\n" + " * public class X {\n" + " * }\n" + " * </pre>\n" + @@ -2265,6 +2263,142 @@ public void testBug236230f() throws JavaModelException { } /** + * @bug 236406: [formatter] Formatting qualified invocations can be broken when the Line Wrapping policy forces element to be on a new line + * @test Verify that wrapping policies forcing the first element to be on a new line are working again... + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=236406" + */ +public void testBug236406_CDB1() { + String source = + "/** Javadoc comment */void foo1() {System.out.println();}\n" + + "// Line comment \n" + + "void foo2() {System.out.println();}\n" + + "/* Block comment */\n" + + "void foo3() {\n" + + "/* statement Block comment */\n" + + "System.out.println();}\n"; + formatSource(source, + "/** Javadoc comment */\n" + + "void foo1() {\n" + + " System.out.println();\n" + + "}\n" + + "\n" + + "// Line comment \n" + + "void foo2() {\n" + + " System.out.println();\n" + + "}\n" + + "\n" + + "/* Block comment */\n" + + "void foo3() {\n" + + " /* statement Block comment */\n" + + " System.out.println();\n" + + "}", + CodeFormatter.K_CLASS_BODY_DECLARATIONS + ); +} +public void testBug236406_CDB2() { + String source = + "/** Javadoc comment */void foo1() {System.out.println();}\n" + + "// Line comment \n" + + "void foo2() {System.out.println();}\n" + + "/* Block comment */\n" + + "void foo3() {\n" + + "/* statement Block comment */\n" + + "System.out.println();}\n"; + formatSource(source, + "/** Javadoc comment */\n" + + "void foo1() {\n" + + " System.out.println();\n" + + "}\n" + + "\n" + + "// Line comment\n" + + "void foo2() {\n" + + " System.out.println();\n" + + "}\n" + + "\n" + + "/* Block comment */\n" + + "void foo3() {\n" + + " /* statement Block comment */\n" + + " System.out.println();\n" + + "}", + CodeFormatter.K_CLASS_BODY_DECLARATIONS | CodeFormatter.F_INCLUDE_COMMENTS + ); +} +public void testBug236406_EX1() { + String source = + "// Line comment \n" + + "i = \n" + + "/** Javadoc comment */\n" + + "1 + (/* Block comment*/++a)\n"; + formatSource(source, + "// Line comment \n" + + "i =\n" + + "/** Javadoc comment */\n" + + "1 + (/* Block comment*/++a)", + CodeFormatter.K_EXPRESSION + ); +} +public void testBug236406_EX2() { + String source = + "// Line comment \n" + + "i = \n" + + "/** Javadoc comment */\n" + + "1 + (/* Block comment*/++a)\n"; + formatSource(source, + "// Line comment\n" + + "i =\n" + + "/** Javadoc comment */\n" + + "1 + (/* Block comment */++a)", + CodeFormatter.K_EXPRESSION | CodeFormatter.F_INCLUDE_COMMENTS + ); +} +public void testBug236406_ST1() { + String source = + "/** Javadoc comment */foo1();\n" + + "// Line comment \n" + + "foo2();\n" + + "/* Block comment */\n" + + "foo3(); {\n" + + "/* indented Block comment */\n" + + "System.out.println();}\n"; + formatSource(source, + "/** Javadoc comment */\n" + + "foo1();\n" + + "// Line comment \n" + + "foo2();\n" + + "/* Block comment */\n" + + "foo3();\n" + + "{\n" + + " /* indented Block comment */\n" + + " System.out.println();\n" + + "}", + CodeFormatter.K_STATEMENTS + ); +} +public void testBug236406_ST2() { + String source = + "/** Javadoc comment */foo1();\n" + + "// Line comment \n" + + "foo2();\n" + + "/* Block comment */\n" + + "foo3(); {\n" + + "/* indented Block comment */\n" + + "System.out.println();}\n"; + formatSource(source, + "/** Javadoc comment */\n" + + "foo1();\n" + + "// Line comment\n" + + "foo2();\n" + + "/* Block comment */\n" + + "foo3();\n" + + "{\n" + + " /* indented Block comment */\n" + + " System.out.println();\n" + + "}", + CodeFormatter.K_STATEMENTS | CodeFormatter.F_INCLUDE_COMMENTS + ); +} + +/** * @bug 237051: [formatter] Formatter insert blank lines after javadoc if javadoc contains Commons Attributes @@ annotations * @test Ensure that Commons Attributes @@ annotations do not screw up the comment formatter * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=237051" @@ -3487,6 +3621,125 @@ public void testBug241687() throws JavaModelException { } /** + * @bug 251133: [formatter] Automatic formatting single line comments is incoherent among tools + * @test Test the new formatter capability to completely ignore line comments starting at first column + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=251133" + */ +public void testBug251133() throws JavaModelException { + String source = + "public class X01 {\n" + + "// int a = 1;\n" + + "// int b = 2;\n" + + "}"; + formatSource(source, + "public class X01 {\n" + + " // int a = 1;\n" + + " // int b = 2;\n" + + "}" + ); +} +public void testBug251133a() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = true; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = true; + this.formatterPrefs.never_indent_line_comments_on_first_column = false; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source, + "public class X {\n" + + " // first column comment\n" + + "}" + ); +} +public void testBug251133b() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = true; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = true; + this.formatterPrefs.never_indent_line_comments_on_first_column = true; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source, + "public class X {\n" + + "// first column comment\n" + + "}" + ); +} +public void testBug251133c() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = true; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = false; + this.formatterPrefs.never_indent_line_comments_on_first_column = false; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source); +} +public void testBug251133d() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = true; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = false; + this.formatterPrefs.never_indent_line_comments_on_first_column = true; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source); +} +public void testBug251133e() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = false; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = true; + this.formatterPrefs.never_indent_line_comments_on_first_column = false; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source, + "public class X {\n" + + " // first column comment \n" + + "}" + ); +} +public void testBug251133f() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = false; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = true; + this.formatterPrefs.never_indent_line_comments_on_first_column = true; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source, + "public class X {\n" + + "// first column comment \n" + + "}" + ); +} +public void testBug251133g() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = false; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = false; + this.formatterPrefs.never_indent_line_comments_on_first_column = false; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source, + "public class X {\n" + + " // first column comment \n" + + "}" + ); +} +public void testBug251133h() throws JavaModelException { + this.formatterPrefs.comment_format_line_comment = false; + this.formatterPrefs.comment_format_line_comment_starting_on_first_column = false; + this.formatterPrefs.never_indent_line_comments_on_first_column = true; + String source = + "public class X {\n" + + "// first column comment \n" + + "}"; + formatSource(source); +} + +/** * @bug 256799: [formatter] Formatter wrongly adds space to //$FALL-THROUGH$ * @test Ensure that the comment formatter preserve $FALL-THROUGH$ tag leading spaces * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=256799" @@ -4071,8 +4324,7 @@ public void testBug260011_07() throws JavaModelException { "\n" + " /**\n" + " * Returns the change directly associated with this change element or <code\n" + - " * null</code>\n" + - " * if the element isn\'t associated with a change.\n" + + " * null</code> if the element isn\'t associated with a change.\n" + " * \n" + " * @return the change or <code>null</code>\n" + " */\n" + @@ -4398,6 +4650,837 @@ public void testBug260276c() throws JavaModelException { } /** + * @bug 260381: [formatter] Javadoc formatter breaks {@code ...} tags. + * @test Ensure that the @code tag is similar to <code> HTML tag + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=260381" + */ +public void testBug260381() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version {@code The text here should not be formatted.... }\n" + + " */\n" + + "public class X01 {\n" + + "}\n"; + formatSource(source); +} +public void testBug260381a() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version {@code " + + " * The text here should not be formatted.... }\n" + + " */\n" + + "public class X01a {\n" + + "}\n"; + formatSource(source); +} +public void testBug260381b() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version {@code\n" + + " * The text here should not be formatted.... }\n" + + " */\n" + + "public class X01b {\n" + + "}\n"; + formatSource(source, + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version {@code The text here should not be formatted.... }\n" + + " */\n" + + "public class X01b {\n" + + "}\n" + ); +} +public void testBug260381c() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version {@code \n" + + " * \n" + + " \n" + + " * The text here should not be formatted.... }\n" + + " */\n" + + "public class X01c {\n" + + "}\n"; + formatSource(source, + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version {@code \n" + + " * \n" + + " * \n" + + " * The text here should not be formatted.... }\n" + + " */\n" + + "public class X01c {\n" + + "}\n" + ); +} +public void testBug260381d() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version <code> The text here should not be formatted.... </code>\n" + + " */\n" + + "public class X02 {\n" + + "}\n"; + formatSource(source); +} +public void testBug260381e() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version\n" + + " * <code> The text here should not be formatted.... </code>\n" + + " */\n" + + "public class X02b {\n" + + "}\n"; + formatSource(source, + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @version <code> The text here should not be formatted.... </code>\n" + + " */\n" + + "public class X02b {\n" + + "}\n" + ); +} +public void testBug260381f() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @see Object <code> The text here should not be formatted.... </code>\n" + + " */\n" + + "public class X02c {\n" + + "}\n"; + formatSource(source, + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * @author Myself\n" + + " * @see Object\n" + + " * <code> The text here should not be formatted.... </code>\n" + + " */\n" + + "public class X02c {\n" + + "}\n" + ); +} +public void testBug260381g() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * {@code The text here should not be formatted.... }\n" + + " */\n" + + "public class X03 {\n" + + "}\n"; + formatSource(source); +} +public void testBug260381h() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * <code> The text here should \n" + + " * not be formatted.... </code>\n" + + " */\n" + + "public class X03b {\n" + + "}\n"; + formatSource(source); +} +public void testBug260381i() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * {@code The text here should\n" + + " * not be formatted.... }\n" + + " */\n" + + "public class X03c {\n" + + "}\n"; + formatSource(source, + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * {@code The text here should\n" + + " * not be formatted.... }\n" + + " */\n" + + "public class X03c {\n" + + "}\n" + ); +} +public void testBug260381j() throws JavaModelException { + String source = + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * {@code \n" + + " * The text here should\n" + + " * not \n" + + " * be formatted.... }\n" + + " */\n" + + "public class X03d {\n" + + "}\n"; + formatSource(source, + "/**\n" + + " * Comments that can be formated in several lines...\n" + + " * \n" + + " * {@code \n" + + " * The text here should\n" + + " * not \n" + + " * be formatted.... }\n" + + " */\n" + + "public class X03d {\n" + + "}\n" + ); +} +public void testBug260381k() throws JavaModelException { + String source = + "/**\n" + + " * Literal inline tag should also be untouched by the formatter\n" + + " * \n" + + " * @version {@literal The text here should not be formatted.... }\n" + + " */\n" + + "public class X04 {\n" + + "\n" + + "}\n"; + formatSource(source); +} +public void testBug260381_wksp1_01() throws JavaModelException { + String source = + "package wksp1;\n" + + "\n" + + "public interface I01 {\n" + + "\n" + + " /**\n" + + " * Returns all configured content types for the given source viewer. This list\n" + + " * tells the caller which content types must be configured for the given source \n" + + " * viewer, i.e. for which content types the given source viewer\'s functionalities\n" + + " * must be specified. This implementation always returns <code>\n" + + " * new String[] { IDocument.DEFAULT_CONTENT_TYPE }</code>.\n" + + " *\n" + + " * @param source the source viewer to be configured by this configuration\n" + + " * @return the configured content types for the given viewer\n" + + " */\n" + + " public String[] getConfiguredContentTypes(String source);\n" + + "}\n"; + formatSource(source, + "package wksp1;\n" + + "\n" + + "public interface I01 {\n" + + "\n" + + " /**\n" + + " * Returns all configured content types for the given source viewer. This\n" + + " * list tells the caller which content types must be configured for the\n" + + " * given source viewer, i.e. for which content types the given source\n" + + " * viewer\'s functionalities must be specified. This implementation always\n" + + " * returns <code>\n" + + " * new String[] { IDocument.DEFAULT_CONTENT_TYPE }</code>.\n" + + " * \n" + + " * @param source\n" + + " * the source viewer to be configured by this configuration\n" + + " * @return the configured content types for the given viewer\n" + + " */\n" + + " public String[] getConfiguredContentTypes(String source);\n" + + "}\n" + ); +} +public void testBug260381_wksp2_01() throws JavaModelException { + String source = + "package wksp2;\n" + + "public interface I01 {\n" + + " /**\n" + + " * Returns the composition of two functions. For {@code f: A->B} and\n" + + " * {@code g: B->C}, composition is defined as the function h such that\n" + + " * {@code h(a) == g(f(a))} for each {@code a}.\n" + + " *\n" + + " * @see <a href=\"//en.wikipedia.org/wiki/Function_composition\">\n" + + " * function composition</a>\n" + + " *\n" + + " * @param g the second function to apply\n" + + " * @param f the first function to apply\n" + + " * @return the composition of {@code f} and {@code g}\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I01 {\n" + + " /**\n" + + " * Returns the composition of two functions. For {@code f: A->B} and\n" + + " * {@code g: B->C}, composition is defined as the function h such that\n" + + " * {@code h(a) == g(f(a))} for each {@code a}.\n" + + " * \n" + + " * @see <a href=\"//en.wikipedia.org/wiki/Function_composition\"> function\n" + + " * composition</a>\n" + + " * \n" + + " * @param g\n" + + " * the second function to apply\n" + + " * @param f\n" + + " * the first function to apply\n" + + " * @return the composition of {@code f} and {@code g}\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_01b() throws JavaModelException { + String source = + "package wksp2;\n" + + "public interface I01b {\n" + + " /**\n" + + " * Returns the composition of two functions. For <code> f: A->B</code> and\n" + + " * <code> g: B->C</code>, composition is defined as the function h such that\n" + + " * <code> h(a) == g(f(a))</code> for each <code> a</code>.\n" + + " *\n" + + " * @see <a href=\"//en.wikipedia.org/wiki/Function_composition\">\n" + + " * function composition</a>\n" + + " *\n" + + " * @param g the second function to apply\n" + + " * @param f the first function to apply\n" + + " * @return the composition of <code> f</code> and <code> g</code>\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I01b {\n" + + " /**\n" + + " * Returns the composition of two functions. For <code> f: A->B</code> and\n" + + " * <code> g: B->C</code>, composition is defined as the function h such that\n" + + " * <code> h(a) == g(f(a))</code> for each <code> a</code>.\n" + + " * \n" + + " * @see <a href=\"//en.wikipedia.org/wiki/Function_composition\"> function\n" + + " * composition</a>\n" + + " * \n" + + " * @param g\n" + + " * the second function to apply\n" + + " * @param f\n" + + " * the first function to apply\n" + + " * @return the composition of <code> f</code> and <code> g</code>\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_01c() throws JavaModelException { + String source = + "package wksp2;\n" + + "public interface I01c {\n" + + " /**\n" + + " * Returns the composition of two functions. For <code> f: A->B</code> and\n" + + " * <code>\n" + + " * g: B->C\n" + + " * </code>,\n" + + " * composition is defined as the function h such that\n" + + " * <code>\n" + + " * h(a) == g(f(a))\n" + + " * </code>\n" + + " * for each\n" + + " * <code>\n" + + " * a\n" + + " * </code>.\n" + + " *\n" + + " * @see <a href=\"//en.wikipedia.org/wiki/Function_composition\">\n" + + " * function composition</a>\n" + + " *\n" + + " * @param g the second function to apply\n" + + " * @param f the first function to apply\n" + + " * @return the composition of <code> f</code> and <code> g</code>\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I01c {\n" + + " /**\n" + + " * Returns the composition of two functions. For <code> f: A->B</code> and\n" + + " * <code>\n" + + " * g: B->C\n" + + " * </code>, composition is defined as the function h such that <code>\n" + + " * h(a) == g(f(a))\n" + + " * </code> for each <code>\n" + + " * a\n" + + " * </code>.\n" + + " * \n" + + " * @see <a href=\"//en.wikipedia.org/wiki/Function_composition\"> function\n" + + " * composition</a>\n" + + " * \n" + + " * @param g\n" + + " * the second function to apply\n" + + " * @param f\n" + + " * the first function to apply\n" + + " * @return the composition of <code> f</code> and <code> g</code>\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_02() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I02 {\n" + + "\n" + + " /**\n" + + " * Implementations of {@code computeNext} <b>must</b> invoke this method when\n" + + " * there are no elements left in the iteration.\n" + + " *\n" + + " * @return {@code null}; a convenience so your {@link #computeNext}\n" + + " * implementation can use the simple statement {@code return endOfData();}\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I02 {\n" + + "\n" + + " /**\n" + + " * Implementations of {@code computeNext} <b>must</b> invoke this method\n" + + " * when there are no elements left in the iteration.\n" + + " * \n" + + " * @return {@code null}; a convenience so your {@link #computeNext}\n" + + " * implementation can use the simple statement\n" + + " * {@code return endOfData();}\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_03() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I03 {\n" + + " /**\n" + + " * A builder for creating immutable bimap instances, especially {@code public\n" + + " * static final} bimaps (\"constant bimaps\"). Example: <pre> {@code\n" + + " *\n" + + " * static final ImmutableBiMap<String, Integer> WORD_TO_INT =\n" + + " * new ImmutableBiMap.Builder<String, Integer>()\n" + + " * .put(\"one\", 1)\n" + + " * .put(\"two\", 2)\n" + + " * .put(\"three\", 3)\n" + + " * .build();}</pre>\n" + + " *\n" + + " * For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods\n" + + " * are even more convenient.\n" + + " *\n" + + " * <p>Builder instances can be reused - it is safe to call {@link #build}\n" + + " * multiple times to build multiple bimaps in series. Each bimap is a superset\n" + + " * of the bimaps created before it.\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I03 {\n" + + " /**\n" + + " * A builder for creating immutable bimap instances, especially\n" + + " * {@code public\n" + + " * static final} bimaps (\"constant bimaps\"). Example:\n" + + " * \n" + + " * <pre>\n" + + " * {\n" + + " * @code\n" + + " * static final ImmutableBiMap<String, Integer> WORD_TO_INT = new ImmutableBiMap.Builder<String, Integer>()\n" + + " * .put("one", 1).put("two", 2).put("three", 3).build();\n" + + " * }\n" + + " * </pre>\n" + + " * \n" + + " * For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()}\n" + + " * methods are even more convenient.\n" + + " * \n" + + " * <p>\n" + + " * Builder instances can be reused - it is safe to call {@link #build}\n" + + " * multiple times to build multiple bimaps in series. Each bimap is a\n" + + " * superset of the bimaps created before it.\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_03b() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I03b {\n" + + " /**\n" + + " * A builder for creating immutable bimap instances, xxxxxxxx {@code public\n" + + " * static final} bimaps (\"constant bimaps\").\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I03b {\n" + + " /**\n" + + " * A builder for creating immutable bimap instances, xxxxxxxx {@code public\n" + + " * static final} bimaps (\"constant bimaps\").\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_04() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I04 {\n" + + "\n" + + " /**\n" + + " * Returns an immutable multiset containing the given elements.\n" + + " * \n" + + " * <p>The multiset is ordered by the first occurrence of each element. For\n" + + " * example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields\n" + + " * a multiset with elements in the order {@code 2, 3, 3, 1}.\n" + + " *\n" + + " * <p>Note that if {@code c} is a {@code Collection<String>}, then {@code\n" + + " * ImmutableMultiset.copyOf(c)} returns an {@code ImmutableMultiset<String>}\n" + + " * containing each of the strings in {@code c}, while\n" + + " * {@code ImmutableMultiset.of(c)} returns an\n" + + " * {@code ImmutableMultiset<Collection<String>>} containing one element\n" + + " * (the given collection itself).\n" + + " *\n" + + " * <p><b>Note:</b> Despite what the method name suggests, if {@code elements}\n" + + " * is an {@code ImmutableMultiset}, no copy will actually be performed, and\n" + + " * the given multiset itself will be returned.\n" + + " *\n" + + " * @throws NullPointerException if any of {@code elements} is null\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I04 {\n" + + "\n" + + " /**\n" + + " * Returns an immutable multiset containing the given elements.\n" + + " * \n" + + " * <p>\n" + + " * The multiset is ordered by the first occurrence of each element. For\n" + + " * example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))}\n" + + " * yields a multiset with elements in the order {@code 2, 3, 3, 1}.\n" + + " * \n" + + " * <p>\n" + + " * Note that if {@code c} is a {@code Collection<String>}, then\n" + + " * {@code ImmutableMultiset.copyOf(c)} returns an\n" + + " * {@code ImmutableMultiset<String>} containing each of the strings in\n" + + " * {@code c}, while {@code ImmutableMultiset.of(c)} returns an\n" + + " * {@code ImmutableMultiset<Collection<String>>} containing one element (the\n" + + " * given collection itself).\n" + + " * \n" + + " * <p>\n" + + " * <b>Note:</b> Despite what the method name suggests, if {@code elements}\n" + + " * is an {@code ImmutableMultiset}, no copy will actually be performed, and\n" + + " * the given multiset itself will be returned.\n" + + " * \n" + + " * @throws NullPointerException\n" + + " * if any of {@code elements} is null\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_05() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I05 {\n" + + "\n" + + " /**\n" + + " * Indexes the specified values into a {@code Multimap} by applying a\n" + + " * specified function to each item in an {@code Iterable} of values. Each\n" + + " * value will be stored as a value in the specified multimap. The key used to\n" + + " * store that value in the multimap will be the result of calling the function\n" + + " * on that value. Depending on the multimap implementation, duplicate entries\n" + + " * (equal keys and equal values) may be collapsed.\n" + + " *\n" + + " * <p>For example,\n" + + " *\n" + + " * <pre class=\"code\">\n" + + " * List<String> badGuys =\n" + + " * Arrays.asList(\"Inky\", \"Blinky\", \"Pinky\", \"Pinky\", \"Clyde\");\n" + + " * Function<String, Integer> stringLengthFunction = ...;\n" + + " * Multimap<Integer, String> index = Multimaps.newHashMultimap();\n" + + " * Multimaps.index(badGuys, stringLengthFunction, index);\n" + + " * System.out.println(index); </pre>\n" + + " *\n" + + " * prints\n" + + " *\n" + + " * <pre class=\"code\">\n" + + " * {4=[Inky], 5=[Pinky, Clyde], 6=[Blinky]} </pre>\n" + + " *\n" + + " * The {@link HashMultimap} collapses the duplicate occurrence of\n" + + " * {@code (5, \"Pinky\")}.\n" + + " *\n" + + " * @param values the values to add to the multimap\n" + + " * @param keyFunction the function used to produce the key for each value\n" + + " * @param multimap the multimap to store the key value pairs\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I05 {\n" + + "\n" + + " /**\n" + + " * Indexes the specified values into a {@code Multimap} by applying a\n" + + " * specified function to each item in an {@code Iterable} of values. Each\n" + + " * value will be stored as a value in the specified multimap. The key used\n" + + " * to store that value in the multimap will be the result of calling the\n" + + " * function on that value. Depending on the multimap implementation,\n" + + " * duplicate entries (equal keys and equal values) may be collapsed.\n" + + " * \n" + + " * <p>\n" + + " * For example,\n" + + " * \n" + + " * <pre class=\"code\">\n" + + " * List<String> badGuys =\n" + + " * Arrays.asList(\"Inky\", \"Blinky\", \"Pinky\", \"Pinky\", \"Clyde\");\n" + + " * Function<String, Integer> stringLengthFunction = ...;\n" + + " * Multimap<Integer, String> index = Multimaps.newHashMultimap();\n" + + " * Multimaps.index(badGuys, stringLengthFunction, index);\n" + + " * System.out.println(index);\n" + + " * </pre>\n" + + " * \n" + + " * prints\n" + + " * \n" + + " * <pre class=\"code\">\n" + + " * {4=[Inky], 5=[Pinky, Clyde], 6=[Blinky]}\n" + + " * </pre>\n" + + " * \n" + + " * The {@link HashMultimap} collapses the duplicate occurrence of\n" + + " * {@code (5, \"Pinky\")}.\n" + + " * \n" + + " * @param values\n" + + " * the values to add to the multimap\n" + + " * @param keyFunction\n" + + " * the function used to produce the key for each value\n" + + " * @param multimap\n" + + " * the multimap to store the key value pairs\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_06() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I06 {\n" + + "\n" + + " /**\n" + + " * Adds a number of occurrences of an element to this multiset. Note that if\n" + + " * {@code occurrences == 1}, this method has the identical effect to {@link\n" + + " * #add(Object)}. This method is functionally equivalent (except in the case\n" + + " * of overflow) to the call {@code addAll(Collections.nCopies(element,\n" + + " * occurrences))}, which would presumably perform much more poorly.\n" + + " *\n" + + " * @param element the element to add occurrences of; may be {@code null} only\n" + + " * if explicitly allowed by the implementation\n" + + " * @param occurrences the number of occurrences of this element to add. May\n" + + " * be zero, in which case no change will be made.\n" + + " * @return the previous count of this element before the operation; possibly\n" + + " * zero - TODO: make this the actual behavior!\n" + + " * @throws IllegalArgumentException if {@code occurrences} is negative, or if\n" + + " * this operation would result in more than {@link Integer#MAX_VALUE}\n" + + " * occurrences of the element \n" + + " * @throws NullPointerException if {@code element} is null and this\n" + + " * implementation does not permit null elements. Note that if {@code\n" + + " * occurrences} is zero, the implementation may opt to return normally.\n" + + " */\n" + + " boolean /*int*/ add(E element, int occurrences);\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I06 {\n" + + "\n" + + " /**\n" + + " * Adds a number of occurrences of an element to this multiset. Note that if\n" + + " * {@code occurrences == 1}, this method has the identical effect to\n" + + " * {@link #add(Object)}. This method is functionally equivalent (except in\n" + + " * the case of overflow) to the call\n" + + " * {@code addAll(Collections.nCopies(element,\n" + + " * occurrences))}, which would presumably perform much more poorly.\n" + + " * \n" + + " * @param element\n" + + " * the element to add occurrences of; may be {@code null} only if\n" + + " * explicitly allowed by the implementation\n" + + " * @param occurrences\n" + + " * the number of occurrences of this element to add. May be zero,\n" + + " * in which case no change will be made.\n" + + " * @return the previous count of this element before the operation; possibly\n" + + " * zero - TODO: make this the actual behavior!\n" + + " * @throws IllegalArgumentException\n" + + " * if {@code occurrences} is negative, or if this operation\n" + + " * would result in more than {@link Integer#MAX_VALUE}\n" + + " * occurrences of the element\n" + + " * @throws NullPointerException\n" + + " * if {@code element} is null and this implementation does not\n" + + " * permit null elements. Note that if {@code occurrences} is\n" + + " * zero, the implementation may opt to return normally.\n" + + " */\n" + + " boolean /* int */add(E element, int occurrences);\n" + + "}\n" + ); +} +public void testBug260381_wksp2_07() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I07 {\n" + + "\n" + + " /**\n" + + " * Constructs a new, empty multiset, sorted according to the specified\n" + + " * comparator. All elements inserted into the multiset must be <i>mutually\n" + + " * comparable</i> by the specified comparator: {@code comparator.compare(e1,\n" + + " * e2)} must not throw a {@code ClassCastException} for any elements {@code\n" + + " * e1} and {@code e2} in the multiset. If the user attempts to add an element\n" + + " * to the multiset that violates this constraint, the {@code add(Object)} call\n" + + " * will throw a {@code ClassCastException}.\n" + + " *\n" + + " * @param comparator the comparator that will be used to sort this multiset. A\n" + + " * null value indicates that the elements\' <i>natural ordering</i> should\n" + + " * be used.\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I07 {\n" + + "\n" + + " /**\n" + + " * Constructs a new, empty multiset, sorted according to the specified\n" + + " * comparator. All elements inserted into the multiset must be <i>mutually\n" + + " * comparable</i> by the specified comparator: {@code comparator.compare(e1,\n" + + " * e2)} must not throw a {@code ClassCastException} for any elements\n" + + " * {@code e1} and {@code e2} in the multiset. If the user attempts to add an\n" + + " * element to the multiset that violates this constraint, the\n" + + " * {@code add(Object)} call will throw a {@code ClassCastException}.\n" + + " * \n" + + " * @param comparator\n" + + " * the comparator that will be used to sort this multiset. A null\n" + + " * value indicates that the elements\' <i>natural ordering</i>\n" + + " * should be used.\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_08() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "public interface I08 {\n" + + "\n" + + " /**\n" + + " * Returns the composition of a function and a predicate. For every {@code x},\n" + + " * the generated predicate returns {@code predicate(function(x))}.\n" + + " *\n" + + " * @return the composition of the provided function and predicate\n" + + " */\n" + + " void foo();\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "public interface I08 {\n" + + "\n" + + " /**\n" + + " * Returns the composition of a function and a predicate. For every\n" + + " * {@code x}, the generated predicate returns {@code predicate(function(x))}\n" + + " * .\n" + + " * \n" + + " * @return the composition of the provided function and predicate\n" + + " */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug260381_wksp2_09() throws JavaModelException { + String source = + "package wksp2;\n" + + "\n" + + "/**\n" + + " A Conditional represents an if/then/else block.\n" + + " When this is created the code will already have\n" + + " the conditional check code. The code is optimized for branch\n" + + " offsets that fit in 2 bytes, though will handle 4 byte offsets.\n" + + "<code>\n" + + " if condition\n" + + " then code\n" + + " else code\n" + + "</code>\n" + + " what actually gets built is\n" + + "<code>\n" + + " if !condition branch to eb:\n" + + " then code\n" + + " goto end: // skip else\n" + + " eb:\n" + + " else code\n" + + " end:\n" + + "</code>\n" + + "*/\n" + + "public class X09 {\n" + + "\n" + + "}\n"; + formatSource(source, + "package wksp2;\n" + + "\n" + + "/**\n" + + " * A Conditional represents an if/then/else block. When this is created the code\n" + + " * will already have the conditional check code. The code is optimized for\n" + + " * branch offsets that fit in 2 bytes, though will handle 4 byte offsets. <code>\n" + + " if condition\n" + + " then code\n" + + " else code\n" + + "</code>\n" + + " * what actually gets built is <code>\n" + + " if !condition branch to eb:\n" + + " then code\n" + + " goto end: // skip else\n" + + " eb:\n" + + " else code\n" + + " end:\n" + + "</code>\n" + + " */\n" + + "public class X09 {\n" + + "\n" + + "}\n" + ); +} + +/** * @bug 260798: [formatter] Strange behavior of never join lines * @test Ensure that the formatter indents lines correctly when never join lines pref is activated * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=260798" @@ -4594,6 +5677,133 @@ public void testBug267658b() throws JavaModelException { } /** + * @bug 270209: [format] Condensed block comment formatting + * @test Verify that block and javadoc comments are formatted in condensed + * mode when the corresponding preferences is set + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=270209" + */ +public void testBug270209_Block01() throws JavaModelException { + this.formatterPrefs.comment_new_lines_at_block_boundaries = false; + String source = + "public interface X01 {\n" + + "\n" + + "/* Instead of like this. I use these a lot and\n" + + " * this can take up a lot of space. */\n" + + "void foo();\n" + + "}\n"; + formatSource(source, + "public interface X01 {\n" + + "\n" + + " /* Instead of like this. I use these a lot and this can take up a lot of\n" + + " * space. */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug270209_Block02() throws JavaModelException { + this.formatterPrefs.comment_new_lines_at_block_boundaries = false; + String source = + "public interface X02 {\n" + + "\n" + + "/*\n" + + " * Instead of like this. I use these a lot and\n" + + " * this can take up a lot of space.\n" + + " */\n" + + "void foo();\n" + + "}\n"; + formatSource(source, + "public interface X02 {\n" + + "\n" + + " /* Instead of like this. I use these a lot and this can take up a lot of\n" + + " * space. */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug270209_Block03() throws JavaModelException { + this.formatterPrefs.comment_new_lines_at_block_boundaries = false; + String source = + "public interface X03 {\n" + + "\n" + + "/*\n" + + " * \n" + + " * Instead of like this. I use these a lot and\n" + + " * this can take up a lot of space.\n" + + " * \n" + + " */\n" + + "void foo();\n" + + "}\n"; + formatSource(source, + "public interface X03 {\n" + + "\n" + + " /* Instead of like this. I use these a lot and this can take up a lot of\n" + + " * space. */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug270209_Javadoc01() throws JavaModelException { + this.formatterPrefs.comment_new_lines_at_javadoc_boundaries = false; + String source = + "public interface X01 {\n" + + "\n" + + "/** Instead of like this. I use these a lot and\n" + + " * this can take up a lot of space. */\n" + + "void foo();\n" + + "}\n"; + formatSource(source, + "public interface X01 {\n" + + "\n" + + " /** Instead of like this. I use these a lot and this can take up a lot of\n" + + " * space. */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug270209_Javadoc02() throws JavaModelException { + this.formatterPrefs.comment_new_lines_at_javadoc_boundaries = false; + String source = + "public interface X02 {\n" + + "\n" + + "/**\n" + + " * Instead of like this. I use these a lot and\n" + + " * this can take up a lot of space.\n" + + " */\n" + + "void foo();\n" + + "}\n"; + formatSource(source, + "public interface X02 {\n" + + "\n" + + " /** Instead of like this. I use these a lot and this can take up a lot of\n" + + " * space. */\n" + + " void foo();\n" + + "}\n" + ); +} +public void testBug270209_Javadoc03() throws JavaModelException { + this.formatterPrefs.comment_new_lines_at_javadoc_boundaries = false; + String source = + "public interface X03 {\n" + + "\n" + + "/**\n" + + " * \n" + + " * Instead of like this. I use these a lot and\n" + + " * this can take up a lot of space.\n" + + " * \n" + + " */\n" + + "void foo();\n" + + "}\n"; + formatSource(source, + "public interface X03 {\n" + + "\n" + + " /** Instead of like this. I use these a lot and this can take up a lot of\n" + + " * space. */\n" + + " void foo();\n" + + "}\n" + ); +} + +/** * @bug 273619: [formatter] Formatting repeats *} in javadoc * @test Ensure that *} is not repeated while formatting * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=273619" @@ -4934,4 +6144,99 @@ public void testBug287833c() { "}\n"); } +/** + * @bug 300379: [formatter] Fup of bug 287833 + * @test Verify that the leading '{' is not deleted while formatting + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=300379" + */ +public void testBug300379() { + String source = + "public class X {\n" + + " /**\n" + + " * <pre> {@code\n" + + " * \n" + + " * public class X {\n" + + " * }}</pre>\n" + + " */\n" + + " public void foo() {}\n" + + "}\n"; + + formatSource(source, + "public class X {\n" + + " /**\n" + + " * <pre>\n" + + " * {\n" + + " * @code\n" + + " * public class X {\n" + + " * }\n" + + " * }\n" + + " * </pre>\n" + + " */\n" + + " public void foo() {\n" + + " }\n" + + "}\n"); +} +public void testBug300379b() { + String source = + "public class X {\n" + + " /**\n" + + " * <pre> {@code\n" + + " * \n" + + " * public class X {}}</pre>\n" + + " */\n" + + " public void foo() {}\n" + + "}\n"; + + formatSource(source, + "public class X {\n" + + " /**\n" + + " * <pre>\n" + + " * {\n" + + " * @code\n" + + " * public class X {\n" + + " * }\n" + + " * }\n" + + " * </pre>\n" + + " */\n" + + " public void foo() {\n" + + " }\n" + + "}\n"); +} + +/** + * @bug 304705: [formatter] Unexpected indentation of wrapped line comments when 'Never indent line comment on first column' preference is checked + * @test Verify that wrapped line comments are also put at first column + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=304705" + */ +public void testBug304705() { + this.formatterPrefs.never_indent_line_comments_on_first_column = true; + String source = + "public interface Example {\n" + + "// This is a long comment with whitespace that should be split in multiple line comments in case the line comment formatting is enabled\n" + + " int foo();\n" + + "}\n"; + formatSource(source, + "public interface Example {\n" + + "// This is a long comment with whitespace that should be split in multiple line\n" + + "// comments in case the line comment formatting is enabled\n" + + " int foo();\n" + + "}\n"); +} +public void testBug304705b() { + this.formatterPrefs.never_indent_block_comments_on_first_column = true; + String source = + "public interface Example {\n" + + "/* This is a long comment with whitespace that should be split in multiple line comments in case the line comment formatting is enabled */\n" + + " int foo();\n" + + "}\n"; + formatSource(source, + "public interface Example {\n" + + "/*\n" + + " * This is a long comment with whitespace that should be split in multiple line\n" + + " * comments in case the line comment formatting is enabled\n" + + " */\n" + + " int foo();\n" + + "}\n"); +} + } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsTests.java index 38e845552..e58ca3185 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterCommentsTests.java @@ -258,7 +258,7 @@ void formatUnit(String packageName, String unitName, int kind, int indentationLe this.workingCopies = new ICompilationUnit[1]; this.workingCopies[0] = getCompilationUnit(JAVA_PROJECT.getElementName() , "", "test."+packageName, unitName); //$NON-NLS-1$ //$NON-NLS-2$ String outputSource = getOutputSource(this.workingCopies[0]); - formatSource(this.workingCopies[0].getSource(), outputSource, kind, indentationLevel, checkNull, offset, length, lineSeparator, true); + formatSource(this.workingCopies[0].getSource(), outputSource, kind, indentationLevel, offset, length, lineSeparator, true); } /** diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterMassiveRegressionTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterMassiveRegressionTests.java index 486b65098..90911f163 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterMassiveRegressionTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterMassiveRegressionTests.java @@ -206,7 +206,7 @@ public class FormatterMassiveRegressionTests extends FormatterRegressionTests { private final int testIndex; // Cleaning - private static int MAX_FILES, MAX_DIGITS; + private final static Map MAX_FILES = new HashMap(); // Formatting behavior final static int FORMAT_REPEAT = Integer.parseInt(System.getProperty("repeat", "2")); @@ -361,7 +361,7 @@ protected static Test suite(File inputDir, String profile, Map directories) { int profiles = initProfiles(profile); // Init directories - initDirectories(inputDir, profiles); + initDirectories(inputDir, profiles, true); // Get files from input dir FileFilter filter = new FileFilter() { @@ -398,8 +398,10 @@ protected static Test suite(File inputDir, String profile, Map directories) { directories.put(inputDir, allFiles); System.out.println("done"); } - MAX_FILES = allFiles.length; - MAX_DIGITS = (int) (Math.log(MAX_FILES)/Math.log(10)); + int[] maxFiles = new int[2]; + maxFiles[0] = allFiles.length; + maxFiles[1] = (int) (Math.log(maxFiles[0])/Math.log(10)); + MAX_FILES.put(inputDir, maxFiles); // Add tests to clean the output directory and rebuild the references // if (CLEAN) { @@ -407,7 +409,7 @@ protected static Test suite(File inputDir, String profile, Map directories) { // } // Add one test per found file - for (int i=0; i<MAX_FILES; i++) { + for (int i=0; i<maxFiles[0]; i++) { if (CLEAN) { suite.addTest(new FormatterMassiveRegressionTests(inputDir, allFiles[i], i, profiles, false/*do not compare while cleaning*/)); } else { @@ -513,7 +515,7 @@ private static int initProfiles(String profile) { return profiles; } -private static void initDirectories(File inputDir, int profiles) { +private static void initDirectories(File inputDir, int profiles, boolean verify) { // Verify input directory if (!inputDir.exists() && !inputDir.isDirectory()) { @@ -557,7 +559,7 @@ private static void initDirectories(File inputDir, int profiles) { // Get log dir try { - setLogDir(inputDir, profiles); + setLogDir(inputDir, profiles, verify); } catch (CoreException e) { e.printStackTrace(); } @@ -573,7 +575,7 @@ private static void initDirectories(File inputDir, int profiles) { } } -private static void setLogDir(File inputDir, int profiles) throws CoreException { +private static void setLogDir(File inputDir, int profiles, boolean verify) throws CoreException { // Compute log dir File logDir = new File(System.getProperty("logDir")); @@ -612,7 +614,7 @@ private static void setLogDir(File inputDir, int profiles) throws CoreException String filePrefix = inputDir.getName().replaceAll("\\.", ""); String logFileName = filePrefix+".txt"; LOG_FILE = new File(logDir, logFileName); - if (LOG_FILE.exists()) { + if (verify && LOG_FILE.exists()) { File saveDir = new File(logDir, "save"); saveDir.mkdir(); int i=0; @@ -729,6 +731,9 @@ private static void appendProfiles(int profiles, StringBuffer buffer) { buffer.append(lines); first = false; } + if (first) { + buffer.append("none!"); + } } private static void setOutputDir(File inputDir, String dir, int profiles) { @@ -883,7 +888,8 @@ public String getName() { StringBuffer name = new StringBuffer(super.getName()); if (this.testIndex >= 0) { int n = this.testIndex == 0 ? 0 : (int) (Math.log(this.testIndex)/Math.log(10)); - for (int i=n; i<MAX_DIGITS; i++) { + int max = ((int[])MAX_FILES.get(this.inputDir))[1]; + for (int i=n; i<max; i++) { name.append('0'); } name.append(this.testIndex); @@ -902,35 +908,70 @@ public String getName() { */ public void setUp() throws Exception { super.setUp(); + + // Setup preferences this.preferences = DefaultCodeFormatterOptions.getEclipseDefaultSettings(); - if (NO_COMMENTS) { + + // Setup no comments profile + if ((this.profiles & PROFILE_NO_COMMENTS) != 0) { this.preferences.comment_format_javadoc_comment = false; this.preferences.comment_format_block_comment = false; this.preferences.comment_format_line_comment = false; } - if (JOIN_LINES != null) { - if (!JOIN_LINES.equals("only_comments")) { + + // Setup join lines profile + String joinLines = null; + switch (this.profiles & PROFILE_JOIN_LINES_MASK) { + case PROFILE_NEVER_JOIN_LINES: + joinLines = "never"; + break; + case PROFILE_JOIN_LINES_ONLY_COMMENTS: + joinLines = "only_comments"; + break; + case PROFILE_JOIN_LINES_ONLY_CODE: + joinLines = "only_code"; + break; + } + if (joinLines != null) { + if (!joinLines.equals("only_comments")) { this.preferences.join_lines_in_comments = false; } - if (!JOIN_LINES.equals("only_code")) { + if (!joinLines.equals("only_code")) { this.preferences.join_wrapped_lines = false; } } - if (BRACES != null) { - this.preferences.brace_position_for_annotation_type_declaration = BRACES; - this.preferences.brace_position_for_anonymous_type_declaration = BRACES; - this.preferences.brace_position_for_array_initializer = BRACES; - this.preferences.brace_position_for_block = BRACES; - this.preferences.brace_position_for_block_in_case = BRACES; - this.preferences.brace_position_for_constructor_declaration = BRACES; - this.preferences.brace_position_for_enum_constant = BRACES; - this.preferences.brace_position_for_enum_declaration = BRACES; - this.preferences.brace_position_for_method_declaration = BRACES; - this.preferences.brace_position_for_switch = BRACES; - this.preferences.brace_position_for_type_declaration = BRACES; - } - if (PRESERVED_LINES != -1) { - this.preferences.number_of_empty_lines_to_preserve = PRESERVED_LINES; + + // Setup braces profile + String braces = null; + switch (this.profiles & PROFILE_BRACES_MASK) { + case PROFILE_BRACES_NEXT_LINE: + braces = DefaultCodeFormatterConstants.NEXT_LINE; + break; + case PROFILE_BRACES_NEXT_LINE_ON_WRAP: + braces = DefaultCodeFormatterConstants.NEXT_LINE_ON_WRAP; + break; + case PROFILE_BRACES_NEXT_LINE_SHIFTED: + braces = DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED; + break; + } + if (braces != null) { + this.preferences.brace_position_for_annotation_type_declaration = braces; + this.preferences.brace_position_for_anonymous_type_declaration = braces; + this.preferences.brace_position_for_array_initializer = braces; + this.preferences.brace_position_for_block = braces; + this.preferences.brace_position_for_block_in_case = braces; + this.preferences.brace_position_for_constructor_declaration = braces; + this.preferences.brace_position_for_enum_constant = braces; + this.preferences.brace_position_for_enum_declaration = braces; + this.preferences.brace_position_for_method_declaration = braces; + this.preferences.brace_position_for_switch = braces; + this.preferences.brace_position_for_type_declaration = braces; + } + + // Setup preserved lines profile + if ((this.profiles & PROFILE_PRESERVED_LINES_MASK) != 0) { + int lines = (this.profiles & PROFILE_PRESERVED_LINES_MASK) >> 5; + this.preferences.number_of_empty_lines_to_preserve = lines; } } @@ -940,7 +981,7 @@ public void setUp() throws Exception { public void setUpSuite() throws Exception { // Init directories - initDirectories(this.inputDir, this.profiles); + initDirectories(this.inputDir, this.profiles, false); // Delete output dir before compute reference if (CLEAN) { @@ -1000,6 +1041,13 @@ private void print() { // Input dir buffer.append("Input dir : "); buffer.append(this.inputDir); + buffer.append(LINE_SEPARATOR); + + // Files + buffer.append(" "); + int[] maxFiles = (int[]) MAX_FILES.get(this.inputDir); + buffer.append(maxFiles[0]); + buffer.append(" java files to format..."); // Flush to console to show startup String firstBuffer = buffer.toString(); @@ -1048,11 +1096,6 @@ private void print() { } else { buffer.append("Compare vs: none"); } - - // Files - buffer.append(" "); - buffer.append(MAX_FILES); - buffer.append(" java files found"); buffer.append(LINE_SEPARATOR); // Write logs diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterRegressionTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterRegressionTests.java index 814ebad70..26601f633 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterRegressionTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterRegressionTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * IBM Corporation - initial API and implementation + * Brock Janiczak - Contribution for bug 150741 *******************************************************************************/ package org.eclipse.jdt.core.tests.formatter; @@ -40,6 +41,7 @@ import org.eclipse.jdt.core.tests.util.Util; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.formatter.DefaultCodeFormatter; import org.eclipse.jdt.internal.formatter.DefaultCodeFormatterOptions; +import org.eclipse.jdt.internal.formatter.align.Alignment; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.text.edits.TextEdit; @@ -218,6 +220,11 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { assertSourceEquals("Different number of length", Util.convertToIndependantLineDelimiter(expectedContents), actualContents); } + void assertLineEquals(String actualContents, String originalSource, String expectedContents) { + String outputSource = expectedContents == null ? originalSource : expectedContents; + assertLineEquals(actualContents, originalSource, outputSource, false /* do not check null */); + } + DefaultCodeFormatter codeFormatter() { if (this.formatterOptions == null) { this.formatterOptions = JAVA_PROJECT.getOptions(true); @@ -225,11 +232,6 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { DefaultCodeFormatter codeFormatter = new DefaultCodeFormatter(this.formatterPrefs, this.formatterOptions); return codeFormatter; } - - void assertLineEquals(String actualContents, String originalSource, String expectedContents) { - String outputSource = expectedContents == null ? originalSource : expectedContents; - assertLineEquals(actualContents, originalSource, outputSource, false /* do not check null */); - } void formatSource(String source) { // expect unchanged source after formatting @@ -239,6 +241,10 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { void formatSource(String source, String formattedOutput) { formatSource(source, formattedOutput, CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, 0, true /*repeat formatting twice*/); } + + void formatSource(String source, String formattedOutput, int kind) { + formatSource(source, formattedOutput, kind, 0, true /*repeat formatting twice*/); + } void formatSource(String source, String formattedOutput, boolean repeat) { formatSource(source, formattedOutput, CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, 0, repeat); @@ -273,11 +279,11 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { } assertLineEquals(result, newSource, formattedOutput); } else { - formatSource(source, formattedOutput, kind, indentationLevel, false, 0, -1, null, repeat); + formatSource(source, formattedOutput, kind, indentationLevel, 0, -1, null, repeat); } } - void formatSource(String source, String formattedOutput, int kind, int indentationLevel, boolean checkNull, int offset, int length, String lineSeparator, boolean repeat) { + void formatSource(String source, String formattedOutput, int kind, int indentationLevel, int offset, int length, String lineSeparator, boolean repeat) { DefaultCodeFormatter codeFormatter = codeFormatter(); String result; if (length == -1) { @@ -285,7 +291,14 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { } else { result = runFormatter(codeFormatter, source, kind, indentationLevel, offset, length, lineSeparator, repeat); } - assertLineEquals(result, source, formattedOutput); + if (lineSeparator == null) { + assertLineEquals(result, source, formattedOutput); + } else { + // Do not convert line delimiter while comparing result when a specific one is specified + assertNotNull("Error(s) occured while formatting", result); + String outputSource = formattedOutput == null ? source : formattedOutput; + assertSourceEquals("Different number of length", outputSource, result, false/*do not convert line delimiter*/); + } } @@ -7310,6 +7323,30 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { JavaCore.setOptions(javaCoreOptions); } } + public void test527b() { + Map options = DefaultCodeFormatterConstants.getJavaConventionsSettings(); + DefaultCodeFormatterOptions preferences = new DefaultCodeFormatterOptions(options); + preferences.tab_char = DefaultCodeFormatterOptions.TAB; + preferences.tab_size = 4; + preferences.alignment_for_arguments_in_annotation = Alignment.M_COMPACT_SPLIT; + Hashtable javaCoreOptions = JavaCore.getOptions(); + try { + Hashtable newJavaCoreOptions = JavaCore.getOptions(); + newJavaCoreOptions.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); + newJavaCoreOptions.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); + newJavaCoreOptions.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); + JavaCore.setOptions(newJavaCoreOptions); + + Map compilerOptions = new HashMap(); + compilerOptions.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); + compilerOptions.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); + compilerOptions.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); + DefaultCodeFormatter codeFormatter = new DefaultCodeFormatter(preferences, compilerOptions); + runTest(codeFormatter, "test527b", "A.java", CodeFormatter.K_COMPILATION_UNIT, false);//$NON-NLS-1$ //$NON-NLS-2$ + } finally { + JavaCore.setOptions(javaCoreOptions); + } + } /** * https://bugs.eclipse.org/bugs/show_bug.cgi?id=79779 @@ -8737,9 +8774,9 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { "/**\r\n" + " * Mensagens SMTP tem o seguinte formato:\r\n" + " * <pre>\r\n" + - " * resposta de uma linha só:\r\n" + + " * resposta de uma linha s�:\r\n" + " * nnn [SP] lalalal [CR] [LF]\r\n" + - " * resposta de várias linhas:\r\n" + + " * resposta de v�rias linhas:\r\n" + " * nnn [-] lalalalal [CR] [LF]\r\n" + " * nnn [-] lalalalal [CR] [LF]\r\n" + " * ...\r\n" + @@ -8751,9 +8788,9 @@ public class FormatterRegressionTests extends AbstractJavaModelTests { " * Mensagens SMTP tem o seguinte formato:\n" + " * \n" + " * <pre>\n" + - " * resposta de uma linha só:\n" + + " * resposta de uma linha s�:\n" + " * nnn [SP] lalalal [CR] [LF]\n" + - " * resposta de várias linhas:\n" + + " * resposta de v�rias linhas:\n" + " * nnn [-] lalalalal [CR] [LF]\n" + " * nnn [-] lalalalal [CR] [LF]\n" + " * ...\n" + @@ -10622,4 +10659,27 @@ public void test723() { DefaultCodeFormatter codeFormatter = new DefaultCodeFormatter(preferences, compilerOptions); runTest(codeFormatter, "test723", "A.java", CodeFormatter.K_COMPILATION_UNIT, false);//$NON-NLS-1$ //$NON-NLS-2$ } +// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150741 +public void test724() { + this.formatterPrefs.insert_new_line_after_label = true; + String source = + "public class X {\n" + + " public static void main(String[] args) {\n" + + " LABEL:for (int i = 0; i < 10; i++) {\n" + + " }\n" + + " }\n" + + "\n" + + "}\n" + + ""; + formatSource(source, + "public class X {\n" + + " public static void main(String[] args) {\n" + + " LABEL:\n" + + " for (int i = 0; i < 10; i++) {\n" + + " }\n" + + " }\n" + + "\n" + + "}\n" + ); +} } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/RunFormatterMassiveTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/RunFormatterMassiveTests.java index f763e0b10..3c3c77a24 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/RunFormatterMassiveTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/RunFormatterMassiveTests.java @@ -29,7 +29,7 @@ public class RunFormatterMassiveTests extends junit.framework.TestCase { private final static File INPUT_DIR = new File(System.getProperty("inputDir")); private final static String PROFILE = System.getProperty("profiles"); private final static String[] SUPPORTED_WORKSPACES = { - "full-src-3.0", + "full-src-30", "galileo", "JDKs", }; diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/CommentTestCase.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/CommentTestCase.java index c55fecf9a..199ebad8e 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/CommentTestCase.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/CommentTestCase.java @@ -24,6 +24,7 @@ import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.tests.model.SuiteOfTestCases; public abstract class CommentTestCase extends SuiteOfTestCases { + public static Test buildTestSuite(Class evaluationTestClass) { return buildTestSuite(evaluationTestClass, null); //$NON-NLS-1$ } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/JavaDocTestCase.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/JavaDocTestCase.java index ba564ca7b..da589d7a5 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/JavaDocTestCase.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/JavaDocTestCase.java @@ -19,23 +19,14 @@ import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; -import org.eclipse.jdt.internal.formatter.DefaultCodeFormatter; -import org.eclipse.jdt.internal.formatter.comment.JavaDocLine; -import org.eclipse.jdt.internal.formatter.comment.MultiCommentLine; import org.eclipse.text.edits.TextEdit; -public class JavaDocTestCase extends CommentTestCase { +public class JavaDocTestCase extends MultiLineTestCase { static { // TESTS_NAMES = new String[] { "test109636_2" } ; } - protected static final String INFIX= MultiCommentLine.MULTI_COMMENT_CONTENT_PREFIX; - - protected static final String POSTFIX= MultiCommentLine.MULTI_COMMENT_END_PREFIX; - - protected static final String PREFIX= JavaDocLine.JAVADOC_START_PREFIX; - public static Test suite() { return buildTestSuite(JavaDocTestCase.class); } @@ -698,7 +689,7 @@ public class JavaDocTestCase extends CommentTestCase { String expected = "/**" + DELIMITER + " * <pre>" + DELIMITER + - (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT ? " * " + DELIMITER : "") + + " * " + DELIMITER + " * </pre>" + DELIMITER + " * " + DELIMITER + " * " + DELIMITER + @@ -876,23 +867,8 @@ public class JavaDocTestCase extends CommentTestCase { " * </code>" + DELIMITER + " */"; - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? input // do not change as <code> is an immutable tag - : "/**" + DELIMITER + - " * <code>" + DELIMITER + - " * <pre>" + DELIMITER + - " * setLeadingComment("/* traditional comment */"); // correct" + DELIMITER + - " * setLeadingComment("missing comment delimiters"); // wrong" + DELIMITER + - " * setLeadingComment("/* unterminated traditional comment "); // wrong" + DELIMITER + - " * setLeadingComment("/* broken\\n traditional comment */"); // correct" + DELIMITER + - " * setLeadingComment("// end-of-line comment\\n"); // correct" + DELIMITER + - " * setLeadingComment("// end-of-line comment without line terminator"); // correct" + DELIMITER + - " * setLeadingComment("// broken\\n end-of-line comment\\n"); // wrong" + DELIMITER + - " * </pre>" + DELIMITER + - " * </code>" + DELIMITER + - " */"; String result=testFormat(input, options); - assertEquals(expected, result); + assertEquals(input, result); } public void test109636_2() { @@ -940,37 +916,35 @@ public class JavaDocTestCase extends CommentTestCase { } public void test109636_4() { - if (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT) { - Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); - - String input = - "/**" + DELIMITER + - " * <pre>" + DELIMITER + - " * setLeadingComment(\"/* traditional comment */\"); // correct" + DELIMITER + - " * setLeadingComment(\"missing comment delimiters\"); // wrong" + DELIMITER + - " * setLeadingComment(\"/* unterminated traditional comment \"); // wrong" + DELIMITER + - " * setLeadingComment(\"/* broken\\n traditional comment */\"); // correct" + DELIMITER + - " * setLeadingComment(\"// end-of-line comment\\n\"); // correct" + DELIMITER + - " * setLeadingComment(\"// end-of-line comment without line terminator\"); // correct" + DELIMITER + - " * setLeadingComment(\"// broken\\n end-of-line comment\\n\"); // wrong" + DELIMITER + - " * </pre>" + DELIMITER + - " */"; - - String expected = - "/**" + DELIMITER + - " * <pre>" + DELIMITER + - " * setLeadingComment("/* traditional comment */"); // correct" + DELIMITER + - " * setLeadingComment("missing comment delimiters"); // wrong" + DELIMITER + - " * setLeadingComment("/* unterminated traditional comment "); // wrong" + DELIMITER + - " * setLeadingComment("/* broken\\n traditional comment */"); // correct" + DELIMITER + - " * setLeadingComment("// end-of-line comment\\n"); // correct" + DELIMITER + - " * setLeadingComment("// end-of-line comment without line terminator"); // correct" + DELIMITER + - " * setLeadingComment("// broken\\n end-of-line comment\\n"); // wrong" + DELIMITER + - " * </pre>" + DELIMITER + - " */"; - String result=testFormat(input, options); - assertEquals(expected, result); - } + Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); + + String input = + "/**" + DELIMITER + + " * <pre>" + DELIMITER + + " * setLeadingComment(\"/* traditional comment */\"); // correct" + DELIMITER + + " * setLeadingComment(\"missing comment delimiters\"); // wrong" + DELIMITER + + " * setLeadingComment(\"/* unterminated traditional comment \"); // wrong" + DELIMITER + + " * setLeadingComment(\"/* broken\\n traditional comment */\"); // correct" + DELIMITER + + " * setLeadingComment(\"// end-of-line comment\\n\"); // correct" + DELIMITER + + " * setLeadingComment(\"// end-of-line comment without line terminator\"); // correct" + DELIMITER + + " * setLeadingComment(\"// broken\\n end-of-line comment\\n\"); // wrong" + DELIMITER + + " * </pre>" + DELIMITER + + " */"; + + String expected = + "/**" + DELIMITER + + " * <pre>" + DELIMITER + + " * setLeadingComment("/* traditional comment */"); // correct" + DELIMITER + + " * setLeadingComment("missing comment delimiters"); // wrong" + DELIMITER + + " * setLeadingComment("/* unterminated traditional comment "); // wrong" + DELIMITER + + " * setLeadingComment("/* broken\\n traditional comment */"); // correct" + DELIMITER + + " * setLeadingComment("// end-of-line comment\\n"); // correct" + DELIMITER + + " * setLeadingComment("// end-of-line comment without line terminator"); // correct" + DELIMITER + + " * setLeadingComment("// broken\\n end-of-line comment\\n"); // wrong" + DELIMITER + + " * </pre>" + DELIMITER + + " */"; + String result=testFormat(input, options); + assertEquals(expected, result); } /** diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/MultiLineTestCase.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/MultiLineTestCase.java index 76d6e0512..2d436d3bc 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/MultiLineTestCase.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/MultiLineTestCase.java @@ -17,18 +17,14 @@ import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import junit.framework.Test; -import org.eclipse.jdt.internal.formatter.DefaultCodeFormatter; -import org.eclipse.jdt.internal.formatter.comment.MultiCommentLine; - public class MultiLineTestCase extends CommentTestCase { static { // TESTS_NAMES = new String[] { "test170580" } ; } - protected static final String INFIX= MultiCommentLine.MULTI_COMMENT_CONTENT_PREFIX; - - protected static final String POSTFIX= MultiCommentLine.MULTI_COMMENT_END_PREFIX; - protected static final String PREFIX= MultiCommentLine.MULTI_COMMENT_START_PREFIX; + protected static final String INFIX= " * "; //$NON-NLS-1$ + protected static final String POSTFIX= " */"; //$NON-NLS-1$ + protected static final String PREFIX= "/* "; //$NON-NLS-1$ public static Test suite() { return buildTestSuite(MultiLineTestCase.class); @@ -116,13 +112,9 @@ public class MultiLineTestCase extends CommentTestCase { " * Member comment\n" +//$NON-NLS-1$ " */";//$NON-NLS-1$ String result= testFormat(input, 0, input.length(), CodeFormatter.K_MULTI_LINE_COMMENT , 2); - String expectedOutput = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? "/**\n" + - " * Member comment\n" + - " */" - : "/***********************************************************************\n" + - " * Member comment\n" + - " */"; + String expectedOutput = "/**\n" + + " * Member comment\n" + + " */"; assertEquals("Different output", expectedOutput, result); } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/SingleLineTestCase.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/SingleLineTestCase.java index 32ce3f869..463c7e298 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/SingleLineTestCase.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/comment/SingleLineTestCase.java @@ -16,11 +16,9 @@ import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; -import org.eclipse.jdt.internal.formatter.DefaultCodeFormatter; -import org.eclipse.jdt.internal.formatter.comment.SingleCommentLine; - public class SingleLineTestCase extends CommentTestCase { - protected static final String PREFIX= SingleCommentLine.SINGLE_COMMENT_PREFIX; + + protected static final String PREFIX= "// "; //$NON-NLS-1$ static { // TESTS_NAMES = new String[] { "test109581" } ; @@ -42,9 +40,7 @@ public class SingleLineTestCase extends CommentTestCase { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "5"); //$NON-NLS-1$ setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT, DefaultCodeFormatterConstants.FALSE); setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT, DefaultCodeFormatterConstants.FALSE); - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + "//"+ DELIMITER + PREFIX + "test" - : PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + "//"+ DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("//test\ttest" + DELIMITER + "//" + DELIMITER + "//\t\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ } @@ -52,9 +48,7 @@ public class SingleLineTestCase extends CommentTestCase { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "5"); //$NON-NLS-1$ setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT, DefaultCodeFormatterConstants.FALSE); setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT, DefaultCodeFormatterConstants.FALSE); - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + DELIMITER + PREFIX + "test" - : PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + "//" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("//test\t\ttest" + DELIMITER + PREFIX + DELIMITER + "//\t\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ } @@ -62,23 +56,17 @@ public class SingleLineTestCase extends CommentTestCase { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "5"); //$NON-NLS-1$ setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT, DefaultCodeFormatterConstants.FALSE); setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT, DefaultCodeFormatterConstants.FALSE); - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + "//"+ DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" - : PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + "//"+ DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("//test\ttest" + DELIMITER + "//" + DELIMITER + PREFIX + "test\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ } public void testCommentBegin1() { - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test" - : PREFIX + "test" + DELIMITER; + String expected = PREFIX + "test"; assertEquals(expected, testFormat("//test")); //$NON-NLS-1$ //$NON-NLS-2$ } public void testCommentBegin2() { - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test" - : PREFIX + "test" + DELIMITER; + String expected = PREFIX + "test"; assertEquals(expected, testFormat(PREFIX + "test")); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -87,14 +75,12 @@ public class SingleLineTestCase extends CommentTestCase { } public void testCommentDelimiter1() { - String expected = PREFIX + "test" + DELIMITER; - if (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT) expected += DELIMITER; + String expected = PREFIX + "test" + DELIMITER + DELIMITER; assertEquals(expected, testFormat("//\t\ttest " + DELIMITER + DELIMITER)); //$NON-NLS-1$ //$NON-NLS-2$ } public void testCommentDelimiter2() { - String expected = PREFIX + "test" + DELIMITER; - if (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT) expected += DELIMITER ; + String expected = PREFIX + "test" + DELIMITER + DELIMITER ; assertEquals(expected, testFormat(PREFIX + "test " + DELIMITER + DELIMITER + DELIMITER)); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -123,47 +109,35 @@ public class SingleLineTestCase extends CommentTestCase { } public void testCommentSpace1() { - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test test" - : PREFIX + "test test" + DELIMITER; + String expected = PREFIX + "test test"; assertEquals(expected, testFormat("//test\t \t test")); //$NON-NLS-1$ //$NON-NLS-2$ } public void testCommentSpace2() { - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test test" - : PREFIX + "test test" + DELIMITER; + String expected = PREFIX + "test test"; assertEquals(expected, testFormat("//test test")); //$NON-NLS-1$ //$NON-NLS-2$ } public void testCommentSpace3() { - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test test" - : PREFIX + "test test" + DELIMITER; + String expected = PREFIX + "test test"; assertEquals(expected, testFormat(PREFIX + "test \t \t test")); //$NON-NLS-1$ //$NON-NLS-2$ } public void testCommentWrapping1() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "5"); //$NON-NLS-1$ - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test" + DELIMITER + PREFIX + "test" - : PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("//test\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void testCommentWrapping2() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "1"); //$NON-NLS-1$ - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test" + DELIMITER + PREFIX + "test" - : PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("//test\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void testCommentWrapping3() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "32"); //$NON-NLS-1$ - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test test" - : PREFIX + "test test" + DELIMITER; + String expected = PREFIX + "test test"; assertEquals(expected, testFormat("//test\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @@ -186,58 +160,48 @@ public class SingleLineTestCase extends CommentTestCase { public void testHeaderComment1() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, DefaultCodeFormatterConstants.FALSE); setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "12"); //$NON-NLS-1$ - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? PREFIX + "test test" + DELIMITER + PREFIX + "test test" + DELIMITER + PREFIX + "test test" - : PREFIX + "test test" + DELIMITER + PREFIX + "test test" + DELIMITER + PREFIX + "test test" + DELIMITER; + String expected = PREFIX + "test test" + DELIMITER + PREFIX + "test test" + DELIMITER + PREFIX + "test test"; assertEquals(expected, testFormat("//test\t\t\t\ttest" + DELIMITER + PREFIX + "test test test test")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } public void testHeaderComment2() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, DefaultCodeFormatterConstants.FALSE); setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "24"); //$NON-NLS-1$ - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? "// test" + DELIMITER + PREFIX + "test test test test" + DELIMITER - : PREFIX + "test test test test" + DELIMITER + PREFIX + "test" + DELIMITER; + String expected = "// test" + DELIMITER + PREFIX + "test test test test" + DELIMITER; assertEquals(expected, testFormat("//test\t\t\t" + DELIMITER + PREFIX + "test test test test" + DELIMITER)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } public void testIllegalLineLength1() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "1"); //$NON-NLS-1$ - String expected =PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; - if (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT) expected = expected.substring(0, expected.length()-DELIMITER.length()); + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("//test\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void testIllegalLineLength2() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "-16"); //$NON-NLS-1$ - String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; - if (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT) expected = expected.substring(0, expected.length()-DELIMITER.length()); + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat(PREFIX + "\t\t test\ttest")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public void testMultipleComments1() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "5"); //$NON-NLS-1$ - String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; - if (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT) expected = expected.substring(0, expected.length()-DELIMITER.length()); + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("//test test" + DELIMITER + PREFIX + "test test test test")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ } public void testMultipleComments2() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "12"); //$NON-NLS-1$ - String expected = DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT - ? "// test test" + DELIMITER + + String expected = "// test test" + DELIMITER + "// test" + DELIMITER + - "// " + DELIMITER + + "//" + DELIMITER + "// test test" + DELIMITER + - "// test test" - : PREFIX + "test test" + DELIMITER + PREFIX + "test test" + DELIMITER + PREFIX + "test test" + DELIMITER + PREFIX + "test" + DELIMITER; + "// test test"; assertEquals(expected, testFormat("//test test\ttest" + DELIMITER + PREFIX + DELIMITER + PREFIX + "test test test test")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ } public void testMultipleComments3() { setUserOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, "11"); //$NON-NLS-1$ - String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER; - if (DefaultCodeFormatter.ENABLE_NEW_COMMENTS_FORMAT) expected = expected.substring(0, expected.length()-DELIMITER.length()); + String expected = PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test" + DELIMITER + PREFIX + "test"; assertEquals(expected, testFormat("// test\t\t\ttest\ttest" + DELIMITER + PREFIX + "test test test test")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AbstractJavaModelTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AbstractJavaModelTests.java index 4ae8bab6c..12386640d 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AbstractJavaModelTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AbstractJavaModelTests.java @@ -725,11 +725,21 @@ public abstract class AbstractJavaModelTests extends SuiteOfTestCases { * The line separators in 'actual' are converted to '\n' before the comparison. */ protected void assertSourceEquals(String message, String expected, String actual) { + assertSourceEquals(message, expected, actual, true/*convert line delimiter*/); + } + /* + * Asserts that the given actual source is equal to the expected one. + * Note that if the line separators in 'actual' are converted to '\n' before the comparison, + * 'expected' is assumed to have the same '\n' line separator. + */ + protected void assertSourceEquals(String message, String expected, String actual, boolean convert) { if (actual == null) { assertEquals(message, expected, null); return; } - actual = org.eclipse.jdt.core.tests.util.Util.convertToIndependantLineDelimiter(actual); + if (convert) { + actual = org.eclipse.jdt.core.tests.util.Util.convertToIndependantLineDelimiter(actual); + } if (!actual.equals(expected)) { System.out.println("Expected source in "+getName()+" should be:"); System.out.print(org.eclipse.jdt.core.tests.util.Util.displayString(actual.toString(), 2)); @@ -2818,13 +2828,23 @@ public abstract class AbstractJavaModelTests extends SuiteOfTestCases { return result; } protected void touch(File f) { - int time = 1000; + final int time = 1000; long lastModified = f.lastModified(); f.setLastModified(lastModified + time); org.eclipse.jdt.core.tests.util.Util.waitAtLeast(time); - // Assertion to track the reason of unexpected failures with tests on external resources + // Loop until the last modified time has really changed on the file // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=295619 - assertEquals("The file "+f.getAbsolutePath()+" was not touched!", lastModified+time, f.lastModified()); + int n = 1; + while (n < 10) { // retry 9 times more if necessary + if (f.lastModified() != lastModified) { + // We can leave the loop as the file has been really touched + return; + } + f.setLastModified(lastModified + n*time); + org.eclipse.jdt.core.tests.util.Util.waitAtLeast(time); + n++; + } + assertFalse("The file "+f.getAbsolutePath()+" was not touched!", lastModified == f.lastModified()); } protected String toString(String[] strings) { diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AllJavaModelTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AllJavaModelTests.java index 2d51faf16..0fa79d8b1 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AllJavaModelTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AllJavaModelTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -180,6 +180,9 @@ private static Class[] getAllTestClasses() { // Creation of imports CreateImportsTests.class, + + // Util tests + UtilTests.class, }; Class[] deprecatedClasses = getDeprecatedJDOMTestClasses(); diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AttachedJavadocTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AttachedJavadocTests.java index cedc8832b..dd50eb158 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AttachedJavadocTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AttachedJavadocTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -547,4 +547,37 @@ public class AttachedJavadocTests extends ModifyingResourceTests { String javadoc = field.getAttachedJavadoc(new NullProgressMonitor()); //$NON-NLS-1$ assertNull("Should have no javadoc", javadoc); //$NON-NLS-1$ } + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316 + public void test025() throws JavaModelException { + IClasspathEntry[] savedEntries = null; + try { + IClasspathEntry[] entries = this.project.getRawClasspath(); + savedEntries = (IClasspathEntry[]) entries.clone(); + final String path = "http:/java.sun.com/javaee/5/docs/api/"; //$NON-NLS-1$ + IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, path); + for (int i = 0, max = entries.length; i < max; i++) { + final IClasspathEntry entry = entries[i]; + if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY + && entry.getContentKind() == IPackageFragmentRoot.K_BINARY + && "/AttachedJavadocProject/lib/test6.jar".equals(entry.getPath().toString())) { //$NON-NLS-1$ + entries[i] = JavaCore.newLibraryEntry(entry.getPath(), entry.getSourceAttachmentPath(), entry.getSourceAttachmentRootPath(), entry.getAccessRules(), new IClasspathAttribute[] { attribute }, entry.isExported()); + } + } + this.project.setRawClasspath(entries, null); + IPackageFragment packageFragment = this.root.getPackageFragment("p1.p2"); //$NON-NLS-1$ + assertNotNull("Should not be null", packageFragment); //$NON-NLS-1$ + IClassFile classFile = packageFragment.getClassFile("X.class"); //$NON-NLS-1$ + assertNotNull(classFile); + IType type = classFile.getType(); + IField field = type.getField("f"); //$NON-NLS-1$ + assertNotNull(field); + String javadoc = field.getAttachedJavadoc(new NullProgressMonitor()); //$NON-NLS-1$ + assertNull("Should not have a javadoc", javadoc); //$NON-NLS-1$ + } finally { + // restore classpath + if (savedEntries != null) { + this.project.setRawClasspath(savedEntries, null); + } + } + } } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassFileTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassFileTests.java index a495d1f2e..f2afc828d 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassFileTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassFileTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -60,7 +60,7 @@ public void setUpSuite() throws Exception { " <U extends Exception> X<T> foo(X<T> x) throws RuntimeException, U {\n" + " return null;\n" + " }\n" + - " <K, V> V foo(K key, V value) throws Exception {\n" + + " <K, V extends T> V foo(K key, V value) throws Exception {\n" + " return value;\n" + " }\n" + "}", @@ -1094,7 +1094,7 @@ public void testParameterTypeSignatures6() throws JavaModelException { assertStringsEqual( "Unexpected type parameters", "K:Ljava.lang.Object;\n" + - "V:Ljava.lang.Object;\n", + "V:TT;\n", method.getTypeParameterSignatures()); } @@ -1523,4 +1523,25 @@ public void testGenericFieldGetTypeSignature() throws JavaModelException { "Ljava.util.Collection<Ljava.lang.String;>;", field.getTypeSignature()); } + + public void testBug246594() throws JavaModelException { + IType type = this.jarRoot.getPackageFragment("generic").getClassFile( + "Z.class").getType(); + ITypeParameter typeParam = type.getTypeParameter("T"); + assertNotNull(typeParam); + assertStringsEqual("Type parameter bounds signatures", + "Ljava.lang.Object;\n" + + "Lgeneric.I<-TT;>;\n", + typeParam.getBoundsSignatures()); + } + + public void testBug246594a() throws JavaModelException { + IType type = this.jarRoot.getPackageFragment("generic").getClassFile( + "X.class").getType(); + IMethod method = type.getMethod("foo", new String[] { "TK;", "TV;" }); + ITypeParameter typeParam = method.getTypeParameter("V"); + assertStringsEqual("Type parameter bounds signatures", + "TT;\n", typeParam.getBoundsSignatures()); + } + } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassNameTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassNameTests.java index d0c31c011..30f9e463b 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassNameTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClassNameTests.java @@ -16,6 +16,8 @@ import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.content.IContentType; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; @@ -1244,4 +1246,47 @@ public void testBug152841() throws Exception{ deleteProject("P"); } } + +/** + * @bug 302455: java.lang.ClassCastException in secondary types removal + * @test Ensure that no invalid entries are put in the secondary types caches + * when a file extension spec is removed from the workspace as the CCE + * does no longer occur... + * Also verify that secondary types from the removed file extension are not + * kept in the projects caches as the secondary type is no longer in the + * cache at the end of the test... + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=302455" + */ +public void testBug302455() throws CoreException, InterruptedException { + IContentType javaContentType = Platform.getContentTypeManager().getContentType(JavaCore.JAVA_SOURCE_CONTENT_TYPE); + try { + // Create project and file + assertNotNull("We should have got a Java Source content type!", javaContentType); + javaContentType.addFileSpec("b302455", IContentType.FILE_EXTENSION_SPEC); + IJavaProject javaProject = createJavaProject("P"); + createFolder("/P/p"); + String filePath = "/P/p/Bug.b302455"; + createFile( + filePath, + "package p;\n" + + "public class Bug {}\n" + + "class Secondary {}\n" + + "" + ); + waitUntilIndexesReady(); + + // Get the secondary type + IType type = javaProject.findType("p.Secondary", new NullProgressMonitor()); + assertNotNull("We should have found the secondary type!", type); + + // Remove file extension + javaContentType.removeFileSpec("b302455", IContentType.FILE_EXTENSION_SPEC); + + // As there's no specific event fo + type = javaProject.findType("p.Secondary", new NullProgressMonitor()); + assertNull("We should have not found the secondary type!", type); + } finally { + deleteProject("P"); + } +} } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClasspathTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClasspathTests.java index 971310e99..67e351f84 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClasspathTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClasspathTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -5971,5 +5971,613 @@ public void testBug248661() throws Exception { this.deleteProject("P"); } } +/** + * @bug 300136:classpathentry OPTIONAL attribute not honored for var entries + * + * Test that classpath entries (CPE_LIB, CPE_CONTAINER and CPE_VARIABLE) that are marked as optional + * in the .classpath file are not reported for errors. + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=300136" + */ +public void testBug300136() throws Exception { + boolean autoBuild = getWorkspace().isAutoBuilding(); + IWorkspaceDescription preferences = getWorkspace().getDescription(); + try { + preferences.setAutoBuilding(false); + IJavaProject project = createJavaProject("P"); + JavaCore.setClasspathVariables( + new String[] {"INVALID_LIB",}, + new IPath[] {new Path("/lib/tmp.jar")}, + null); + + StringBuffer buffer = new StringBuffer( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"var\" path=\"INVALID_LIB\">\n" + + " <attributes>\n" + + " <attribute name=\"optional\" value=\"true\"/>" + + " </attributes>\n" + + " </classpathentry>\n" + + " <classpathentry kind=\"var\" path=\"UNBOUND_VAR\">\n" + + " <attributes>\n" + + " <attribute name=\"optional\" value=\"true\"/>" + + " </attributes>\n" + + " </classpathentry>\n" + + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.core.tests.model.TEST_CONTAINER\">\n" + + " <attributes>\n" + + " <attribute name=\"optional\" value=\"true\"/>" + + " </attributes>\n" + + " </classpathentry>\n" + + " <classpathentry kind=\"output\" path=\"bin\"/>\n" + + "</classpath>" + ); + editFile( + "/P/.classpath", + buffer.toString() + ); + assertMarkers( + "Unexpected markers", + "", + project); + } finally { + preferences.setAutoBuilding(autoBuild); + deleteProject("P"); + JavaCore.removeClasspathVariable("INVALID_LIB", null); + } +} +/** + * Additional test for bug 300136 - Test that the errors are reported when the + * optional attribute is not used. + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=300136" + */ +public void testBug300136a() throws Exception { + boolean autoBuild = getWorkspace().isAutoBuilding(); + IWorkspaceDescription preferences = getWorkspace().getDescription(); + try { + preferences.setAutoBuilding(false); + IJavaProject project = createJavaProject("P"); + IPath libPath = new Path("/lib/tmp.jar"); + JavaCore.setClasspathVariables( + new String[] {"INVALID_LIB",}, + new IPath[] {libPath}, + null); + + StringBuffer buffer = new StringBuffer( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"var\" path=\"INVALID_LIB\" />\n" + + " <classpathentry kind=\"var\" path=\"UNBOUND_VAR\" />\n" + + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.core.tests.model.TEST_CONTAINER\">\n" + + " </classpathentry>\n" + + " <classpathentry kind=\"output\" path=\"bin\"/>\n" + + "</classpath>" + ); + editFile( + "/P/.classpath", + buffer.toString() + ); + assertMarkers( + "Unexpected markers", + "Project \'P\' is missing required library: \'" + libPath.toOSString() + "'\n" + + "Unbound classpath container: \'org.eclipse.jdt.core.tests.model.TEST_CONTAINER\' in project \'P\'\n" + + "Unbound classpath variable: \'UNBOUND_VAR\' in project \'P\'", + project); + } finally { + preferences.setAutoBuilding(autoBuild); + deleteProject("P"); + JavaCore.removeClasspathVariable("INVALID_LIB", null); + } +} +/** + * @bug 294360:Duplicate entries in Classpath Resolution when importing dependencies from parent project + * Test that duplicate entries are not added to the resolved classpath + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=294360" + * @throws Exception + */ +public void testBug294360a() throws Exception { + try { + IJavaProject p = createJavaProject("P"); + addExternalLibrary(p, getExternalResourcePath("lib.jar"), new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n", + }, + JavaCore.VERSION_1_4); + IClasspathEntry[] classpath = new IClasspathEntry[2]; + classpath[0] = JavaCore.newLibraryEntry(new Path(getExternalResourcePath("lib.jar")), null, null); + ContainerInitializer.setInitializer(new DefaultContainerInitializer(new String[] {"P", getExternalResourcePath("lib.jar")})); + classpath[1] = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.core.tests.model.TEST_CONTAINER")); + setClasspath(p, classpath); + + StringBuffer buffer = new StringBuffer( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.core.tests.model.TEST_CONTAINER\"/>\n" + + " <classpathentry kind=\"lib\" path=\""+ getExternalResourcePath("lib.jar") + "\">\n" + + " <attributes>\n" + + " <attribute name=\"optional\" value=\"true\"/>\n" + + " </attributes>\n" + + " </classpathentry>\n" + + " <classpathentry kind=\"output\" path=\"\"/>\n" + + "</classpath>\n"); + + editFile( + "/P/.classpath", + buffer.toString() + ); + + IClasspathEntry[] resolvedClasspath = p.getResolvedClasspath(true); + assertClasspathEquals(resolvedClasspath, + ""+ getExternalPath() + "lib.jar[CPE_LIBRARY][K_BINARY][isExported:false]"); + } finally { + deleteProject("P"); + deleteExternalResource("lib.jar"); + } +} +/** + * @bug 252431:New API is needed to better identify referenced jars in the Class-Path: entry + * Test that 1) referenced libraries are added to the resolved classpath in the right order + * 2) referenced libraries are added to the appropriate referencing library in the correct order + * 3) referenced libraries and top-level libraries retain the source attachment and source attachment root path + * 4) referenced libraries point to the correct entry as their referencingEntry. + * 5) referenced libraries and their attributes are persisted in the .classpath file + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=252431" + * @throws Exception + */ +public void testBug252341a() throws Exception { + try { + IJavaProject p = createJavaProject("P"); + addLibrary(p, "lib1.jar", "abc.zip", new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib2.jar lib3.jar\n", + }, + JavaCore.VERSION_1_4); + createFile("/P/lib2.jar", ""); + createFile("/P/lib3.jar", ""); + + // Test referenced entries are included in the right order in the resolved classpath + IClasspathEntry[] resolvedClasspath = p.getResolvedClasspath(true); + assertClasspathEquals(resolvedClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + ""+ getExternalJCLPathString() + "[CPE_LIBRARY][K_BINARY][isExported:false]\n" + + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib1.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/abc.zip][isExported:true]"); + + IClasspathEntry[] rawClasspath = p.getRawClasspath(); + assertClasspathEquals(rawClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + "JCL_LIB[CPE_VARIABLE][K_SOURCE][isExported:false]\n" + + "/P/lib1.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/abc.zip][isExported:true]"); + + // Test referenced entries for a particular entry appear in the right order and the referencingEntry + // attribute has the correct value + IClasspathEntry[] chains = JavaCore.getReferencedClasspathEntries(rawClasspath[2], p); + assertClasspathEquals(chains, + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + + assertSame("Referencing Entry", rawClasspath[2], chains[0].getReferencingEntry()); + assertSame("Referencing Entry", rawClasspath[2], chains[1].getReferencingEntry()); + + // Test a newly created library entry with similar attributes but without any referencing entry is equal to + // the original referenced entry + IClasspathEntry tempLibEntry = JavaCore.newLibraryEntry(chains[0].getPath(), chains[0].getSourceAttachmentPath(), chains[0].getSourceAttachmentRootPath(), true); + assertEquals("Library Entry", tempLibEntry, chains[0]); + + // Test the source attachment and other attributes added to the referenced entries are stored and retrieved properly + assertEquals("source attachment", resolvedClasspath[4].getSourceAttachmentPath().toPortableString(), "/P/abc.zip"); + assertNull("source attachment", chains[0].getSourceAttachmentPath()); + assertNull("source attachment", chains[1].getSourceAttachmentPath()); + assertNull("source attachment root", chains[0].getSourceAttachmentRootPath()); + assertNull("source attachment root", chains[1].getSourceAttachmentRootPath()); + + ((ClasspathEntry)chains[0]).sourceAttachmentPath = new Path("/P/efg.zip"); + ((ClasspathEntry)chains[1]).sourceAttachmentPath = new Path("/P/xyz.zip"); + ((ClasspathEntry)chains[0]).sourceAttachmentRootPath = new Path("/src2"); + ((ClasspathEntry)chains[1]).sourceAttachmentRootPath = new Path("/src3"); + + IClasspathAttribute javadocLoc = JavaCore.newClasspathAttribute("javadoc_location", "/P/efg.zip"); + ((ClasspathEntry)chains[0]).extraAttributes = new IClasspathAttribute[]{javadocLoc}; + + p.setRawClasspath(rawClasspath, chains, p.getOutputLocation(), null); + + // Test the .classpath file contains all the referenced entries and their attributes + String contents = new String (org.eclipse.jdt.internal.core.util.Util.getResourceContentsAsCharArray(getFile("/P/.classpath"))); + assertSourceEquals( + "Unexpected content", + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"src\" path=\"\"/>\n" + + " <classpathentry kind=\"var\" path=\"JCL_LIB\"/>\n" + + " <classpathentry exported=\"true\" kind=\"lib\" path=\"lib1.jar\" sourcepath=\"abc.zip\"/>\n" + + " <classpathentry kind=\"output\" path=\"\"/>\n" + + " <referencedentry exported=\"true\" kind=\"lib\" path=\"lib2.jar\" rootpath=\"/src2\" sourcepath=\"efg.zip\">\n" + + " <attributes>\n" + + " <attribute name=\"javadoc_location\" value=\"/P/efg.zip\"/>\n" + + " </attributes>\n" + + " </referencedentry>\n" + + " <referencedentry exported=\"true\" kind=\"lib\" path=\"lib3.jar\" rootpath=\"/src3\" sourcepath=\"xyz.zip\"/>\n" + + "</classpath>\n", + contents); + + p.close(); + p.open(null); + rawClasspath = p.getRawClasspath(); + resolvedClasspath = p.getResolvedClasspath(true); + + assertClasspathEquals(rawClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + "JCL_LIB[CPE_VARIABLE][K_SOURCE][isExported:false]\n" + + "/P/lib1.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/abc.zip][isExported:true]"); + + assertClasspathEquals(resolvedClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + ""+ getExternalJCLPathString() + "[CPE_LIBRARY][K_BINARY][isExported:false]\n" + + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/efg.zip][rootPath:/src2][isExported:true][attributes:javadoc_location=/P/efg.zip]\n" + + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/xyz.zip][rootPath:/src3][isExported:true]\n" + + "/P/lib1.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/abc.zip][isExported:true]"); + + } finally { + deleteProject("P"); + } +} +/** + * Additional tests for bug 252431. + * When multiple libraries have one or more common referenced library in their MANIFEST + * 1) The common referenced libries are added to the first library entry in the raw classpath + * 2) Removing one of the top-level library from the raw classpath doesn't remove the referenced + * entry that was commonly referenced by another entry and the referenced entry's source + * attachment and other attributes are retained. + * 3) Passing a NULL referencedEntries array retains the referenced entries + * 4) Passing an empty array as referencedEntries clears the earlier referenced entries + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=252431" + * @throws Exception + */ +public void testBug252341b() throws Exception { + try { + IJavaProject p = createJavaProject("P"); + addLibrary(p, "lib1.jar", null, new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib3.jar lib4.jar\n", + }, + JavaCore.VERSION_1_4); + + addLibrary(p, "lib2.jar", null, new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib3.jar lib5.jar\n", + }, + JavaCore.VERSION_1_4); + createFile("/P/lib3.jar", ""); + createFile("/P/lib4.jar", ""); + createFile("/P/lib5.jar", ""); + + // Test that the referenced entries are not included in the raw classpath + IClasspathEntry[] rawClasspath = p.getRawClasspath(); + assertClasspathEquals( + rawClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + "JCL_LIB[CPE_VARIABLE][K_SOURCE][isExported:false]\n" + + "/P/lib1.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + + IClasspathEntry[] rawEntries = new IClasspathEntry[2]; + rawEntries[0] = JavaCore.newLibraryEntry(new Path("/P/lib1.jar"), null, null, true); + rawEntries[1] = JavaCore.newLibraryEntry(new Path("/P/lib2.jar"), null, null, true); + + // Test that the referenced entries are included in the raw classpath and in the right order + IClasspathEntry[] resolvedClasspath = p.getResolvedClasspath(true); + assertClasspathEquals(resolvedClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + ""+ getExternalJCLPathString() + "[CPE_LIBRARY][K_BINARY][isExported:false]\n" + + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib4.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib1.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib5.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + + // Test that the referenced classpath entries has the appropriate referencingEntry value + IClasspathEntry[] chains = JavaCore.getReferencedClasspathEntries(rawEntries[0], p); + assertClasspathEquals( + chains, + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib4.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + assertEquals("Referencing Entry" , rawEntries[0], chains[0].getReferencingEntry()); + assertEquals("Referencing Entry" , rawEntries[0], chains[1].getReferencingEntry()); + + chains = JavaCore.getReferencedClasspathEntries(rawEntries[1], p); + assertClasspathEquals( + chains, + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib5.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + + assertEquals("Referencing Entry" , rawEntries[0], chains[0].getReferencingEntry()); + assertEquals("Referencing Entry" , rawEntries[1], chains[1].getReferencingEntry()); + +// // Test IPackageFragmentRoot#getResolvedClasspathEntry + IPackageFragmentRoot[] roots = p.getPackageFragmentRoots(); + assertEquals("Package fragment root", roots[2].getResolvedClasspathEntry(), resolvedClasspath[2]); + assertEquals("Package fragment root", roots[3].getResolvedClasspathEntry(), resolvedClasspath[3]); + assertEquals("Package fragment root", roots[4].getResolvedClasspathEntry(), resolvedClasspath[4]); + assertEquals("Package fragment root", roots[5].getResolvedClasspathEntry(), resolvedClasspath[5]); + assertEquals("Package fragment root", roots[6].getResolvedClasspathEntry(), resolvedClasspath[6]); + + // Test the attributes added to the referenced classpath entries are stored and retrieved properly + ((ClasspathEntry)chains[0]).sourceAttachmentPath = new Path("/P/efg.zip"); + ((ClasspathEntry)chains[1]).sourceAttachmentPath = new Path("/P/xyz.zip"); + ((ClasspathEntry)chains[0]).sourceAttachmentRootPath = new Path("/src2"); + ((ClasspathEntry)chains[1]).sourceAttachmentRootPath = new Path("/src3"); + + IClasspathAttribute javadocLoc = JavaCore.newClasspathAttribute("javadoc_location", "/P/efg.zip"); + ((ClasspathEntry)chains[0]).extraAttributes = new IClasspathAttribute[]{javadocLoc}; + + p.setRawClasspath(rawClasspath, chains, p.getOutputLocation(), null); + resolvedClasspath = p.getResolvedClasspath(true); + + assertClasspathEquals(resolvedClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + ""+ getExternalJCLPathString() + "[CPE_LIBRARY][K_BINARY][isExported:false]\n" + + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/efg.zip][rootPath:/src2][isExported:true][attributes:javadoc_location=/P/efg.zip]\n" + + "/P/lib4.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib1.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib5.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/xyz.zip][rootPath:/src3][isExported:true]\n" + + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + + // Test that removing any of the referencing entry from the raw classpath has the correct effect + // on the resolved classpath. Also test passing referencedEntries = null retains the existing + // referenced entries + IClasspathEntry[] newRawClasspath = new IClasspathEntry[rawClasspath.length-1]; + System.arraycopy(rawClasspath, 0, newRawClasspath, 0, 2); + System.arraycopy(rawClasspath, 3, newRawClasspath, 2, 1); + p.setRawClasspath(newRawClasspath, null, p.getOutputLocation(), null); + resolvedClasspath = p.getResolvedClasspath(true); + assertClasspathEquals(resolvedClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + ""+ getExternalJCLPathString() + "[CPE_LIBRARY][K_BINARY][isExported:false]\n" + + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/efg.zip][rootPath:/src2][isExported:true][attributes:javadoc_location=/P/efg.zip]\n" + + "/P/lib5.jar[CPE_LIBRARY][K_BINARY][sourcePath:/P/xyz.zip][rootPath:/src3][isExported:true]\n" + + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + + // Test that passing empty array of referencedEntries clears all the earlier ones. + p.setRawClasspath(newRawClasspath, new IClasspathEntry[]{}, p.getOutputLocation(), null); + resolvedClasspath = p.getResolvedClasspath(true); + assertClasspathEquals(resolvedClasspath, + "/P[CPE_SOURCE][K_SOURCE][isExported:false]\n" + + ""+ getExternalJCLPathString() + "[CPE_LIBRARY][K_BINARY][isExported:false]\n" + + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib5.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib2.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + + } finally { + deleteProject("P"); + } +} +/** + * Additional tests for bug 252431. + * Test that duplicate referenced entries or entries that are already present in the raw classpath + * are excluded from the referenced entries when invoking + * {@link IJavaProject#setRawClasspath(IClasspathEntry[], IClasspathEntry[], IPath, IProgressMonitor)} + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=252431" + * @throws Exception + */ +public void testBug252341c() throws Exception { + try { + IJavaProject p = createJavaProject("P"); + addLibrary(p, "lib1.jar", null, new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib3.jar lib4.jar\n", + }, + JavaCore.VERSION_1_4); + + addLibrary(p, "lib2.jar", null, new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib3.jar lib5.jar\n", + }, + JavaCore.VERSION_1_4); + createFile("/P/lib3.jar", ""); + createFile("/P/lib4.jar", ""); + createFile("/P/lib5.jar", ""); + + IClasspathEntry[] rawClasspath = p.getRawClasspath(); + + IClasspathEntry[] rawEntries = new IClasspathEntry[2]; + rawEntries[0] = JavaCore.newLibraryEntry(new Path("/P/lib1.jar"), null, null, true); + rawEntries[1] = JavaCore.newLibraryEntry(new Path("/P/lib2.jar"), null, null, true); + + // Test that the referenced classpath entries has the appropriate referencingEntry value + IClasspathEntry[] chains = JavaCore.getReferencedClasspathEntries(rawEntries[0], p); + + IClasspathEntry[] referencedEntries = new IClasspathEntry[5]; + referencedEntries[0] = chains[0]; + referencedEntries[1] = chains[1]; + + chains = JavaCore.getReferencedClasspathEntries(rawEntries[1], p); + + referencedEntries[2] = chains[0]; + referencedEntries[3] = chains[1]; + referencedEntries[4] = chains[1]; + + p.setRawClasspath(rawClasspath, referencedEntries, p.getOutputLocation(), null); + + p.close(); + p.open(null); + + IClasspathEntry[] storedReferencedEnties = p.getReferencedClasspathEntries(); + assertClasspathEquals(storedReferencedEnties, + "/P/lib3.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib4.jar[CPE_LIBRARY][K_BINARY][isExported:true]\n" + + "/P/lib5.jar[CPE_LIBRARY][K_BINARY][isExported:true]"); + } + finally { + deleteProject("P"); + } +} +/** + * @bug 304081:IJavaProject#isOnClasspath(IJavaElement) returns false for type from referenced JAR + * When the JAR, which a variable classpath entry resolves to, references other JAR via + * MANIFEST, test that {@link IJavaProject#isOnClasspath(IJavaElement)} returns true + * for the referenced classpath entries. + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=304081" + * @throws Exception + */ +public void testBug304081() throws Exception { + File libDir = null; + try { + + IJavaProject proj = this.createJavaProject("P", new String[] {}, "bin"); + IPath libPath = proj.getResource().getLocation(); + JavaCore.setClasspathVariable("MyVar", libPath, null); + libDir = new File(libPath.toPortableString()); + IClasspathEntry[] classpath = new IClasspathEntry[1]; + File libJar = new File(libDir, "variable.jar"); + libJar.createNewFile(); + + addLibrary(proj, "variable.jar", null, new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib1.jar\n", + }, + JavaCore.VERSION_1_4); + + createFile("/P/lib1.jar", ""); + + classpath[0] = JavaCore.newVariableEntry(new Path( + "/MyVar/variable.jar"), null, null); + + proj.setRawClasspath(classpath, null); + waitForAutoBuild(); + IProject project = getWorkspaceRoot().getProject("P"); + IResource resource = project.getFile("variable.jar"); + assertTrue(proj.isOnClasspath(resource)); + IJavaElement element = proj.getPackageFragmentRoot(resource); + assertTrue(proj.isOnClasspath(element)); + + resource = project.getFile("lib1.jar"); + assertTrue(proj.isOnClasspath(resource)); + element = proj.getPackageFragmentRoot(resource); + assertTrue(proj.isOnClasspath(element)); + } finally { + this.deleteProject("P"); + JavaCore.removeClasspathVariable("MyVar", null); + } +} +/** + * Additional tests for 304081 + * When the JAR, which is in the raw classpath, references other JAR via + * MANIFEST, test that {@link IJavaProject#isOnClasspath(IJavaElement)} returns true + * for the referenced classpath entries. + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=304081" + * @throws Exception + */ +public void testBug304081a() throws Exception { + try { + + IJavaProject proj = this.createJavaProject("P", new String[] {}, "bin"); + IClasspathEntry[] classpath = new IClasspathEntry[1]; + + addLibrary(proj, "library.jar", null, new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib1.jar\n", + }, + JavaCore.VERSION_1_4); + createFile("/P/lib1.jar", ""); + classpath[0] = JavaCore.newLibraryEntry(new Path("/P/library.jar"), null, null); + + proj.setRawClasspath(classpath, null); + waitForAutoBuild(); + IProject project = getWorkspaceRoot().getProject("P"); + IResource resource = project.getFile("library.jar"); + assertTrue(proj.isOnClasspath(resource)); + IJavaElement element = proj.getPackageFragmentRoot(resource); + assertTrue(proj.isOnClasspath(element)); + + resource = project.getFile("lib1.jar"); + assertTrue(proj.isOnClasspath(resource)); + element = proj.getPackageFragmentRoot(resource); + assertTrue(proj.isOnClasspath(element)); + } finally { + this.deleteProject("P"); + } +} +/** + * Additional tests for 304081 + * When the JAR, which is part of a classpath container, references other JAR via + * MANIFEST, test that {@link IJavaProject#isOnClasspath(IJavaElement)} returns true + * for the referenced classpath entries. + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=304081" + * @throws Exception + */ +public void testBug304081b() throws Exception { + File libDir = null; + try { + + IJavaProject proj = this.createJavaProject("P", new String[] {}, "bin"); + IClasspathEntry[] classpath = new IClasspathEntry[1]; + libDir = new File(proj.getResource().getLocation().toPortableString()); + File libJar = new File(libDir, "container.jar"); + + addLibrary(proj, "container.jar", null, new String[0], + new String[] { + "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\n" + + "Class-Path: lib1.jar\n", + }, + JavaCore.VERSION_1_4); + createFile("/P/lib1.jar", ""); + + ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(JavaCore.USER_LIBRARY_CONTAINER_ID); + String libraryName = "TestUserLibrary"; + IPath containerPath = new Path(JavaCore.USER_LIBRARY_CONTAINER_ID); + UserLibraryClasspathContainer containerSuggestion = new UserLibraryClasspathContainer(libraryName); + initializer.requestClasspathContainerUpdate(containerPath.append(libraryName), null, containerSuggestion); + + IEclipsePreferences preferences = new InstanceScope().getNode(JavaCore.PLUGIN_ID); + String propertyName = JavaModelManager.CP_USERLIBRARY_PREFERENCES_PREFIX+"TestUserLibrary"; + StringBuffer propertyValue = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<userlibrary systemlibrary=\"false\" version=\"1\">\r\n<archive"); + propertyValue.append(" path=\"" + libJar.getAbsolutePath()); + propertyValue.append("\"/>\r\n</userlibrary>\r\n"); + preferences.put(propertyName, propertyValue.toString()); + preferences.flush(); + + classpath[0] = JavaCore.newContainerEntry(containerSuggestion.getPath()); + + proj.setRawClasspath(classpath, null); + waitForAutoBuild(); + IProject project = getWorkspaceRoot().getProject("P"); + IResource resource = project.getFile("container.jar"); + assertTrue(proj.isOnClasspath(resource)); + IJavaElement element = proj.getPackageFragmentRoot(resource); + assertTrue(proj.isOnClasspath(element)); + + resource = project.getFile("lib1.jar"); + assertTrue(proj.isOnClasspath(resource)); + element = proj.getPackageFragmentRoot(resource); + assertTrue(proj.isOnClasspath(element)); + + } finally { + this.deleteProject("P"); + } +} } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompilationUnitTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompilationUnitTests.java index 0c41a516e..4b1509a32 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompilationUnitTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompilationUnitTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -2436,4 +2436,37 @@ public void testBug248312() throws CoreException{ annotations); } +public void testBug246594() throws CoreException { + createWorkingCopy( + "package p;\n" + + "public class Z<T extends Object & I<? super T>> {\n" + + "}\n" + + "public interface I<T> {}" + ); + IType type = this.workingCopy.getType("Z"); + ITypeParameter[] typeParameters = type.getTypeParameters(); + assertStringsEqual("Type parameter signature", "T:QObject;:QI<-QT;>;\n", type.getTypeParameterSignatures()); + assertStringsEqual("Type parameter bounds signatures", + "QObject;\n" + + "QI<-QT;>;\n", + typeParameters[0].getBoundsSignatures()); +} +public void testBug246594a() throws CoreException { + createWorkingCopy( + "package p;\n" + + "interface Collection<E> {\n" + + "public <T> boolean containsAll(Collection<T> c);\n" + + "public <T extends E & I<? super String>> boolean addAll(Collection<T> c);\n" + + "}" + + "public interface I<T> {}"); + IMethod[] methods = this.workingCopy.getType("Collection").getMethods();//<T:TE;> + ITypeParameter[] typeParameters = methods[1].getTypeParameters(); + assertStringsEqual("Type parameter bounds signatures", + "QE;\n" + + "QI<-QString;>;\n", + typeParameters[0].getBoundsSignatures()); + +} + + } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompletionTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompletionTests.java index 6edbf0fc3..90b9b58c3 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompletionTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompletionTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20600,4 +20600,170 @@ public void test276526d() throws JavaModelException { requestor.getResults()); } +// https://bugs.eclipse.org/bugs/show_bug.cgi?id=287939 +// To verify that auto complete works after instance of expression when content assist is requested on a field +// Code assist requested in a local variable declaration statement +public void testBug287939a() throws JavaModelException { + this.workingCopies = new ICompilationUnit[1]; + this.workingCopies[0] = getWorkingCopy( + "/Completion/src/test/CompletionAfterInstanceOf.java", + "package test;\n" + + "public class CompletionAfterInstanceOf {\n" + + " public int returnZero(){ return 0;}\n" + + " public Object a;\n" + + " void bar(){\n" + + " if (this.a instanceof CompletionAfterInstanceOf) {\n" + + " int i = this.a.r\n" + + " int j = 0;\n" + + " int k = 2;\n" + + " int p = 12;\n" + + " }\n" + + "}\n"); + + CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true, false, true, true, true, true); + requestor.allowAllRequiredProposals(); + String str = this.workingCopies[0].getSource(); + String completeBehind = "this.a.r"; + int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length(); + this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner); + + int relevance1 = R_DEFAULT + R_RESOLVED + R_INTERESTING + R_CASE + R_NON_STATIC + R_NON_RESTRICTED + R_EXACT_EXPECTED_TYPE; + int start1 = str.lastIndexOf("r") + "".length(); + int end1 = start1 + "r".length(); + int start2 = str.lastIndexOf("this.a.r"); + int end2 = start2 + "this.a.r".length(); + int start3 = str.lastIndexOf("this.a."); + int end3 = start3 + "this.a".length(); + + assertResults( + "expectedTypesSignatures={I}\n" + + "expectedTypesKeys={I}", + requestor.getContext()); + assertResults( + "returnZero[METHOD_REF_WITH_CASTED_RECEIVER]{((CompletionAfterInstanceOf)this.a).returnZero(), Ltest.CompletionAfterInstanceOf;, ()I, Ltest.CompletionAfterInstanceOf;, returnZero, null, replace["+start2+", "+end2+"], token["+start1+", "+end1+"], receiver["+start3+", "+end3+"], " + (relevance1) + "}", + requestor.getResults()); +} + +// https://bugs.eclipse.org/bugs/show_bug.cgi?id=287939 +// To verify that auto complete works after instance of expression when content assist is requested on a field +// Code assist requested in an assignment statement +public void testBug287939b() throws JavaModelException { + this.workingCopies = new ICompilationUnit[1]; + this.workingCopies[0] = getWorkingCopy( + "/Completion/src/test/CompletionAfterInstanceOf.java", + "package test;\n" + + "public class CompletionAfterInstanceOf {\n" + + " public int returnZero(){ return 0;}\n" + + " public Object a;\n" + + " void bar(){\n" + + " int i;\n" + + " if (this.a instanceof CompletionAfterInstanceOf) {\n" + + " i = this.a.r\n" + + " }\n" + + "}\n"); + + CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true, false, true, true, true, true); + requestor.allowAllRequiredProposals(); + String str = this.workingCopies[0].getSource(); + String completeBehind = "this.a.r"; + int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length(); + this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner); + + int relevance1 = R_DEFAULT + R_RESOLVED + R_INTERESTING + R_CASE + R_NON_STATIC + R_NON_RESTRICTED + R_EXACT_EXPECTED_TYPE; + int start1 = str.lastIndexOf("r") + "".length(); + int end1 = start1 + "r".length(); + int start2 = str.lastIndexOf("this.a.r"); + int end2 = start2 + "this.a.r".length(); + int start3 = str.lastIndexOf("this.a."); + int end3 = start3 + "this.a".length(); + + assertResults( + "expectedTypesSignatures={I}\n" + + "expectedTypesKeys={I}", + requestor.getContext()); + assertResults( + "returnZero[METHOD_REF_WITH_CASTED_RECEIVER]{((CompletionAfterInstanceOf)this.a).returnZero(), Ltest.CompletionAfterInstanceOf;, ()I, Ltest.CompletionAfterInstanceOf;, returnZero, null, replace["+start2+", "+end2+"], token["+start1+", "+end1+"], receiver["+start3+", "+end3+"], " + (relevance1) + "}", + requestor.getResults()); +} + +// https://bugs.eclipse.org/bugs/show_bug.cgi?id=287939 +// To verify that auto complete works after instance of expression when content assist is requested on a local variable +// Code assist requested in an assignment statement +public void testBug287939c() throws JavaModelException { + this.workingCopies = new ICompilationUnit[1]; + this.workingCopies[0] = getWorkingCopy( + "/Completion/src/test/CompletionAfterInstanceOf.java", + "package test;\n" + + "public class CompletionAfterInstanceOf {\n" + + " public int returnZero(){ return 0;}\n" + + " void bar(Object a){\n" + + " int i;\n" + + " if (a instanceof CompletionAfterInstanceOf) {" + + " i = a.r\n" + + " }\n" + + "}\n"); + + CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true, false, true, true, true, true); + requestor.allowAllRequiredProposals(); + String str = this.workingCopies[0].getSource(); + String completeBehind = "a.r"; + int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length(); + this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner); + + int relevance1 = R_DEFAULT + R_RESOLVED + R_INTERESTING + R_CASE + R_NON_STATIC + R_NON_RESTRICTED + R_EXACT_EXPECTED_TYPE; + int start1 = str.lastIndexOf("r") + "".length(); + int end1 = start1 + "r".length(); + int start2 = str.lastIndexOf("a.r"); + int end2 = start2 + "a.r".length(); + int start3 = str.lastIndexOf("a."); + int end3 = start3 + "a".length(); + + assertResults( + "expectedTypesSignatures={I}\n" + + "expectedTypesKeys={I}", + requestor.getContext()); + assertResults( + "returnZero[METHOD_REF_WITH_CASTED_RECEIVER]{((CompletionAfterInstanceOf)a).returnZero(), Ltest.CompletionAfterInstanceOf;, ()I, Ltest.CompletionAfterInstanceOf;, returnZero, null, replace["+start2+", "+end2+"], token["+start1+", "+end1+"], receiver["+start3+", "+end3+"], " + (relevance1) + "}", + requestor.getResults()); +} + +// https://bugs.eclipse.org/bugs/show_bug.cgi?id=287939 +// To verify that auto complete works after instance of expression when content assist is requested on a local variable +// Code assist requested in a local variable declaration statement +public void testBug287939d() throws JavaModelException { + this.workingCopies = new ICompilationUnit[1]; + this.workingCopies[0] = getWorkingCopy( + "/Completion/src/test/CompletionAfterInstanceOf.java", + "package test;\n" + + "public class CompletionAfterInstanceOf {\n" + + " public int returnZero(){ return 0;}\n" + + " void bar(Object a){\n" + + " if (a instanceof CompletionAfterInstanceOf) {" + + " int i = a.r\n" + + " }\n" + + "}\n"); + + CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true, false, true, true, true, true); + requestor.allowAllRequiredProposals(); + String str = this.workingCopies[0].getSource(); + String completeBehind = "a.r"; + int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length(); + this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner); + + int relevance1 = R_DEFAULT + R_RESOLVED + R_INTERESTING + R_CASE + R_NON_STATIC + R_NON_RESTRICTED + R_EXACT_EXPECTED_TYPE; + int start1 = str.lastIndexOf("r") + "".length(); + int end1 = start1 + "r".length(); + int start2 = str.lastIndexOf("a.r"); + int end2 = start2 + "a.r".length(); + int start3 = str.lastIndexOf("a."); + int end3 = start3 + "a".length(); + + assertResults( + "expectedTypesSignatures={I}\n" + + "expectedTypesKeys={I}", + requestor.getContext()); + assertResults( + "returnZero[METHOD_REF_WITH_CASTED_RECEIVER]{((CompletionAfterInstanceOf)a).returnZero(), Ltest.CompletionAfterInstanceOf;, ()I, Ltest.CompletionAfterInstanceOf;, returnZero, null, replace["+start2+", "+end2+"], token["+start1+", "+end1+"], receiver["+start3+", "+end3+"], " + (relevance1) + "}", + requestor.getResults()); +} } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchBugsTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchBugsTests.java index 113d18967..8a676f8e3 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchBugsTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchBugsTests.java @@ -24,6 +24,7 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IWorkspaceDescription; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; @@ -11461,4 +11462,83 @@ public void testBug296343() throws Exception { } } +/** + * @bug 304841: [search] NPE in IndexSelector.initializeIndexLocations + * @test Ensure that no NPE occurs when searching for a reference in a CU without primary type + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=304841" + */ +public void testBug304841() throws Exception { + boolean autoBuild = getWorkspace().isAutoBuilding(); + IWorkspaceDescription preferences = getWorkspace().getDescription(); + try { + // ensure that the workspace auto-build is ON + preferences.setAutoBuilding(true); + getWorkspace().setDescription(preferences); + + // create test case + IJavaProject project = createJavaProject("P"); + createFolder("/P/p"); + createFile( + "/P/p/Hello.java", + "package p;\n" + + "class One {\n" + + "}\n" + + "class Two {\n" + + "}\n" + ); + createFile( + "/P/p/Ref.java", + "package p;\n" + + "class Three {\n" + + " Two two;\n" + + "}\n" + ); + waitUntilIndexesReady(); + + // perform search + final ICompilationUnit cu = getCompilationUnit("/P/p/Hello.java"); + IType type = cu.getType("Two"); + SearchPattern pattern = SearchPattern.createPattern(type, REFERENCES); + MatchLocator.setFocus(pattern, type); + new SearchEngine().search( + pattern, + new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, + SearchEngine.createJavaSearchScope(new IJavaElement[] { project }), + this.resultCollector, + null + ); + assertSearchResults( + "p/Ref.java p.Three.two [Two] EXACT_MATCH" + ); + } finally { + preferences.setAutoBuilding(autoBuild); + getWorkspace().setDescription(preferences); + deleteProject("P"); + } +} +public void testBug304841b() throws Exception { + boolean autoBuild = getWorkspace().isAutoBuilding(); + IWorkspaceDescription preferences = getWorkspace().getDescription(); + try { + // ensure that the workspace auto-build is ON + preferences.setAutoBuilding(true); + getWorkspace().setDescription(preferences); + + // perform search + IType type = getClassFile("/JavaSearchBugs/lib/Bug148380.class").getType(); + SearchPattern pattern = SearchPattern.createPattern(type, REFERENCES); + MatchLocator.setFocus(pattern, type); + new SearchEngine().search( + pattern, + new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, + getJavaSearchScope(), + this.resultCollector, + null + ); + assertSearchResults(""); // No expected results, only verify that no CCE occurs + } finally { + preferences.setAutoBuilding(autoBuild); + getWorkspace().setDescription(preferences); + } +} }
\ No newline at end of file diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchTests.java index ed6fe6801..36fc8f969 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchTests.java @@ -661,6 +661,7 @@ public void testZIPArchive1() throws Exception { getExternalResourcePath("externalLib.abc")); IJavaProject p = createJavaProject("P", new String[0], new String[] {getExternalResourcePath("externalLib.abc")}, ""); refreshExternalArchives(p); + waitUntilIndexesReady(); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaProject[] {getJavaProject("P")}); search("foo", METHOD, DECLARATIONS, scope); @@ -688,6 +689,7 @@ public void testZIPArchive2() throws Exception { }, getExternalResourcePath("externalLib.abc")); refreshExternalArchives(p); + waitUntilIndexesReady(); TypeNameMatchCollector collector = new TypeNameMatchCollector(); new SearchEngine(this.workingCopies).searchAllTypeNames( diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ResolveTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ResolveTests.java index 535d6c2ac..065d3b953 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ResolveTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ResolveTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,10 +12,20 @@ package org.eclipse.jdt.core.tests.model; import java.io.IOException; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jdt.core.*; +import junit.framework.Test; -import junit.framework.*; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jdt.core.IClassFile; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.ILocalVariable; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.WorkingCopyOwner; public class ResolveTests extends AbstractJavaModelTests { ICompilationUnit wc = null; @@ -2546,5 +2556,36 @@ public void testInvalidMethod2() throws JavaModelException { elements ); } +// https://bugs.eclipse.org/bugs/show_bug.cgi?id=235658 +// To verify that "open declaration" works for a protected interface, which is +// an inner type of an extending class's superclass. +public void testInterfaceX() throws JavaModelException { + this.workingCopies = new ICompilationUnit[2]; + this.workingCopies[0] = getWorkingCopy( + "/Resolve/src/test/Bug.java", + "package test;\n"+ + "public class Bug {\n" + + " void foo() {}\n" + + " protected interface Proto {}\n" + + "}\n"); + + this.workingCopies[1] = getWorkingCopy( + "/Resolve/src/Type.java", + "import test.Bug;\n"+ + "import test.Bug.*;\n"+ + "class Type extends Bug implements Proto {\n" + + "}\n"); + + String str = this.workingCopies[1].getSource(); + int start = str.lastIndexOf("Proto"); + int length = "Proto".length(); + IJavaElement[] elements = this.workingCopies[1].codeSelect(start, length, this.wcOwner); + + assertElementsEqual( + "Unexpected elements", + "Proto [in Bug [in [Working copy] Bug.java [in test [in src [in Resolve]]]]]", + elements + ); +} } diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/SignatureTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/SignatureTests.java index b2820cfec..236554371 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/SignatureTests.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/SignatureTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,7 +39,7 @@ static { // Prefix for tests names to run // TESTS_PREFIX = "testGetTypeErasure"; // Names of tests to run: can be "testBugXXXX" or "BugXXXX") -// TESTS_NAMES = new String[] { "testGetSimpleName" }; +// TESTS_NAMES = new String[] { "testToStringMethod13" }; // Numbers of tests to run: "test<number>" will be run for each number of this array // TESTS_NUMBERS = new int[] { 8 }; // Range numbers of tests to run: all tests between "test<first>" and "test<last>" will be run for { first, last } @@ -267,6 +267,14 @@ public void testGetParameterCount17() { Signature.getParameterCount(methodSig)); } /* + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=267432 + */ +public void testGetParameterCount19() { + String methodSig= "<TYPE:Ljava/lang/Object;>(Ljava/lang/Object;Ljava/lang/Class<TTYPE;>;)TTYPE;"; + assertEquals("Signature#getParameterCount is not correct", 2, + Signature.getParameterCount(methodSig)); +} +/* * Ensures that a signature with a '? extends ?' wildcard can be decoded. * (regression test for bug 92370 [1.5] IAE in Signature.getParameterCount(..) for method proposal on capture type receiver) */ @@ -280,9 +288,9 @@ public void testGetParameterCount18() { */ public void testGetParameterTypes() { String methodSig = "(QString;QObject;I)I"; - String[] types= Signature.getParameterTypes(methodSig); - assertEquals("Signature#getParameterTypes is not correct1", 3, types.length); - assertEquals("Signature#getParameterTypes is not correct2", "QObject;", types[1]); + String[] parameterTypes = Signature.getParameterTypes(methodSig); + assertEquals("Signature#getParameterTypes is not correct1", 3, parameterTypes.length); + assertEquals("Signature#getParameterTypes is not correct2", "QObject;", parameterTypes[1]); try { Signature.getParameterTypes(""); assertTrue("Signature#getParameterTypes is not correct: exception", false); @@ -292,60 +300,75 @@ public void testGetParameterTypes() { // primitive types methodSig = "(BCDFIJSVZ)V"; + parameterTypes = Signature.getParameterTypes(methodSig); assertEquals("Signature#getParameterTypes 4", 9, - Signature.getParameterTypes(methodSig).length); + parameterTypes.length); assertEquals("Signature#getParameterTypes 4", "B", - Signature.getParameterTypes(methodSig)[0]); + parameterTypes[0]); assertEquals("Signature#getParameterTypes 4", "C", - Signature.getParameterTypes(methodSig)[1]); + parameterTypes[1]); assertEquals("Signature#getParameterTypes 4", "D", - Signature.getParameterTypes(methodSig)[2]); + parameterTypes[2]); assertEquals("Signature#getParameterTypes 4", "F", - Signature.getParameterTypes(methodSig)[3]); + parameterTypes[3]); assertEquals("Signature#getParameterTypes 4", "I", - Signature.getParameterTypes(methodSig)[4]); + parameterTypes[4]); assertEquals("Signature#getParameterTypes 4", "J", - Signature.getParameterTypes(methodSig)[5]); + parameterTypes[5]); assertEquals("Signature#getParameterTypes 4", "S", - Signature.getParameterTypes(methodSig)[6]); + parameterTypes[6]); assertEquals("Signature#getParameterTypes 4", "V", - Signature.getParameterTypes(methodSig)[7]); + parameterTypes[7]); assertEquals("Signature#getParameterTypes 4", "Z", - Signature.getParameterTypes(methodSig)[8]); + parameterTypes[8]); // array types methodSig = "([I[[J[[[B[Qstring;[Tv;[Lstring;)V"; + parameterTypes = Signature.getParameterTypes(methodSig); assertEquals("Signature#getParameterTypes 5", 6, - Signature.getParameterTypes(methodSig).length); + parameterTypes.length); assertEquals("Signature#getParameterTypes 5", "[I", - Signature.getParameterTypes(methodSig)[0]); + parameterTypes[0]); assertEquals("Signature#getParameterTypes 5", "[[J", - Signature.getParameterTypes(methodSig)[1]); + parameterTypes[1]); assertEquals("Signature#getParameterTypes 5", "[[[B", - Signature.getParameterTypes(methodSig)[2]); + parameterTypes[2]); assertEquals("Signature#getParameterTypes 5", "[Qstring;", - Signature.getParameterTypes(methodSig)[3]); + parameterTypes[3]); assertEquals("Signature#getParameterTypes 5", "[Tv;", - Signature.getParameterTypes(methodSig)[4]); + parameterTypes[4]); assertEquals("Signature#getParameterTypes 5", "[Lstring;", - Signature.getParameterTypes(methodSig)[5]); + parameterTypes[5]); // resolved types methodSig = "(La;)V"; - assertEquals("Signature#getParameterTypes 6", 1, - Signature.getParameterTypes(methodSig).length); - assertEquals("Signature#getParameterTypes 6", "La;", - Signature.getParameterTypes(methodSig)[0]); + parameterTypes = Signature.getParameterTypes(methodSig); + assertEquals("Signature#getParameterTypes 6", 1, parameterTypes.length); + assertEquals("Signature#getParameterTypes 6", "La;", parameterTypes[0]); + methodSig = "(La<TE;>;)V"; + parameterTypes = Signature.getParameterTypes(methodSig); assertEquals("Signature#getParameterTypes 6", 1, - Signature.getParameterTypes(methodSig).length); + parameterTypes.length); assertEquals("Signature#getParameterTypes 6", "La<TE;>;", - Signature.getParameterTypes(methodSig)[0]); - methodSig = "(La/b/c<TE;>.d<TF;>;)V"; + parameterTypes[0]); + + methodSig = "(La.b.c<TE;>.d<TF;>;)V"; + parameterTypes = Signature.getParameterTypes(methodSig); assertEquals("Signature#getParameterTypes 6", 1, - Signature.getParameterTypes(methodSig).length); - assertEquals("Signature#getParameterTypes 6", "La/b/c<TE;>.d<TF;>;", - Signature.getParameterTypes(methodSig)[0]); + parameterTypes.length); + assertEquals("Signature#getParameterTypes 6", "La.b.c<TE;>.d<TF;>;", + parameterTypes[0]); + + // signature with type variable + methodSig = "<TYPE:Ljava.lang.Object;>(Ljava.lang.Object;Ljava.lang.Class<TTYPE;>;)TTYPE;"; + parameterTypes = Signature.getParameterTypes(methodSig); + assertEquals("Signature#getParameterTypes 7", 2, + parameterTypes.length); + assertEquals("Signature#getParameterTypes 7", "Ljava.lang.Object;", + parameterTypes[0]); + assertEquals("Signature#getParameterTypes 7", "Ljava.lang.Class<TTYPE;>;", + parameterTypes[1]); } /** * @see Signature @@ -1070,7 +1093,6 @@ public void testToStringMethod12() { } assertTrue("Should get an exception", false); } - /** * Test the toString() signature of an inner type. */ diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/UtilTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/UtilTests.java new file mode 100644 index 000000000..ab1311043 --- /dev/null +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/UtilTests.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.core.tests.model; + +import org.eclipse.jdt.internal.core.util.Util; + +import junit.framework.Test; + +public class UtilTests extends AbstractJavaModelTests { + + static { +// TESTS_PREFIX = "testInvalidCompilerOptions"; +// TESTS_NAMES = new String[] { "test028"}; + } + + public UtilTests(String name) { + super(name); + } + + public static Test suite() { + return buildModelTestSuite(UtilTests.class); + } + public void test001() { + String[] arguments = Util.getProblemArgumentsFromMarker("1:foo"); + assertStringsEqual("Wrong arguments", new String[] {"foo"}, arguments); + } + public void test002() { + String[] arguments = Util.getProblemArgumentsFromMarker("2:foo#bar"); + assertStringsEqual("Wrong arguments", new String[] {"foo", "bar"}, arguments); + } + public void test003() { + String[] arguments = Util.getProblemArgumentsFromMarker("1: "); + assertStringsEqual("Wrong arguments", new String[] {""}, arguments); + } + public void test004() { + String[] arguments = Util.getProblemArgumentsFromMarker("0:"); + assertStringsEqual("Wrong arguments", new String[0], arguments); + } + public void test005() { + String[] arguments = Util.getProblemArgumentsFromMarker("3:Task<capture##1-of ?>#getTaskListeners# "); + assertStringsEqual("Wrong arguments", new String[] {"Task<capture#1-of ?>", "getTaskListeners", ""}, arguments); + } + public void test006() { + String[] arguments = new String[] {"Task<capture#1-of ?>", "getTaskListeners", ""}; + String[] result = Util.getProblemArgumentsFromMarker(Util.getProblemArgumentsForMarker(arguments)); + assertStringsEqual("Wrong arguments", arguments, result); + } + public void test007() { + assertNull("Not null", Util.getProblemArgumentsFromMarker("tt:Task<capture##1-of ?>#getTaskListeners# ")); + } + public void test008() { + assertNull("Not null", Util.getProblemArgumentsFromMarker("3Task<capture##1-of ?>#getTaskListeners# ")); + } + public void test009() { + assertNull("Not null", Util.getProblemArgumentsFromMarker(null)); + } + public void test010() { + assertNull("Not null", Util.getProblemArgumentsFromMarker("0:Task")); + } + public void test011() { + String[] arguments = new String[] {"", "", ""}; + String[] result = Util.getProblemArgumentsFromMarker(Util.getProblemArgumentsForMarker(arguments)); + assertStringsEqual("Wrong arguments", arguments, result); + } + public void test012() { + String[] arguments = new String[] {"foo#test", "bar"}; + String[] result = Util.getProblemArgumentsFromMarker(Util.getProblemArgumentsForMarker(arguments)); + assertStringsEqual("Wrong arguments", arguments, result); + } +}
\ No newline at end of file diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/describing/ImportRewriteTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/describing/ImportRewriteTest.java index 254855995..d53ac2a2a 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/describing/ImportRewriteTest.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/describing/ImportRewriteTest.java @@ -26,6 +26,8 @@ import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jdt.core.tests.model.AbstractJavaModelTests; @@ -300,6 +302,39 @@ public class ImportRewriteTest extends AbstractJavaModelTests { assertEqualString(cu.getSource(), buf.toString()); } + public void testAddImports5() throws Exception { + getJavaProject("P").setOption(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON, JavaCore.INSERT); + + IPackageFragment pack1= this.sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + String[] order= new String[] { "java", "java.util", "com", "pack" }; + + ImportRewrite imports= newImportsRewrite(cu, order, 1, 1, true); + imports.setUseContextToFilterImplicitImports(true); + imports.addImport("java.util.Map"); + imports.addImport("java.util.Set"); + imports.addImport("java.util.Map.Entry"); + imports.addImport("java.util.Collections"); + + apply(imports); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.* ;\n"); + buf.append("import java.util.Map.Entry ;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + public void testAddImportsWithGroupsOfUnmatched1() throws Exception { IPackageFragment pack1= this.sourceFolder.createPackageFragment("pack1", false, null); @@ -446,6 +481,57 @@ public class ImportRewriteTest extends AbstractJavaModelTests { assertEqualString(cu.getSource(), buf.toString()); } + public void testRemoveImports3() throws Exception { + IPackageFragment pack= this.sourceFolder.createPackageFragment("pack", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack;\n"); + buf.append("\n"); + buf.append("public class A {\n"); + buf.append(" public class Inner {\n"); + buf.append(" }\n"); + buf.append("}\n"); + pack.createCompilationUnit("A.java", buf.toString(), false, null); + + IPackageFragment test1= this.sourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("\n"); + buf.append("import pack.A;\n"); + buf.append("import pack.A.Inner;\n"); + buf.append("import pack.A.NotThere;\n"); + buf.append("import pack.B;\n"); + buf.append("import pack.B.Inner;\n"); + buf.append("import pack.B.NotThere;\n"); + buf.append("\n"); + buf.append("public class T {\n"); + buf.append("}\n"); + ICompilationUnit cuT= test1.createCompilationUnit("T.java", buf.toString(), false, null); + + ASTParser parser= ASTParser.newParser(AST.JLS3); + parser.setSource(cuT); + parser.setResolveBindings(true); + CompilationUnit astRoot= (CompilationUnit) parser.createAST(null); + + ImportRewrite imports= newImportsRewrite(astRoot, new String[0], 99, 99, true); + imports.setUseContextToFilterImplicitImports(true); + + imports.removeImport("pack.A.Inner"); + imports.removeImport("pack.A.NotThere"); + imports.removeImport("pack.B.Inner"); + imports.removeImport("pack.B.NotThere"); + + apply(imports); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("\n"); + buf.append("import pack.A;\n"); + buf.append("import pack.B;\n"); + buf.append("\n"); + buf.append("public class T {\n"); + buf.append("}\n"); + assertEqualString(cuT.getSource(), buf.toString()); + } public void testAddImports_bug23078() throws Exception { @@ -572,6 +658,145 @@ public class ImportRewriteTest extends AbstractJavaModelTests { assertEqualString(cu.getSource(), buf.toString()); } + /** + * Test that the Inner class import comes in the right order (i.e. after the enclosing type's import) when re-organized + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=194358" + */ + public void testBug194358() throws Exception { + + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import pack2.A;\n"); + buf.append("import pack2.A.Inner;\n"); + buf.append("import pack2.B;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append("}\n"); + + IPackageFragment pack1= this.sourceFolder.createPackageFragment("pack1", false, null); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + // We need to actually make some state in the AST for the classes, to test that we can + // disambiguate between packages and inner classes (see the bug for details). + IPackageFragment pack2= this.sourceFolder.createPackageFragment("pack2", false, null); + ICompilationUnit aUnit= pack2.createCompilationUnit("A.java", "", false, null); + ICompilationUnit bUnit= pack2.createCompilationUnit("B.java", "", false, null); + bUnit.createType("class B {}", null, false, null); + + IType aType= aUnit.createType("class A {}", null, false, null); + aType.createType("class Inner {}", null, false, null); + String[] order= new String[] { "java" }; + + ImportRewrite imports= newImportsRewrite(cu, order, 99, 99, false); + imports.setUseContextToFilterImplicitImports(true); + imports.addImport("pack2.A"); + imports.addImport("pack2.B"); + imports.addImport("pack2.A.Inner"); + + apply(imports); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import pack2.A;\n"); + buf.append("import pack2.A.Inner;\n"); + buf.append("import pack2.B;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + /** + * Test that a valid inner class import is not removed even when the container + * class is implicitly available. This tests the case where the classes are in + * different compilation units. + * + * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=194358" + */ + public void testBug194358a() throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package com.pack1;\n"); + buf.append("\n"); + buf.append("import com.pack1.A;\n"); + buf.append("import com.pack1.A.Inner;\n"); + buf.append("import com.pack2.B;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append("}\n"); + + IPackageFragment pack1= this.sourceFolder.createPackageFragment("com.pack1", false, null); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + ICompilationUnit aUnit= pack1.createCompilationUnit("A.java", "", false, null); + + IPackageFragment pack2= this.sourceFolder.createPackageFragment("com.pack2", false, null); + ICompilationUnit bUnit= pack2.createCompilationUnit("B.java", "", false, null); + bUnit.createType("class B {}", null, false, null); + IType aType= aUnit.createType("class A {}", null, false, null); + aType.createType("class Inner {}", null, false, null); + String[] order= new String[] { "java" }; + + ImportRewrite imports= newImportsRewrite(cu, order, 99, 99, false); + imports.setUseContextToFilterImplicitImports(false); + imports.addImport("com.pack1.A"); + imports.addImport("com.pack1.A.Inner"); + imports.addImport("com.pack2.B"); + + apply(imports); + + buf= new StringBuffer(); + buf.append("package com.pack1;\n"); + buf.append("\n"); + buf.append("import com.pack1.A.Inner;\n"); + buf.append("import com.pack2.B;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + /** + * Test that the Inner type imports are not removed while organizing even though the + * containing class is implicitly available - for the case when both the classes are + * in the same compilation unit + * + * see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=235253" + */ + public void testBug235253() throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package bug;\n"); + buf.append("\n"); + buf.append("class Bug {\n"); + buf.append("public void addFile(File file) {}\n"); + buf.append("\tinterface Proto{};\n"); + buf.append("}\n"); + buf.append("class Foo implements Proto{}"); + + IPackageFragment pack1= this.sourceFolder.createPackageFragment("bug", false, null); + ICompilationUnit cu= pack1.createCompilationUnit("Bug.java", buf.toString(), false, null); + String[] order= new String[] { "bug" , "java" }; + ImportRewrite imports= newImportsRewrite(cu, order, 99, 99, false); + imports.setUseContextToFilterImplicitImports(true); + imports.addImport("bug.Bug.Proto"); + imports.addImport("java.io.File"); + + apply(imports); + buf = new StringBuffer(); + buf.append("package bug;\n"); + buf.append("\n"); + buf.append("import bug.Bug.Proto;\n"); + buf.append("\n"); + buf.append("import java.io.File;\n"); + buf.append("\n"); + buf.append("class Bug {\n"); + buf.append("public void addFile(File file) {}\n"); + buf.append("\tinterface Proto{};\n"); + buf.append("}\n"); + buf.append("class Foo implements Proto{}"); + assertEqualString(cu.getSource(), buf.toString()); + } + public void testAddStaticImports1() throws Exception { IPackageFragment pack1= this.sourceFolder.createPackageFragment("pack1", false, null); @@ -1007,6 +1232,14 @@ public class ImportRewriteTest extends AbstractJavaModelTests { return rewrite; } + protected ImportRewrite newImportsRewrite(CompilationUnit cu, String[] order, int normalThreshold, int staticThreshold, boolean restoreExistingImports) { + ImportRewrite rewrite= ImportRewrite.create(cu, restoreExistingImports); + rewrite.setImportOrder(order); + rewrite.setOnDemandImportThreshold(normalThreshold); + rewrite.setStaticOnDemandImportThreshold(staticThreshold); + return rewrite; + } + private void apply(ImportRewrite rewrite) throws CoreException, MalformedTreeException, BadLocationException { TextEdit edit= rewrite.rewriteImports(null); diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/modifying/ASTRewritingModifyingCopyTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/modifying/ASTRewritingModifyingCopyTest.java index 8965012aa..46b478a51 100644 --- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/modifying/ASTRewritingModifyingCopyTest.java +++ b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/modifying/ASTRewritingModifyingCopyTest.java @@ -14,10 +14,29 @@ import java.util.List; import junit.framework.Test; +import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IPackageFragment; - -import org.eclipse.jdt.core.dom.*; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.Block; +import org.eclipse.jdt.core.dom.CatchClause; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.ExpressionStatement; +import org.eclipse.jdt.core.dom.FieldAccess; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.PrimitiveType; +import org.eclipse.jdt.core.dom.QualifiedName; +import org.eclipse.jdt.core.dom.SingleVariableDeclaration; +import org.eclipse.jdt.core.dom.Statement; +import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; +import org.eclipse.jdt.core.dom.ThrowStatement; +import org.eclipse.jdt.core.dom.TryStatement; +import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.tests.util.Util; public class ASTRewritingModifyingCopyTest extends ASTRewritingModifyingTest { @@ -342,30 +361,30 @@ public class ASTRewritingModifyingCopyTest extends ASTRewritingModifyingTest { astRoot.recordModifications(); TypeDeclaration type = (TypeDeclaration) astRoot.types().get(0); - AST ast = type.getAST(); + AST ast = type.getAST(); - MethodDeclaration m = ast.newMethodDeclaration(); - type.bodyDeclarations().add(m); + MethodDeclaration m = ast.newMethodDeclaration(); + type.bodyDeclarations().add(m); - Block block = ast.newBlock(); - m.setName(ast.newSimpleName("foo")); - m.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID)); - m.setBody(block); + Block block = ast.newBlock(); + m.setName(ast.newSimpleName("foo")); + m.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID)); + m.setBody(block); - FieldAccess fa = ast.newFieldAccess(); - fa.setExpression(ast.newThisExpression()); - fa.setName(ast.newSimpleName("x")); - MethodInvocation mi = ast.newMethodInvocation(); - mi.setExpression(fa); - mi.setName(ast.newSimpleName("llall")); + FieldAccess fa = ast.newFieldAccess(); + fa.setExpression(ast.newThisExpression()); + fa.setName(ast.newSimpleName("x")); + MethodInvocation mi = ast.newMethodInvocation(); + mi.setExpression(fa); + mi.setName(ast.newSimpleName("llall")); - ExpressionStatement exp = ast.newExpressionStatement(mi); - block.statements().add(exp); + ExpressionStatement exp = ast.newExpressionStatement(mi); + block.statements().add(exp); - StructuralPropertyDescriptor loc = mi.getLocationInParent(); - //This will cause the bug - ASTNode node = ASTNode.copySubtree(ast, fa); - exp.setStructuralProperty(loc, node); + StructuralPropertyDescriptor loc = mi.getLocationInParent(); + //This will cause the bug + ASTNode node = ASTNode.copySubtree(ast, fa); + exp.setStructuralProperty(loc, node); String preview = evaluateRewrite(cu, astRoot); @@ -375,58 +394,179 @@ public class ASTRewritingModifyingCopyTest extends ASTRewritingModifyingTest { buf.append(" void foo(){this.x;} }"); assertEqualString(Util.convertToIndependantLineDelimiter(preview), Util.convertToIndependantLineDelimiter(buf.toString())); } + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304656 + public void test0008() throws Exception { + IPackageFragment pack1= this.sourceFolder.createPackageFragment("test0008", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test0008;\n" + + "\n" + + "public class TestClass {\n" + + " Thread t = new Thread(new Runnable(){\n" + + "\n" + + " @Override\n" + + " public void run() {\n" + + " try {\n" + + " Thread.currentThread().sleep(1000);\n" + + " } catch (InterruptedException e) {\n" + + " e.printStackTrace();\n" + + " }\n" + + " }\n" + + " \n" + + " });\n" + + "\n" + + " public void testMethod(){\n" + + " t.start();\n" + + " }\n" + + "\n" + + " public static Thread staticTestMethod(Thread thread){\n" + + " return thread;\n" + + " }\n" + + "}"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + ASTParser astParser = ASTParser.newParser(AST.JLS3); + astParser.setSource(cu); + ASTNode root = astParser.createAST(new NullProgressMonitor()); + AST ast = root.getAST(); + + CompilationUnit compilationUnit = (CompilationUnit) root; + compilationUnit.recordModifications(); + List types = compilationUnit.types(); + for (int i = 0, max = types.size(); i < max; i++) { + TypeDeclaration td = (TypeDeclaration) types.get(i); + MethodDeclaration[] methods = td.getMethods(); + for (int j = 0, max2 = methods.length; j < max2; j++) { + MethodDeclaration md = methods[j]; + if (md.getName().getFullyQualifiedName().equals("testMethod")) { + List statements = md.getBody().statements(); + ExpressionStatement es = (ExpressionStatement) statements.get(0); + MethodInvocation mi = (MethodInvocation) es.getExpression(); + Expression existingExpression = mi.getExpression(); + MethodInvocation threadNameInvocation = ast.newMethodInvocation(); + threadNameInvocation.setExpression(null); + threadNameInvocation.setName(ast.newSimpleName("staticTestMethod")); + existingExpression.delete(); + threadNameInvocation.arguments().add(existingExpression); + mi.setExpression(threadNameInvocation); + + + Block code = md.getBody(); + TryStatement tryStatement = ast.newTryStatement(); + List catches = tryStatement.catchClauses(); + // create catch clause + CatchClause catchClause = ast.newCatchClause(); + // exception to catch + SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); + svd.setType(ast.newSimpleType(ast.newName("Throwable"))); + svd.setName(ast.newSimpleName("e")); + catchClause.setException(svd); + // code to run on catch + Block catchBody = ast.newBlock(); + List catchStatements = catchBody.statements(); + // throw statement + ThrowStatement throwStatement = ast.newThrowStatement(); + Expression throwExpression = ast.newName("e"); + throwStatement.setExpression(throwExpression); + catchStatements.add(throwStatement); + catches.add(catchClause); + // create finally statement + Block finallyBlock = ast.newBlock(); + statements = code.statements(); + tryStatement.setFinally(finallyBlock); + code.delete(); + tryStatement.setBody(code); + Block tryBlock = ast.newBlock(); + tryBlock.statements().add(tryStatement); + md.setBody(tryBlock); + } + } + + } + String preview = evaluateRewrite(cu, compilationUnit); + + buf= new StringBuffer(); + buf.append("package test0008;\n"); + buf.append("\n"); + buf.append("public class TestClass {\n"); + buf.append(" Thread t = new Thread(new Runnable(){\n"); + buf.append("\n"); + buf.append(" @Override\n"); + buf.append(" public void run() {\n"); + buf.append(" try {\n"); + buf.append(" Thread.currentThread().sleep(1000);\n"); + buf.append(" } catch (InterruptedException e) {\n"); + buf.append(" e.printStackTrace();\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" });\n"); + buf.append("\n"); + buf.append(" public void testMethod(){\n"); + buf.append(" try {\n"); + buf.append(" staticTestMethod(t).start();\n"); + buf.append(" } catch (Throwable e) {\n"); + buf.append(" } finally {\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" public static Thread staticTestMethod(Thread thread){\n"); + buf.append(" return thread;\n"); + buf.append(" }\n"); + buf.append("}"); + assertEqualString(Util.convertToIndependantLineDelimiter(preview), Util.convertToIndependantLineDelimiter(buf.toString())); + } -// public void test0007() throws Exception { -// IPackageFragment pack1= fSourceFolder.createPackageFragment("test0007", false, null); -// StringBuffer buf= new StringBuffer(); -// buf.append("package test0007;\n"); -// buf.append("\n"); -// buf.append("public class X {\n"); -// buf.append(" /**\n"); -// buf.append(" * NOTHING\n"); -// buf.append(" */\n"); -// buf.append(" void foo() {\n"); -// buf.append(" \n"); -// buf.append(" }\n"); -// buf.append(" void bar() {\n"); -// buf.append(" \n"); -// buf.append(" }\n"); -// buf.append("}\n"); -// ICompilationUnit cu= pack1.createCompilationUnit("X.java", buf.toString(), false, null); -// -// CompilationUnit astRoot= parseCompilationUnit(cu, false); -// -// astRoot.recordModifications(); -// -// AST a = astRoot.getAST(); -// -// List types = astRoot.types(); -// TypeDeclaration typeDeclaration = (TypeDeclaration)types.get(0); -// MethodDeclaration methodDeclaration1 = typeDeclaration.getMethods()[0]; -// MethodDeclaration methodDeclaration2 = typeDeclaration.getMethods()[1]; -// Javadoc javadoc1 = methodDeclaration1.getJavadoc(); -// Javadoc javadoc2 = (Javadoc)ASTNode.copySubtree(a, javadoc1); -// methodDeclaration2.setJavadoc(javadoc2); -// -// String preview = evaluateRewrite(cu, astRoot); -// -// buf= new StringBuffer(); -// buf.append("package test0007;\n"); -// buf.append("\n"); -// buf.append("public class X {\n"); -// buf.append(" /**\n"); -// buf.append(" * NOTHING\n"); -// buf.append(" */\n"); -// buf.append(" void foo() {\n"); -// buf.append(" \n"); -// buf.append(" }\n"); -// buf.append(" /**\n"); -// buf.append(" * NOTHING\n"); -// buf.append(" */\n"); -// buf.append(" void bar() {\n"); -// buf.append(" \n"); -// buf.append(" }\n"); -// buf.append("}\n"); -// assertEqualString(Util.convertToIndependantLineDelimiter(preview), Util.convertToIndependantLineDelimiter(buf.toString())); -// } + // public void test0007() throws Exception { + // IPackageFragment pack1= fSourceFolder.createPackageFragment("test0007", false, null); + // StringBuffer buf= new StringBuffer(); + // buf.append("package test0007;\n"); + // buf.append("\n"); + // buf.append("public class X {\n"); + // buf.append(" /**\n"); + // buf.append(" * NOTHING\n"); + // buf.append(" */\n"); + // buf.append(" void foo() {\n"); + // buf.append(" \n"); + // buf.append(" }\n"); + // buf.append(" void bar() {\n"); + // buf.append(" \n"); + // buf.append(" }\n"); + // buf.append("}\n"); + // ICompilationUnit cu= pack1.createCompilationUnit("X.java", buf.toString(), false, null); + // + // CompilationUnit astRoot= parseCompilationUnit(cu, false); + // + // astRoot.recordModifications(); + // + // AST a = astRoot.getAST(); + // + // List types = astRoot.types(); + // TypeDeclaration typeDeclaration = (TypeDeclaration)types.get(0); + // MethodDeclaration methodDeclaration1 = typeDeclaration.getMethods()[0]; + // MethodDeclaration methodDeclaration2 = typeDeclaration.getMethods()[1]; + // Javadoc javadoc1 = methodDeclaration1.getJavadoc(); + // Javadoc javadoc2 = (Javadoc)ASTNode.copySubtree(a, javadoc1); + // methodDeclaration2.setJavadoc(javadoc2); + // + // String preview = evaluateRewrite(cu, astRoot); + // + // buf= new StringBuffer(); + // buf.append("package test0007;\n"); + // buf.append("\n"); + // buf.append("public class X {\n"); + // buf.append(" /**\n"); + // buf.append(" * NOTHING\n"); + // buf.append(" */\n"); + // buf.append(" void foo() {\n"); + // buf.append(" \n"); + // buf.append(" }\n"); + // buf.append(" /**\n"); + // buf.append(" * NOTHING\n"); + // buf.append(" */\n"); + // buf.append(" void bar() {\n"); + // buf.append(" \n"); + // buf.append(" }\n"); + // buf.append("}\n"); + // assertEqualString(Util.convertToIndependantLineDelimiter(preview), Util.convertToIndependantLineDelimiter(buf.toString())); + // } } |