• 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     auto Result = applyAllReplacements(Code, Replaces);
29     EXPECT_TRUE(static_cast<bool>(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   verifyFormat("@Annotation(\"Some\"\n"
316                "    + \" text\")\n"
317                "List<Integer> list;");
318 }
319 
TEST_F(FormatTestJava,Generics)320 TEST_F(FormatTestJava, Generics) {
321   verifyFormat("Iterable<?> a;");
322   verifyFormat("Iterable<?> a;");
323   verifyFormat("Iterable<? extends SomeObject> a;");
324 
325   verifyFormat("A.<B>doSomething();");
326 
327   verifyFormat("@Override\n"
328                "public Map<String, ?> getAll() {}");
329 
330   verifyFormat("public <R> ArrayList<R> get() {}");
331   verifyFormat("protected <R> ArrayList<R> get() {}");
332   verifyFormat("private <R> ArrayList<R> get() {}");
333   verifyFormat("public static <R> ArrayList<R> get() {}");
334   verifyFormat("public static native <R> ArrayList<R> get();");
335   verifyFormat("public final <X> Foo foo() {}");
336   verifyFormat("public abstract <X> Foo foo();");
337   verifyFormat("<T extends B> T getInstance(Class<T> type);");
338   verifyFormat("Function<F, ? extends T> function;");
339 
340   verifyFormat("private Foo<X, Y>[] foos;");
341   verifyFormat("Foo<X, Y>[] foos = this.foos;");
342   verifyFormat("return (a instanceof List<?>)\n"
343                "    ? aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
344                "    : aaaaaaaaaaaaaaaaaaaaaaa;",
345                getStyleWithColumns(60));
346 
347   verifyFormat(
348       "SomeLoooooooooooooooooooooongType name =\n"
349       "    SomeType.foo(someArgument)\n"
350       "        .<X>method()\n"
351       "        .aaaaaaaaaaaaaaaaaaa()\n"
352       "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
353 }
354 
TEST_F(FormatTestJava,StringConcatenation)355 TEST_F(FormatTestJava, StringConcatenation) {
356   verifyFormat("String someString = \"abc\"\n"
357                "    + \"cde\";");
358 }
359 
TEST_F(FormatTestJava,TryCatchFinally)360 TEST_F(FormatTestJava, TryCatchFinally) {
361   verifyFormat("try {\n"
362                "  Something();\n"
363                "} catch (SomeException e) {\n"
364                "  HandleException(e);\n"
365                "}");
366   verifyFormat("try {\n"
367                "  Something();\n"
368                "} finally {\n"
369                "  AlwaysDoThis();\n"
370                "}");
371   verifyFormat("try {\n"
372                "  Something();\n"
373                "} catch (SomeException e) {\n"
374                "  HandleException(e);\n"
375                "} finally {\n"
376                "  AlwaysDoThis();\n"
377                "}");
378 
379   verifyFormat("try {\n"
380                "  Something();\n"
381                "} catch (SomeException | OtherException e) {\n"
382                "  HandleException(e);\n"
383                "}");
384 }
385 
TEST_F(FormatTestJava,TryWithResources)386 TEST_F(FormatTestJava, TryWithResources) {
387   verifyFormat("try (SomeResource rs = someFunction()) {\n"
388                "  Something();\n"
389                "}");
390   verifyFormat("try (SomeResource rs = someFunction()) {\n"
391                "  Something();\n"
392                "} catch (SomeException e) {\n"
393                "  HandleException(e);\n"
394                "}");
395 }
396 
TEST_F(FormatTestJava,SynchronizedKeyword)397 TEST_F(FormatTestJava, SynchronizedKeyword) {
398   verifyFormat("synchronized (mData) {\n"
399                "  // ...\n"
400                "}");
401 }
402 
TEST_F(FormatTestJava,AssertKeyword)403 TEST_F(FormatTestJava, AssertKeyword) {
404   verifyFormat("assert a && b;");
405 }
406 
TEST_F(FormatTestJava,PackageDeclarations)407 TEST_F(FormatTestJava, PackageDeclarations) {
408   verifyFormat("package some.really.loooooooooooooooooooooong.package;",
409                getStyleWithColumns(50));
410 }
411 
TEST_F(FormatTestJava,ImportDeclarations)412 TEST_F(FormatTestJava, ImportDeclarations) {
413   verifyFormat("import some.really.loooooooooooooooooooooong.imported.Class;",
414                getStyleWithColumns(50));
415   verifyFormat("import static some.really.looooooooooooooooong.imported.Class;",
416                getStyleWithColumns(50));
417 }
418 
TEST_F(FormatTestJava,MethodDeclarations)419 TEST_F(FormatTestJava, MethodDeclarations) {
420   verifyFormat("void methodName(Object arg1,\n"
421                "    Object arg2, Object arg3) {}",
422                getStyleWithColumns(40));
423   verifyFormat("void methodName(\n"
424                "    Object arg1, Object arg2) {}",
425                getStyleWithColumns(40));
426 }
427 
TEST_F(FormatTestJava,CppKeywords)428 TEST_F(FormatTestJava, CppKeywords) {
429   verifyFormat("public void union(Type a, Type b);");
430   verifyFormat("public void struct(Object o);");
431   verifyFormat("public void delete(Object o);");
432   verifyFormat("return operator && (aa);");
433 }
434 
TEST_F(FormatTestJava,NeverAlignAfterReturn)435 TEST_F(FormatTestJava, NeverAlignAfterReturn) {
436   verifyFormat("return aaaaaaaaaaaaaaaaaaa\n"
437                "    && bbbbbbbbbbbbbbbbbbb\n"
438                "    && ccccccccccccccccccc;",
439                getStyleWithColumns(40));
440   verifyFormat("return (result == null)\n"
441                "    ? aaaaaaaaaaaaaaaaa\n"
442                "    : bbbbbbbbbbbbbbbbb;",
443                getStyleWithColumns(40));
444   verifyFormat("return aaaaaaaaaaaaaaaaaaa()\n"
445                "    .bbbbbbbbbbbbbbbbbbb()\n"
446                "    .ccccccccccccccccccc();",
447                getStyleWithColumns(40));
448   verifyFormat("return aaaaaaaaaaaaaaaaaaa()\n"
449                "    .bbbbbbbbbbbbbbbbbbb(\n"
450                "        ccccccccccccccc)\n"
451                "    .ccccccccccccccccccc();",
452                getStyleWithColumns(40));
453 }
454 
TEST_F(FormatTestJava,FormatsInnerBlocks)455 TEST_F(FormatTestJava, FormatsInnerBlocks) {
456   verifyFormat("someObject.someFunction(new Runnable() {\n"
457                "  @Override\n"
458                "  public void run() {\n"
459                "    System.out.println(42);\n"
460                "  }\n"
461                "}, someOtherParameter);");
462   verifyFormat("someFunction(new Runnable() {\n"
463                "  public void run() {\n"
464                "    System.out.println(42);\n"
465                "  }\n"
466                "});");
467   verifyFormat("someObject.someFunction(\n"
468                "    new Runnable() {\n"
469                "      @Override\n"
470                "      public void run() {\n"
471                "        System.out.println(42);\n"
472                "      }\n"
473                "    },\n"
474                "    new Runnable() {\n"
475                "      @Override\n"
476                "      public void run() {\n"
477                "        System.out.println(43);\n"
478                "      }\n"
479                "    },\n"
480                "    someOtherParameter);");
481 }
482 
TEST_F(FormatTestJava,FormatsLambdas)483 TEST_F(FormatTestJava, FormatsLambdas) {
484   verifyFormat("(aaaaaaaaaa, bbbbbbbbbb) -> aaaaaaaaaa + bbbbbbbbbb;");
485   verifyFormat("(aaaaaaaaaa, bbbbbbbbbb)\n"
486                "    -> aaaaaaaaaa + bbbbbbbbbb;",
487                getStyleWithColumns(40));
488   verifyFormat("Runnable someLambda = () -> DoSomething();");
489   verifyFormat("Runnable someLambda = () -> {\n"
490                "  DoSomething();\n"
491                "}");
492 
493   verifyFormat("Runnable someLambda =\n"
494                "    (int aaaaa) -> DoSomething(aaaaa);",
495                getStyleWithColumns(40));
496 }
497 
TEST_F(FormatTestJava,BreaksStringLiterals)498 TEST_F(FormatTestJava, BreaksStringLiterals) {
499   // FIXME: String literal breaking is currently disabled for Java and JS, as it
500   // requires strings to be merged using "+" which we don't support.
501   EXPECT_EQ("\"some text other\";",
502             format("\"some text other\";", getStyleWithColumns(14)));
503 }
504 
TEST_F(FormatTestJava,AlignsBlockComments)505 TEST_F(FormatTestJava, AlignsBlockComments) {
506   EXPECT_EQ("/*\n"
507             " * Really multi-line\n"
508             " * comment.\n"
509             " */\n"
510             "void f() {}",
511             format("  /*\n"
512                    "   * Really multi-line\n"
513                    "   * comment.\n"
514                    "   */\n"
515                    "  void f() {}"));
516 }
517 
518 } // end namespace tooling
519 } // end namespace clang
520