• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- unittest/Format/FormatTestJava.cpp - Formatting tests for Java -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "FormatTestUtils.h"
11 #include "clang/Format/Format.h"
12 #include "llvm/Support/Debug.h"
13 #include "gtest/gtest.h"
14 
15 #define DEBUG_TYPE "format-test"
16 
17 namespace clang {
18 namespace format {
19 
20 class FormatTestJava : public ::testing::Test {
21 protected:
format(llvm::StringRef Code,unsigned Offset,unsigned Length,const FormatStyle & Style)22   static std::string format(llvm::StringRef Code, unsigned Offset,
23                             unsigned Length, const FormatStyle &Style) {
24     DEBUG(llvm::errs() << "---\n");
25     DEBUG(llvm::errs() << Code << "\n\n");
26     std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
27     tooling::Replacements Replaces = reformat(Style, Code, Ranges);
28     std::string Result = applyAllReplacements(Code, Replaces);
29     EXPECT_NE("", Result);
30     DEBUG(llvm::errs() << "\n" << Result << "\n\n");
31     return Result;
32   }
33 
34   static std::string
format(llvm::StringRef Code,const FormatStyle & Style=getGoogleStyle (FormatStyle::LK_Java))35   format(llvm::StringRef Code,
36          const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_Java)) {
37     return format(Code, 0, Code.size(), Style);
38   }
39 
getStyleWithColumns(unsigned ColumnLimit)40   static FormatStyle getStyleWithColumns(unsigned ColumnLimit) {
41     FormatStyle Style = getGoogleStyle(FormatStyle::LK_Java);
42     Style.ColumnLimit = ColumnLimit;
43     return Style;
44   }
45 
verifyFormat(llvm::StringRef Code,const FormatStyle & Style=getGoogleStyle (FormatStyle::LK_Java))46   static void verifyFormat(
47       llvm::StringRef Code,
48       const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_Java)) {
49     EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
50   }
51 };
52 
TEST_F(FormatTestJava,NoAlternativeOperatorNames)53 TEST_F(FormatTestJava, NoAlternativeOperatorNames) {
54   verifyFormat("someObject.and();");
55 }
56 
TEST_F(FormatTestJava,UnderstandsCasts)57 TEST_F(FormatTestJava, UnderstandsCasts) {
58   verifyFormat("a[b >> 1] = (byte) (c() << 4);");
59 }
60 
TEST_F(FormatTestJava,FormatsInstanceOfLikeOperators)61 TEST_F(FormatTestJava, FormatsInstanceOfLikeOperators) {
62   FormatStyle Style = getStyleWithColumns(50);
63   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
64                "    instanceof bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
65                Style);
66   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
67   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaa instanceof\n"
68                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
69                Style);
70   verifyFormat("return aaaaaaaaaaaaaaaaaaa instanceof bbbbbbbbbbbbbbbbbbbbbbb\n"
71                "    && ccccccccccccccccccc instanceof dddddddddddddddddddddd;");
72 }
73 
TEST_F(FormatTestJava,Chromium)74 TEST_F(FormatTestJava, Chromium) {
75   verifyFormat("class SomeClass {\n"
76                "    void f() {}\n"
77                "    int g() {\n"
78                "        return 0;\n"
79                "    }\n"
80                "    void h() {\n"
81                "        while (true) f();\n"
82                "        for (;;) f();\n"
83                "        if (true) f();\n"
84                "    }\n"
85                "}",
86                getChromiumStyle(FormatStyle::LK_Java));
87 }
88 
TEST_F(FormatTestJava,QualifiedNames)89 TEST_F(FormatTestJava, QualifiedNames) {
90   verifyFormat("public some.package.Type someFunction( // comment\n"
91                "    int parameter) {}");
92 }
93 
TEST_F(FormatTestJava,ClassKeyword)94 TEST_F(FormatTestJava, ClassKeyword) {
95   verifyFormat("SomeClass.class.getName();");
96   verifyFormat("Class c = SomeClass.class;");
97 }
98 
TEST_F(FormatTestJava,ClassDeclarations)99 TEST_F(FormatTestJava, ClassDeclarations) {
100   verifyFormat("public class SomeClass {\n"
101                "  private int a;\n"
102                "  private int b;\n"
103                "}");
104   verifyFormat("public class A {\n"
105                "  class B {\n"
106                "    int i;\n"
107                "  }\n"
108                "  class C {\n"
109                "    int j;\n"
110                "  }\n"
111                "}");
112   verifyFormat("public class A extends B.C {}");
113 
114   verifyFormat("abstract class SomeClass\n"
115                "    extends SomeOtherClass implements SomeInterface {}",
116                getStyleWithColumns(60));
117   verifyFormat("abstract class SomeClass extends SomeOtherClass\n"
118                "    implements SomeInterfaceeeeeeeeeeeee {}",
119                getStyleWithColumns(60));
120   verifyFormat("abstract class SomeClass\n"
121                "    extends SomeOtherClass\n"
122                "    implements SomeInterface {}",
123                getStyleWithColumns(40));
124   verifyFormat("abstract class SomeClass\n"
125                "    extends SomeOtherClass\n"
126                "    implements SomeInterface,\n"
127                "               AnotherInterface {}",
128                getStyleWithColumns(40));
129   verifyFormat("abstract class SomeClass\n"
130                "    implements SomeInterface, AnotherInterface {}",
131                getStyleWithColumns(60));
132   verifyFormat("@SomeAnnotation()\n"
133                "abstract class aaaaaaaaaaaa\n"
134                "    extends bbbbbbbbbbbbbbb implements cccccccccccc {}",
135                getStyleWithColumns(76));
136   verifyFormat("@SomeAnnotation()\n"
137                "abstract class aaaaaaaaa<a>\n"
138                "    extends bbbbbbbbbbbb<b> implements cccccccccccc {}",
139                getStyleWithColumns(76));
140   verifyFormat("interface SomeInterface<A> extends Foo, Bar {\n"
141                "  void doStuff(int theStuff);\n"
142                "  void doMoreStuff(int moreStuff);\n"
143                "}");
144   verifyFormat("public interface SomeInterface {\n"
145                "  void doStuff(int theStuff);\n"
146                "  void doMoreStuff(int moreStuff);\n"
147                "}");
148   verifyFormat("@interface SomeInterface {\n"
149                "  void doStuff(int theStuff);\n"
150                "  void doMoreStuff(int moreStuff);\n"
151                "}");
152   verifyFormat("public @interface SomeInterface {\n"
153                "  void doStuff(int theStuff);\n"
154                "  void doMoreStuff(int moreStuff);\n"
155                "}");
156 }
157 
TEST_F(FormatTestJava,AnonymousClasses)158 TEST_F(FormatTestJava, AnonymousClasses) {
159   verifyFormat("return new A() {\n"
160                "  public String toString() {\n"
161                "    return \"NotReallyA\";\n"
162                "  }\n"
163                "};");
164   verifyFormat("A a = new A() {\n"
165                "  public String toString() {\n"
166                "    return \"NotReallyA\";\n"
167                "  }\n"
168                "};");
169 }
170 
TEST_F(FormatTestJava,EnumDeclarations)171 TEST_F(FormatTestJava, EnumDeclarations) {
172   verifyFormat("enum SomeThing { ABC, CDE }");
173   verifyFormat("enum SomeThing {\n"
174                "  ABC,\n"
175                "  CDE,\n"
176                "}");
177   verifyFormat("public class SomeClass {\n"
178                "  enum SomeThing { ABC, CDE }\n"
179                "  void f() {}\n"
180                "}");
181   verifyFormat("public class SomeClass implements SomeInterface {\n"
182                "  enum SomeThing { ABC, CDE }\n"
183                "  void f() {}\n"
184                "}");
185   verifyFormat("enum SomeThing {\n"
186                "  ABC,\n"
187                "  CDE;\n"
188                "  void f() {}\n"
189                "}");
190   verifyFormat("enum SomeThing {\n"
191                "  ABC(1, \"ABC\"),\n"
192                "  CDE(2, \"CDE\");\n"
193                "  Something(int i, String s) {}\n"
194                "}");
195   verifyFormat("enum SomeThing {\n"
196                "  ABC(new int[] {1, 2}),\n"
197                "  CDE(new int[] {2, 3});\n"
198                "  Something(int[] i) {}\n"
199                "}");
200   verifyFormat("public enum SomeThing {\n"
201                "  ABC {\n"
202                "    public String toString() {\n"
203                "      return \"ABC\";\n"
204                "    }\n"
205                "  },\n"
206                "  CDE {\n"
207                "    @Override\n"
208                "    public String toString() {\n"
209                "      return \"CDE\";\n"
210                "    }\n"
211                "  };\n"
212                "  public void f() {}\n"
213                "}");
214   verifyFormat("private enum SomeEnum implements Foo<?, B> {\n"
215                "  ABC {\n"
216                "    @Override\n"
217                "    public String toString() {\n"
218                "      return \"ABC\";\n"
219                "    }\n"
220                "  },\n"
221                "  CDE {\n"
222                "    @Override\n"
223                "    public String toString() {\n"
224                "      return \"CDE\";\n"
225                "    }\n"
226                "  };\n"
227                "}");
228 }
229 
TEST_F(FormatTestJava,ArrayInitializers)230 TEST_F(FormatTestJava, ArrayInitializers) {
231   verifyFormat("new int[] {1, 2, 3, 4};");
232   verifyFormat("new int[] {\n"
233                "    1, 2, 3, 4,\n"
234                "};");
235 
236   FormatStyle Style = getStyleWithColumns(65);
237   Style.Cpp11BracedListStyle = false;
238   verifyFormat(
239       "expected = new int[] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n"
240       "  100, 100, 100, 100, 100, 100, 100, 100, 100, 100 };",
241       Style);
242 }
243 
TEST_F(FormatTestJava,ThrowsDeclarations)244 TEST_F(FormatTestJava, ThrowsDeclarations) {
245   verifyFormat("public void doSooooooooooooooooooooooooooomething()\n"
246                "    throws LooooooooooooooooooooooooooooongException {}");
247   verifyFormat("public void doSooooooooooooooooooooooooooomething()\n"
248                "    throws LoooooooooongException, LooooooooooongException {}");
249 }
250 
TEST_F(FormatTestJava,Annotations)251 TEST_F(FormatTestJava, Annotations) {
252   verifyFormat("@Override\n"
253                "public String toString() {}");
254   verifyFormat("@Override\n"
255                "@Nullable\n"
256                "public String getNameIfPresent() {}");
257   verifyFormat("@Override // comment\n"
258                "@Nullable\n"
259                "public String getNameIfPresent() {}");
260   verifyFormat("@java.lang.Override // comment\n"
261                "@Nullable\n"
262                "public String getNameIfPresent() {}");
263 
264   verifyFormat("@SuppressWarnings(value = \"unchecked\")\n"
265                "public void doSomething() {}");
266   verifyFormat("@SuppressWarnings(value = \"unchecked\")\n"
267                "@Author(name = \"abc\")\n"
268                "public void doSomething() {}");
269 
270   verifyFormat("DoSomething(new A() {\n"
271                "  @Override\n"
272                "  public String toString() {}\n"
273                "});");
274 
275   verifyFormat("void SomeFunction(@Nullable String something) {}");
276   verifyFormat("void SomeFunction(@org.llvm.Nullable String something) {}");
277 
278   verifyFormat("@Partial @Mock DataLoader loader;");
279   verifyFormat("@Partial\n"
280                "@Mock\n"
281                "DataLoader loader;",
282                getChromiumStyle(FormatStyle::LK_Java));
283   verifyFormat("@SuppressWarnings(value = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")\n"
284                "public static int iiiiiiiiiiiiiiiiiiiiiiii;");
285 
286   verifyFormat("@SomeAnnotation(\"With some really looooooooooooooong text\")\n"
287                "private static final long something = 0L;");
288   verifyFormat("@org.llvm.Qualified(\"With some really looooooooooong text\")\n"
289                "private static final long something = 0L;");
290   verifyFormat("@Mock\n"
291                "DataLoader loooooooooooooooooooooooader =\n"
292                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
293                getStyleWithColumns(60));
294   verifyFormat("@org.llvm.QualifiedMock\n"
295                "DataLoader loooooooooooooooooooooooader =\n"
296                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
297                getStyleWithColumns(60));
298   verifyFormat("@Test(a)\n"
299                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
300                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa);");
301   verifyFormat("@SomeAnnotation(\n"
302                "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa)\n"
303                "int i;",
304                getStyleWithColumns(50));
305   verifyFormat("@Test\n"
306                "ReturnType doSomething(\n"
307                "    String aaaaaaaaaaaaa, String bbbbbbbbbbbbbbb) {}",
308                getStyleWithColumns(60));
309   verifyFormat("{\n"
310                "  boolean someFunction(\n"
311                "      @Param(aaaaaaaaaaaaaaaa) String aaaaa,\n"
312                "      String bbbbbbbbbbbbbbb) {}\n"
313                "}",
314                getStyleWithColumns(60));
315 }
316 
TEST_F(FormatTestJava,Generics)317 TEST_F(FormatTestJava, Generics) {
318   verifyFormat("Iterable<?> a;");
319   verifyFormat("Iterable<?> a;");
320   verifyFormat("Iterable<? extends SomeObject> a;");
321 
322   verifyFormat("A.<B>doSomething();");
323 
324   verifyFormat("@Override\n"
325                "public Map<String, ?> getAll() {}");
326 
327   verifyFormat("public <R> ArrayList<R> get() {}");
328   verifyFormat("protected <R> ArrayList<R> get() {}");
329   verifyFormat("private <R> ArrayList<R> get() {}");
330   verifyFormat("public static <R> ArrayList<R> get() {}");
331   verifyFormat("public static native <R> ArrayList<R> get();");
332   verifyFormat("public final <X> Foo foo() {}");
333   verifyFormat("public abstract <X> Foo foo();");
334   verifyFormat("<T extends B> T getInstance(Class<T> type);");
335   verifyFormat("Function<F, ? extends T> function;");
336 
337   verifyFormat("private Foo<X, Y>[] foos;");
338   verifyFormat("Foo<X, Y>[] foos = this.foos;");
339   verifyFormat("return (a instanceof List<?>)\n"
340                "    ? aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
341                "    : aaaaaaaaaaaaaaaaaaaaaaa;",
342                getStyleWithColumns(60));
343 
344   verifyFormat(
345       "SomeLoooooooooooooooooooooongType name =\n"
346       "    SomeType.foo(someArgument)\n"
347       "        .<X>method()\n"
348       "        .aaaaaaaaaaaaaaaaaaa()\n"
349       "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
350 }
351 
TEST_F(FormatTestJava,StringConcatenation)352 TEST_F(FormatTestJava, StringConcatenation) {
353   verifyFormat("String someString = \"abc\"\n"
354                "    + \"cde\";");
355 }
356 
TEST_F(FormatTestJava,TryCatchFinally)357 TEST_F(FormatTestJava, TryCatchFinally) {
358   verifyFormat("try {\n"
359                "  Something();\n"
360                "} catch (SomeException e) {\n"
361                "  HandleException(e);\n"
362                "}");
363   verifyFormat("try {\n"
364                "  Something();\n"
365                "} finally {\n"
366                "  AlwaysDoThis();\n"
367                "}");
368   verifyFormat("try {\n"
369                "  Something();\n"
370                "} catch (SomeException e) {\n"
371                "  HandleException(e);\n"
372                "} finally {\n"
373                "  AlwaysDoThis();\n"
374                "}");
375 
376   verifyFormat("try {\n"
377                "  Something();\n"
378                "} catch (SomeException | OtherException e) {\n"
379                "  HandleException(e);\n"
380                "}");
381 }
382 
TEST_F(FormatTestJava,TryWithResources)383 TEST_F(FormatTestJava, TryWithResources) {
384   verifyFormat("try (SomeResource rs = someFunction()) {\n"
385                "  Something();\n"
386                "}");
387   verifyFormat("try (SomeResource rs = someFunction()) {\n"
388                "  Something();\n"
389                "} catch (SomeException e) {\n"
390                "  HandleException(e);\n"
391                "}");
392 }
393 
TEST_F(FormatTestJava,SynchronizedKeyword)394 TEST_F(FormatTestJava, SynchronizedKeyword) {
395   verifyFormat("synchronized (mData) {\n"
396                "  // ...\n"
397                "}");
398 }
399 
TEST_F(FormatTestJava,AssertKeyword)400 TEST_F(FormatTestJava, AssertKeyword) {
401   verifyFormat("assert a && b;");
402 }
403 
TEST_F(FormatTestJava,PackageDeclarations)404 TEST_F(FormatTestJava, PackageDeclarations) {
405   verifyFormat("package some.really.loooooooooooooooooooooong.package;",
406                getStyleWithColumns(50));
407 }
408 
TEST_F(FormatTestJava,ImportDeclarations)409 TEST_F(FormatTestJava, ImportDeclarations) {
410   verifyFormat("import some.really.loooooooooooooooooooooong.imported.Class;",
411                getStyleWithColumns(50));
412   verifyFormat("import static some.really.looooooooooooooooong.imported.Class;",
413                getStyleWithColumns(50));
414 }
415 
TEST_F(FormatTestJava,MethodDeclarations)416 TEST_F(FormatTestJava, MethodDeclarations) {
417   verifyFormat("void methodName(Object arg1,\n"
418                "    Object arg2, Object arg3) {}",
419                getStyleWithColumns(40));
420   verifyFormat("void methodName(\n"
421                "    Object arg1, Object arg2) {}",
422                getStyleWithColumns(40));
423 }
424 
TEST_F(FormatTestJava,CppKeywords)425 TEST_F(FormatTestJava, CppKeywords) {
426   verifyFormat("public void union(Type a, Type b);");
427   verifyFormat("public void struct(Object o);");
428   verifyFormat("public void delete(Object o);");
429 }
430 
TEST_F(FormatTestJava,NeverAlignAfterReturn)431 TEST_F(FormatTestJava, NeverAlignAfterReturn) {
432   verifyFormat("return aaaaaaaaaaaaaaaaaaa\n"
433                "    && bbbbbbbbbbbbbbbbbbb\n"
434                "    && ccccccccccccccccccc;",
435                getStyleWithColumns(40));
436   verifyFormat("return (result == null)\n"
437                "    ? aaaaaaaaaaaaaaaaa\n"
438                "    : bbbbbbbbbbbbbbbbb;",
439                getStyleWithColumns(40));
440   verifyFormat("return aaaaaaaaaaaaaaaaaaa()\n"
441                "    .bbbbbbbbbbbbbbbbbbb()\n"
442                "    .ccccccccccccccccccc();",
443                getStyleWithColumns(40));
444   verifyFormat("return aaaaaaaaaaaaaaaaaaa()\n"
445                "    .bbbbbbbbbbbbbbbbbbb(\n"
446                "        ccccccccccccccc)\n"
447                "    .ccccccccccccccccccc();",
448                getStyleWithColumns(40));
449 }
450 
TEST_F(FormatTestJava,FormatsInnerBlocks)451 TEST_F(FormatTestJava, FormatsInnerBlocks) {
452   verifyFormat("someObject.someFunction(new Runnable() {\n"
453                "  @Override\n"
454                "  public void run() {\n"
455                "    System.out.println(42);\n"
456                "  }\n"
457                "}, someOtherParameter);");
458   verifyFormat("someFunction(new Runnable() {\n"
459                "  public void run() {\n"
460                "    System.out.println(42);\n"
461                "  }\n"
462                "});");
463   verifyFormat("someObject.someFunction(\n"
464                "    new Runnable() {\n"
465                "      @Override\n"
466                "      public void run() {\n"
467                "        System.out.println(42);\n"
468                "      }\n"
469                "    },\n"
470                "    new Runnable() {\n"
471                "      @Override\n"
472                "      public void run() {\n"
473                "        System.out.println(43);\n"
474                "      }\n"
475                "    },\n"
476                "    someOtherParameter);");
477 }
478 
TEST_F(FormatTestJava,FormatsLambdas)479 TEST_F(FormatTestJava, FormatsLambdas) {
480   verifyFormat("(aaaaaaaaaa, bbbbbbbbbb) -> aaaaaaaaaa + bbbbbbbbbb;");
481   verifyFormat("(aaaaaaaaaa, bbbbbbbbbb)\n"
482                "    -> aaaaaaaaaa + bbbbbbbbbb;",
483                getStyleWithColumns(40));
484   verifyFormat("Runnable someLambda = () -> DoSomething();");
485   verifyFormat("Runnable someLambda = () -> {\n"
486                "  DoSomething();\n"
487                "}");
488 
489   verifyFormat("Runnable someLambda =\n"
490                "    (int aaaaa) -> DoSomething(aaaaa);",
491                getStyleWithColumns(40));
492 }
493 
TEST_F(FormatTestJava,BreaksStringLiterals)494 TEST_F(FormatTestJava, BreaksStringLiterals) {
495   // FIXME: String literal breaking is currently disabled for Java and JS, as it
496   // requires strings to be merged using "+" which we don't support.
497   EXPECT_EQ("\"some text other\";",
498             format("\"some text other\";", getStyleWithColumns(14)));
499 }
500 
TEST_F(FormatTestJava,AlignsBlockComments)501 TEST_F(FormatTestJava, AlignsBlockComments) {
502   EXPECT_EQ("/*\n"
503             " * Really multi-line\n"
504             " * comment.\n"
505             " */\n"
506             "void f() {}",
507             format("  /*\n"
508                    "   * Really multi-line\n"
509                    "   * comment.\n"
510                    "   */\n"
511                    "  void f() {}"));
512 }
513 
514 } // end namespace tooling
515 } // end namespace clang
516