1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "clang/Format/Format.h"
10
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "gtest/gtest.h"
17
18 #define DEBUG_TYPE "format-test"
19
20 using clang::tooling::ReplacementTest;
21 using clang::tooling::toReplacements;
22 using testing::ScopedTrace;
23
24 namespace clang {
25 namespace format {
26 namespace {
27
getGoogleStyle()28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29
30 class FormatTest : public ::testing::Test {
31 protected:
32 enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33
format(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle (),StatusCheck CheckComplete=SC_ExpectComplete)34 std::string format(llvm::StringRef Code,
35 const FormatStyle &Style = getLLVMStyle(),
36 StatusCheck CheckComplete = SC_ExpectComplete) {
37 LLVM_DEBUG(llvm::errs() << "---\n");
38 LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40 FormattingAttemptStatus Status;
41 tooling::Replacements Replaces =
42 reformat(Style, Code, Ranges, "<stdin>", &Status);
43 if (CheckComplete != SC_DoNotCheck) {
44 bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45 EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46 << Code << "\n\n";
47 }
48 ReplacementCount = Replaces.size();
49 auto Result = applyAllReplacements(Code, Replaces);
50 EXPECT_TRUE(static_cast<bool>(Result));
51 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52 return *Result;
53 }
54
getStyleWithColumns(FormatStyle Style,unsigned ColumnLimit)55 FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56 Style.ColumnLimit = ColumnLimit;
57 return Style;
58 }
59
getLLVMStyleWithColumns(unsigned ColumnLimit)60 FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61 return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62 }
63
getGoogleStyleWithColumns(unsigned ColumnLimit)64 FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65 return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66 }
67
_verifyFormat(const char * File,int Line,llvm::StringRef Expected,llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())68 void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69 llvm::StringRef Code,
70 const FormatStyle &Style = getLLVMStyle()) {
71 ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72 EXPECT_EQ(Expected.str(), format(Expected, Style))
73 << "Expected code is not stable";
74 EXPECT_EQ(Expected.str(), format(Code, Style));
75 if (Style.Language == FormatStyle::LK_Cpp) {
76 // Objective-C++ is a superset of C++, so everything checked for C++
77 // needs to be checked for Objective-C++ as well.
78 FormatStyle ObjCStyle = Style;
79 ObjCStyle.Language = FormatStyle::LK_ObjC;
80 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81 }
82 }
83
_verifyFormat(const char * File,int Line,llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())84 void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85 const FormatStyle &Style = getLLVMStyle()) {
86 _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87 }
88
_verifyIncompleteFormat(const char * File,int Line,llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())89 void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90 const FormatStyle &Style = getLLVMStyle()) {
91 ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92 EXPECT_EQ(Code.str(),
93 format(test::messUp(Code), Style, SC_ExpectIncomplete));
94 }
95
_verifyIndependentOfContext(const char * File,int Line,llvm::StringRef Text,const FormatStyle & Style=getLLVMStyle ())96 void _verifyIndependentOfContext(const char *File, int Line,
97 llvm::StringRef Text,
98 const FormatStyle &Style = getLLVMStyle()) {
99 _verifyFormat(File, Line, Text, Style);
100 _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101 Style);
102 }
103
104 /// \brief Verify that clang-format does not crash on the given input.
verifyNoCrash(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())105 void verifyNoCrash(llvm::StringRef Code,
106 const FormatStyle &Style = getLLVMStyle()) {
107 format(Code, Style, SC_DoNotCheck);
108 }
109
110 int ReplacementCount;
111 };
112
113 #define verifyIndependentOfContext(...) \
114 _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...) \
116 _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119
TEST_F(FormatTest,MessUp)120 TEST_F(FormatTest, MessUp) {
121 EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127
TEST_F(FormatTest,DefaultLLVMStyleIsCpp)128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131
TEST_F(FormatTest,LLVMStyleOverride)132 TEST_F(FormatTest, LLVMStyleOverride) {
133 EXPECT_EQ(FormatStyle::LK_Proto,
134 getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140
TEST_F(FormatTest,DoesNotChangeCorrectlyFormattedCode)141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142 EXPECT_EQ(";", format(";"));
143 }
144
TEST_F(FormatTest,FormatsGlobalStatementsAt0)145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146 EXPECT_EQ("int i;", format(" int i;"));
147 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;"));
148 EXPECT_EQ("int i;\nint j;", format(" int i; int j;"));
149 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;"));
150 }
151
TEST_F(FormatTest,FormatsUnwrappedLinesAtFirstFormat)152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153 EXPECT_EQ("int i;", format("int\ni;"));
154 }
155
TEST_F(FormatTest,FormatsNestedBlockStatements)156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}"));
158 }
159
TEST_F(FormatTest,FormatsNestedCall)160 TEST_F(FormatTest, FormatsNestedCall) {
161 verifyFormat("Method(f1, f2(f3));");
162 verifyFormat("Method(f1(f2, f3()));");
163 verifyFormat("Method(f1(f2, (f3())));");
164 }
165
TEST_F(FormatTest,NestedNameSpecifiers)166 TEST_F(FormatTest, NestedNameSpecifiers) {
167 verifyFormat("vector<::Type> v;");
168 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169 verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170 verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171 verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172 verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173 verifyFormat("bool a = 2 < ::SomeFunction();");
174 verifyFormat("ALWAYS_INLINE ::std::string getName();");
175 verifyFormat("some::string getName();");
176 }
177
TEST_F(FormatTest,OnlyGeneratesNecessaryReplacements)178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179 EXPECT_EQ("if (a) {\n"
180 " f();\n"
181 "}",
182 format("if(a){f();}"));
183 EXPECT_EQ(4, ReplacementCount);
184 EXPECT_EQ("if (a) {\n"
185 " f();\n"
186 "}",
187 format("if (a) {\n"
188 " f();\n"
189 "}"));
190 EXPECT_EQ(0, ReplacementCount);
191 EXPECT_EQ("/*\r\n"
192 "\r\n"
193 "*/\r\n",
194 format("/*\r\n"
195 "\r\n"
196 "*/\r\n"));
197 EXPECT_EQ(0, ReplacementCount);
198 }
199
TEST_F(FormatTest,RemovesEmptyLines)200 TEST_F(FormatTest, RemovesEmptyLines) {
201 EXPECT_EQ("class C {\n"
202 " int i;\n"
203 "};",
204 format("class C {\n"
205 " int i;\n"
206 "\n"
207 "};"));
208
209 // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210 EXPECT_EQ("namespace N {\n"
211 "\n"
212 "int i;\n"
213 "}",
214 format("namespace N {\n"
215 "\n"
216 "int i;\n"
217 "}",
218 getGoogleStyle()));
219 EXPECT_EQ("/* something */ namespace N {\n"
220 "\n"
221 "int i;\n"
222 "}",
223 format("/* something */ namespace N {\n"
224 "\n"
225 "int i;\n"
226 "}",
227 getGoogleStyle()));
228 EXPECT_EQ("inline namespace N {\n"
229 "\n"
230 "int i;\n"
231 "}",
232 format("inline namespace N {\n"
233 "\n"
234 "int i;\n"
235 "}",
236 getGoogleStyle()));
237 EXPECT_EQ("/* something */ inline namespace N {\n"
238 "\n"
239 "int i;\n"
240 "}",
241 format("/* something */ inline namespace N {\n"
242 "\n"
243 "int i;\n"
244 "}",
245 getGoogleStyle()));
246 EXPECT_EQ("export namespace N {\n"
247 "\n"
248 "int i;\n"
249 "}",
250 format("export namespace N {\n"
251 "\n"
252 "int i;\n"
253 "}",
254 getGoogleStyle()));
255 EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256 "\n"
257 "int i;\n"
258 "}",
259 format("extern /**/ \"C\" /**/ {\n"
260 "\n"
261 "int i;\n"
262 "}",
263 getGoogleStyle()));
264
265 auto CustomStyle = clang::format::getLLVMStyle();
266 CustomStyle.BreakBeforeBraces = clang::format::FormatStyle::BS_Custom;
267 CustomStyle.BraceWrapping.AfterNamespace = true;
268 CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
269 EXPECT_EQ("namespace N\n"
270 "{\n"
271 "\n"
272 "int i;\n"
273 "}",
274 format("namespace N\n"
275 "{\n"
276 "\n"
277 "\n"
278 "int i;\n"
279 "}",
280 CustomStyle));
281 EXPECT_EQ("/* something */ namespace N\n"
282 "{\n"
283 "\n"
284 "int i;\n"
285 "}",
286 format("/* something */ namespace N {\n"
287 "\n"
288 "\n"
289 "int i;\n"
290 "}",
291 CustomStyle));
292 EXPECT_EQ("inline namespace N\n"
293 "{\n"
294 "\n"
295 "int i;\n"
296 "}",
297 format("inline namespace N\n"
298 "{\n"
299 "\n"
300 "\n"
301 "int i;\n"
302 "}",
303 CustomStyle));
304 EXPECT_EQ("/* something */ inline namespace N\n"
305 "{\n"
306 "\n"
307 "int i;\n"
308 "}",
309 format("/* something */ inline namespace N\n"
310 "{\n"
311 "\n"
312 "int i;\n"
313 "}",
314 CustomStyle));
315 EXPECT_EQ("export namespace N\n"
316 "{\n"
317 "\n"
318 "int i;\n"
319 "}",
320 format("export namespace N\n"
321 "{\n"
322 "\n"
323 "int i;\n"
324 "}",
325 CustomStyle));
326 EXPECT_EQ("namespace a\n"
327 "{\n"
328 "namespace b\n"
329 "{\n"
330 "\n"
331 "class AA {};\n"
332 "\n"
333 "} // namespace b\n"
334 "} // namespace a\n",
335 format("namespace a\n"
336 "{\n"
337 "namespace b\n"
338 "{\n"
339 "\n"
340 "\n"
341 "class AA {};\n"
342 "\n"
343 "\n"
344 "}\n"
345 "}\n",
346 CustomStyle));
347 EXPECT_EQ("namespace A /* comment */\n"
348 "{\n"
349 "class B {}\n"
350 "} // namespace A",
351 format("namespace A /* comment */ { class B {} }", CustomStyle));
352 EXPECT_EQ("namespace A\n"
353 "{ /* comment */\n"
354 "class B {}\n"
355 "} // namespace A",
356 format("namespace A {/* comment */ class B {} }", CustomStyle));
357 EXPECT_EQ("namespace A\n"
358 "{ /* comment */\n"
359 "\n"
360 "class B {}\n"
361 "\n"
362 ""
363 "} // namespace A",
364 format("namespace A { /* comment */\n"
365 "\n"
366 "\n"
367 "class B {}\n"
368 "\n"
369 "\n"
370 "}",
371 CustomStyle));
372 EXPECT_EQ("namespace A /* comment */\n"
373 "{\n"
374 "\n"
375 "class B {}\n"
376 "\n"
377 "} // namespace A",
378 format("namespace A/* comment */ {\n"
379 "\n"
380 "\n"
381 "class B {}\n"
382 "\n"
383 "\n"
384 "}",
385 CustomStyle));
386
387 // ...but do keep inlining and removing empty lines for non-block extern "C"
388 // functions.
389 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
390 EXPECT_EQ("extern \"C\" int f() {\n"
391 " int i = 42;\n"
392 " return i;\n"
393 "}",
394 format("extern \"C\" int f() {\n"
395 "\n"
396 " int i = 42;\n"
397 " return i;\n"
398 "}",
399 getGoogleStyle()));
400
401 // Remove empty lines at the beginning and end of blocks.
402 EXPECT_EQ("void f() {\n"
403 "\n"
404 " if (a) {\n"
405 "\n"
406 " f();\n"
407 " }\n"
408 "}",
409 format("void f() {\n"
410 "\n"
411 " if (a) {\n"
412 "\n"
413 " f();\n"
414 "\n"
415 " }\n"
416 "\n"
417 "}",
418 getLLVMStyle()));
419 EXPECT_EQ("void f() {\n"
420 " if (a) {\n"
421 " f();\n"
422 " }\n"
423 "}",
424 format("void f() {\n"
425 "\n"
426 " if (a) {\n"
427 "\n"
428 " f();\n"
429 "\n"
430 " }\n"
431 "\n"
432 "}",
433 getGoogleStyle()));
434
435 // Don't remove empty lines in more complex control statements.
436 EXPECT_EQ("void f() {\n"
437 " if (a) {\n"
438 " f();\n"
439 "\n"
440 " } else if (b) {\n"
441 " f();\n"
442 " }\n"
443 "}",
444 format("void f() {\n"
445 " if (a) {\n"
446 " f();\n"
447 "\n"
448 " } else if (b) {\n"
449 " f();\n"
450 "\n"
451 " }\n"
452 "\n"
453 "}"));
454
455 // Don't remove empty lines before namespace endings.
456 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
457 LLVMWithNoNamespaceFix.FixNamespaceComments = false;
458 EXPECT_EQ("namespace {\n"
459 "int i;\n"
460 "\n"
461 "}",
462 format("namespace {\n"
463 "int i;\n"
464 "\n"
465 "}",
466 LLVMWithNoNamespaceFix));
467 EXPECT_EQ("namespace {\n"
468 "int i;\n"
469 "}",
470 format("namespace {\n"
471 "int i;\n"
472 "}",
473 LLVMWithNoNamespaceFix));
474 EXPECT_EQ("namespace {\n"
475 "int i;\n"
476 "\n"
477 "};",
478 format("namespace {\n"
479 "int i;\n"
480 "\n"
481 "};",
482 LLVMWithNoNamespaceFix));
483 EXPECT_EQ("namespace {\n"
484 "int i;\n"
485 "};",
486 format("namespace {\n"
487 "int i;\n"
488 "};",
489 LLVMWithNoNamespaceFix));
490 EXPECT_EQ("namespace {\n"
491 "int i;\n"
492 "\n"
493 "}",
494 format("namespace {\n"
495 "int i;\n"
496 "\n"
497 "}"));
498 EXPECT_EQ("namespace {\n"
499 "int i;\n"
500 "\n"
501 "} // namespace",
502 format("namespace {\n"
503 "int i;\n"
504 "\n"
505 "} // namespace"));
506
507 FormatStyle Style = getLLVMStyle();
508 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
509 Style.MaxEmptyLinesToKeep = 2;
510 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
511 Style.BraceWrapping.AfterClass = true;
512 Style.BraceWrapping.AfterFunction = true;
513 Style.KeepEmptyLinesAtTheStartOfBlocks = false;
514
515 EXPECT_EQ("class Foo\n"
516 "{\n"
517 " Foo() {}\n"
518 "\n"
519 " void funk() {}\n"
520 "};",
521 format("class Foo\n"
522 "{\n"
523 " Foo()\n"
524 " {\n"
525 " }\n"
526 "\n"
527 " void funk() {}\n"
528 "};",
529 Style));
530 }
531
TEST_F(FormatTest,RecognizesBinaryOperatorKeywords)532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
533 verifyFormat("x = (a) and (b);");
534 verifyFormat("x = (a) or (b);");
535 verifyFormat("x = (a) bitand (b);");
536 verifyFormat("x = (a) bitor (b);");
537 verifyFormat("x = (a) not_eq (b);");
538 verifyFormat("x = (a) and_eq (b);");
539 verifyFormat("x = (a) or_eq (b);");
540 verifyFormat("x = (a) xor (b);");
541 }
542
TEST_F(FormatTest,RecognizesUnaryOperatorKeywords)543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
544 verifyFormat("x = compl(a);");
545 verifyFormat("x = not(a);");
546 verifyFormat("x = bitand(a);");
547 // Unary operator must not be merged with the next identifier
548 verifyFormat("x = compl a;");
549 verifyFormat("x = not a;");
550 verifyFormat("x = bitand a;");
551 }
552
553 //===----------------------------------------------------------------------===//
554 // Tests for control statements.
555 //===----------------------------------------------------------------------===//
556
TEST_F(FormatTest,FormatIfWithoutCompoundStatement)557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
558 verifyFormat("if (true)\n f();\ng();");
559 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();");
560 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();");
561 verifyFormat("if constexpr (true)\n"
562 " f();\ng();");
563 verifyFormat("if CONSTEXPR (true)\n"
564 " f();\ng();");
565 verifyFormat("if constexpr (a)\n"
566 " if constexpr (b)\n"
567 " if constexpr (c)\n"
568 " g();\n"
569 "h();");
570 verifyFormat("if CONSTEXPR (a)\n"
571 " if CONSTEXPR (b)\n"
572 " if CONSTEXPR (c)\n"
573 " g();\n"
574 "h();");
575 verifyFormat("if constexpr (a)\n"
576 " if constexpr (b) {\n"
577 " f();\n"
578 " }\n"
579 "g();");
580 verifyFormat("if CONSTEXPR (a)\n"
581 " if CONSTEXPR (b) {\n"
582 " f();\n"
583 " }\n"
584 "g();");
585
586 verifyFormat("if (a)\n"
587 " g();");
588 verifyFormat("if (a) {\n"
589 " g()\n"
590 "};");
591 verifyFormat("if (a)\n"
592 " g();\n"
593 "else\n"
594 " g();");
595 verifyFormat("if (a) {\n"
596 " g();\n"
597 "} else\n"
598 " g();");
599 verifyFormat("if (a)\n"
600 " g();\n"
601 "else {\n"
602 " g();\n"
603 "}");
604 verifyFormat("if (a) {\n"
605 " g();\n"
606 "} else {\n"
607 " g();\n"
608 "}");
609 verifyFormat("if (a)\n"
610 " g();\n"
611 "else if (b)\n"
612 " g();\n"
613 "else\n"
614 " g();");
615 verifyFormat("if (a) {\n"
616 " g();\n"
617 "} else if (b)\n"
618 " g();\n"
619 "else\n"
620 " g();");
621 verifyFormat("if (a)\n"
622 " g();\n"
623 "else if (b) {\n"
624 " g();\n"
625 "} else\n"
626 " g();");
627 verifyFormat("if (a)\n"
628 " g();\n"
629 "else if (b)\n"
630 " g();\n"
631 "else {\n"
632 " g();\n"
633 "}");
634 verifyFormat("if (a)\n"
635 " g();\n"
636 "else if (b) {\n"
637 " g();\n"
638 "} else {\n"
639 " g();\n"
640 "}");
641 verifyFormat("if (a) {\n"
642 " g();\n"
643 "} else if (b) {\n"
644 " g();\n"
645 "} else {\n"
646 " g();\n"
647 "}");
648
649 FormatStyle AllowsMergedIf = getLLVMStyle();
650 AllowsMergedIf.IfMacros.push_back("MYIF");
651 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
652 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
653 FormatStyle::SIS_WithoutElse;
654 verifyFormat("if (a)\n"
655 " // comment\n"
656 " f();",
657 AllowsMergedIf);
658 verifyFormat("{\n"
659 " if (a)\n"
660 " label:\n"
661 " f();\n"
662 "}",
663 AllowsMergedIf);
664 verifyFormat("#define A \\\n"
665 " if (a) \\\n"
666 " label: \\\n"
667 " f()",
668 AllowsMergedIf);
669 verifyFormat("if (a)\n"
670 " ;",
671 AllowsMergedIf);
672 verifyFormat("if (a)\n"
673 " if (b) return;",
674 AllowsMergedIf);
675
676 verifyFormat("if (a) // Can't merge this\n"
677 " f();\n",
678 AllowsMergedIf);
679 verifyFormat("if (a) /* still don't merge */\n"
680 " f();",
681 AllowsMergedIf);
682 verifyFormat("if (a) { // Never merge this\n"
683 " f();\n"
684 "}",
685 AllowsMergedIf);
686 verifyFormat("if (a) { /* Never merge this */\n"
687 " f();\n"
688 "}",
689 AllowsMergedIf);
690 verifyFormat("MYIF (a)\n"
691 " // comment\n"
692 " f();",
693 AllowsMergedIf);
694 verifyFormat("{\n"
695 " MYIF (a)\n"
696 " label:\n"
697 " f();\n"
698 "}",
699 AllowsMergedIf);
700 verifyFormat("#define A \\\n"
701 " MYIF (a) \\\n"
702 " label: \\\n"
703 " f()",
704 AllowsMergedIf);
705 verifyFormat("MYIF (a)\n"
706 " ;",
707 AllowsMergedIf);
708 verifyFormat("MYIF (a)\n"
709 " MYIF (b) return;",
710 AllowsMergedIf);
711
712 verifyFormat("MYIF (a) // Can't merge this\n"
713 " f();\n",
714 AllowsMergedIf);
715 verifyFormat("MYIF (a) /* still don't merge */\n"
716 " f();",
717 AllowsMergedIf);
718 verifyFormat("MYIF (a) { // Never merge this\n"
719 " f();\n"
720 "}",
721 AllowsMergedIf);
722 verifyFormat("MYIF (a) { /* Never merge this */\n"
723 " f();\n"
724 "}",
725 AllowsMergedIf);
726
727 AllowsMergedIf.ColumnLimit = 14;
728 // Where line-lengths matter, a 2-letter synonym that maintains line length.
729 // Not IF to avoid any confusion that IF is somehow special.
730 AllowsMergedIf.IfMacros.push_back("FI");
731 verifyFormat("if (a) return;", AllowsMergedIf);
732 verifyFormat("if (aaaaaaaaa)\n"
733 " return;",
734 AllowsMergedIf);
735 verifyFormat("FI (a) return;", AllowsMergedIf);
736 verifyFormat("FI (aaaaaaaaa)\n"
737 " return;",
738 AllowsMergedIf);
739
740 AllowsMergedIf.ColumnLimit = 13;
741 verifyFormat("if (a)\n return;", AllowsMergedIf);
742 verifyFormat("FI (a)\n return;", AllowsMergedIf);
743
744 FormatStyle AllowsMergedIfElse = getLLVMStyle();
745 AllowsMergedIfElse.IfMacros.push_back("MYIF");
746 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
747 FormatStyle::SIS_AllIfsAndElse;
748 verifyFormat("if (a)\n"
749 " // comment\n"
750 " f();\n"
751 "else\n"
752 " // comment\n"
753 " f();",
754 AllowsMergedIfElse);
755 verifyFormat("{\n"
756 " if (a)\n"
757 " label:\n"
758 " f();\n"
759 " else\n"
760 " label:\n"
761 " f();\n"
762 "}",
763 AllowsMergedIfElse);
764 verifyFormat("if (a)\n"
765 " ;\n"
766 "else\n"
767 " ;",
768 AllowsMergedIfElse);
769 verifyFormat("if (a) {\n"
770 "} else {\n"
771 "}",
772 AllowsMergedIfElse);
773 verifyFormat("if (a) return;\n"
774 "else if (b) return;\n"
775 "else return;",
776 AllowsMergedIfElse);
777 verifyFormat("if (a) {\n"
778 "} else return;",
779 AllowsMergedIfElse);
780 verifyFormat("if (a) {\n"
781 "} else if (b) return;\n"
782 "else return;",
783 AllowsMergedIfElse);
784 verifyFormat("if (a) return;\n"
785 "else if (b) {\n"
786 "} else return;",
787 AllowsMergedIfElse);
788 verifyFormat("if (a)\n"
789 " if (b) return;\n"
790 " else return;",
791 AllowsMergedIfElse);
792 verifyFormat("if constexpr (a)\n"
793 " if constexpr (b) return;\n"
794 " else if constexpr (c) return;\n"
795 " else return;",
796 AllowsMergedIfElse);
797 verifyFormat("MYIF (a)\n"
798 " // comment\n"
799 " f();\n"
800 "else\n"
801 " // comment\n"
802 " f();",
803 AllowsMergedIfElse);
804 verifyFormat("{\n"
805 " MYIF (a)\n"
806 " label:\n"
807 " f();\n"
808 " else\n"
809 " label:\n"
810 " f();\n"
811 "}",
812 AllowsMergedIfElse);
813 verifyFormat("MYIF (a)\n"
814 " ;\n"
815 "else\n"
816 " ;",
817 AllowsMergedIfElse);
818 verifyFormat("MYIF (a) {\n"
819 "} else {\n"
820 "}",
821 AllowsMergedIfElse);
822 verifyFormat("MYIF (a) return;\n"
823 "else MYIF (b) return;\n"
824 "else return;",
825 AllowsMergedIfElse);
826 verifyFormat("MYIF (a) {\n"
827 "} else return;",
828 AllowsMergedIfElse);
829 verifyFormat("MYIF (a) {\n"
830 "} else MYIF (b) return;\n"
831 "else return;",
832 AllowsMergedIfElse);
833 verifyFormat("MYIF (a) return;\n"
834 "else MYIF (b) {\n"
835 "} else return;",
836 AllowsMergedIfElse);
837 verifyFormat("MYIF (a)\n"
838 " MYIF (b) return;\n"
839 " else return;",
840 AllowsMergedIfElse);
841 verifyFormat("MYIF constexpr (a)\n"
842 " MYIF constexpr (b) return;\n"
843 " else MYIF constexpr (c) return;\n"
844 " else return;",
845 AllowsMergedIfElse);
846 }
847
TEST_F(FormatTest,FormatIfWithoutCompoundStatementButElseWith)848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
849 FormatStyle AllowsMergedIf = getLLVMStyle();
850 AllowsMergedIf.IfMacros.push_back("MYIF");
851 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
852 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
853 FormatStyle::SIS_WithoutElse;
854 verifyFormat("if (a)\n"
855 " f();\n"
856 "else {\n"
857 " g();\n"
858 "}",
859 AllowsMergedIf);
860 verifyFormat("if (a)\n"
861 " f();\n"
862 "else\n"
863 " g();\n",
864 AllowsMergedIf);
865
866 verifyFormat("if (a) g();", AllowsMergedIf);
867 verifyFormat("if (a) {\n"
868 " g()\n"
869 "};",
870 AllowsMergedIf);
871 verifyFormat("if (a)\n"
872 " g();\n"
873 "else\n"
874 " g();",
875 AllowsMergedIf);
876 verifyFormat("if (a) {\n"
877 " g();\n"
878 "} else\n"
879 " g();",
880 AllowsMergedIf);
881 verifyFormat("if (a)\n"
882 " g();\n"
883 "else {\n"
884 " g();\n"
885 "}",
886 AllowsMergedIf);
887 verifyFormat("if (a) {\n"
888 " g();\n"
889 "} else {\n"
890 " g();\n"
891 "}",
892 AllowsMergedIf);
893 verifyFormat("if (a)\n"
894 " g();\n"
895 "else if (b)\n"
896 " g();\n"
897 "else\n"
898 " g();",
899 AllowsMergedIf);
900 verifyFormat("if (a) {\n"
901 " g();\n"
902 "} else if (b)\n"
903 " g();\n"
904 "else\n"
905 " g();",
906 AllowsMergedIf);
907 verifyFormat("if (a)\n"
908 " g();\n"
909 "else if (b) {\n"
910 " g();\n"
911 "} else\n"
912 " g();",
913 AllowsMergedIf);
914 verifyFormat("if (a)\n"
915 " g();\n"
916 "else if (b)\n"
917 " g();\n"
918 "else {\n"
919 " g();\n"
920 "}",
921 AllowsMergedIf);
922 verifyFormat("if (a)\n"
923 " g();\n"
924 "else if (b) {\n"
925 " g();\n"
926 "} else {\n"
927 " g();\n"
928 "}",
929 AllowsMergedIf);
930 verifyFormat("if (a) {\n"
931 " g();\n"
932 "} else if (b) {\n"
933 " g();\n"
934 "} else {\n"
935 " g();\n"
936 "}",
937 AllowsMergedIf);
938 verifyFormat("MYIF (a)\n"
939 " f();\n"
940 "else {\n"
941 " g();\n"
942 "}",
943 AllowsMergedIf);
944 verifyFormat("MYIF (a)\n"
945 " f();\n"
946 "else\n"
947 " g();\n",
948 AllowsMergedIf);
949
950 verifyFormat("MYIF (a) g();", AllowsMergedIf);
951 verifyFormat("MYIF (a) {\n"
952 " g()\n"
953 "};",
954 AllowsMergedIf);
955 verifyFormat("MYIF (a)\n"
956 " g();\n"
957 "else\n"
958 " g();",
959 AllowsMergedIf);
960 verifyFormat("MYIF (a) {\n"
961 " g();\n"
962 "} else\n"
963 " g();",
964 AllowsMergedIf);
965 verifyFormat("MYIF (a)\n"
966 " g();\n"
967 "else {\n"
968 " g();\n"
969 "}",
970 AllowsMergedIf);
971 verifyFormat("MYIF (a) {\n"
972 " g();\n"
973 "} else {\n"
974 " g();\n"
975 "}",
976 AllowsMergedIf);
977 verifyFormat("MYIF (a)\n"
978 " g();\n"
979 "else MYIF (b)\n"
980 " g();\n"
981 "else\n"
982 " g();",
983 AllowsMergedIf);
984 verifyFormat("MYIF (a)\n"
985 " g();\n"
986 "else if (b)\n"
987 " g();\n"
988 "else\n"
989 " g();",
990 AllowsMergedIf);
991 verifyFormat("MYIF (a) {\n"
992 " g();\n"
993 "} else MYIF (b)\n"
994 " g();\n"
995 "else\n"
996 " g();",
997 AllowsMergedIf);
998 verifyFormat("MYIF (a) {\n"
999 " g();\n"
1000 "} else if (b)\n"
1001 " g();\n"
1002 "else\n"
1003 " g();",
1004 AllowsMergedIf);
1005 verifyFormat("MYIF (a)\n"
1006 " g();\n"
1007 "else MYIF (b) {\n"
1008 " g();\n"
1009 "} else\n"
1010 " g();",
1011 AllowsMergedIf);
1012 verifyFormat("MYIF (a)\n"
1013 " g();\n"
1014 "else if (b) {\n"
1015 " g();\n"
1016 "} else\n"
1017 " g();",
1018 AllowsMergedIf);
1019 verifyFormat("MYIF (a)\n"
1020 " g();\n"
1021 "else MYIF (b)\n"
1022 " g();\n"
1023 "else {\n"
1024 " g();\n"
1025 "}",
1026 AllowsMergedIf);
1027 verifyFormat("MYIF (a)\n"
1028 " g();\n"
1029 "else if (b)\n"
1030 " g();\n"
1031 "else {\n"
1032 " g();\n"
1033 "}",
1034 AllowsMergedIf);
1035 verifyFormat("MYIF (a)\n"
1036 " g();\n"
1037 "else MYIF (b) {\n"
1038 " g();\n"
1039 "} else {\n"
1040 " g();\n"
1041 "}",
1042 AllowsMergedIf);
1043 verifyFormat("MYIF (a)\n"
1044 " g();\n"
1045 "else if (b) {\n"
1046 " g();\n"
1047 "} else {\n"
1048 " g();\n"
1049 "}",
1050 AllowsMergedIf);
1051 verifyFormat("MYIF (a) {\n"
1052 " g();\n"
1053 "} else MYIF (b) {\n"
1054 " g();\n"
1055 "} else {\n"
1056 " g();\n"
1057 "}",
1058 AllowsMergedIf);
1059 verifyFormat("MYIF (a) {\n"
1060 " g();\n"
1061 "} else if (b) {\n"
1062 " g();\n"
1063 "} else {\n"
1064 " g();\n"
1065 "}",
1066 AllowsMergedIf);
1067
1068 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1069 FormatStyle::SIS_OnlyFirstIf;
1070
1071 verifyFormat("if (a) f();\n"
1072 "else {\n"
1073 " g();\n"
1074 "}",
1075 AllowsMergedIf);
1076 verifyFormat("if (a) f();\n"
1077 "else {\n"
1078 " if (a) f();\n"
1079 " else {\n"
1080 " g();\n"
1081 " }\n"
1082 " g();\n"
1083 "}",
1084 AllowsMergedIf);
1085
1086 verifyFormat("if (a) g();", AllowsMergedIf);
1087 verifyFormat("if (a) {\n"
1088 " g()\n"
1089 "};",
1090 AllowsMergedIf);
1091 verifyFormat("if (a) g();\n"
1092 "else\n"
1093 " g();",
1094 AllowsMergedIf);
1095 verifyFormat("if (a) {\n"
1096 " g();\n"
1097 "} else\n"
1098 " g();",
1099 AllowsMergedIf);
1100 verifyFormat("if (a) g();\n"
1101 "else {\n"
1102 " g();\n"
1103 "}",
1104 AllowsMergedIf);
1105 verifyFormat("if (a) {\n"
1106 " g();\n"
1107 "} else {\n"
1108 " g();\n"
1109 "}",
1110 AllowsMergedIf);
1111 verifyFormat("if (a) g();\n"
1112 "else if (b)\n"
1113 " g();\n"
1114 "else\n"
1115 " g();",
1116 AllowsMergedIf);
1117 verifyFormat("if (a) {\n"
1118 " g();\n"
1119 "} else if (b)\n"
1120 " g();\n"
1121 "else\n"
1122 " g();",
1123 AllowsMergedIf);
1124 verifyFormat("if (a) g();\n"
1125 "else if (b) {\n"
1126 " g();\n"
1127 "} else\n"
1128 " g();",
1129 AllowsMergedIf);
1130 verifyFormat("if (a) g();\n"
1131 "else if (b)\n"
1132 " g();\n"
1133 "else {\n"
1134 " g();\n"
1135 "}",
1136 AllowsMergedIf);
1137 verifyFormat("if (a) g();\n"
1138 "else if (b) {\n"
1139 " g();\n"
1140 "} else {\n"
1141 " g();\n"
1142 "}",
1143 AllowsMergedIf);
1144 verifyFormat("if (a) {\n"
1145 " g();\n"
1146 "} else if (b) {\n"
1147 " g();\n"
1148 "} else {\n"
1149 " g();\n"
1150 "}",
1151 AllowsMergedIf);
1152 verifyFormat("MYIF (a) f();\n"
1153 "else {\n"
1154 " g();\n"
1155 "}",
1156 AllowsMergedIf);
1157 verifyFormat("MYIF (a) f();\n"
1158 "else {\n"
1159 " if (a) f();\n"
1160 " else {\n"
1161 " g();\n"
1162 " }\n"
1163 " g();\n"
1164 "}",
1165 AllowsMergedIf);
1166
1167 verifyFormat("MYIF (a) g();", AllowsMergedIf);
1168 verifyFormat("MYIF (a) {\n"
1169 " g()\n"
1170 "};",
1171 AllowsMergedIf);
1172 verifyFormat("MYIF (a) g();\n"
1173 "else\n"
1174 " g();",
1175 AllowsMergedIf);
1176 verifyFormat("MYIF (a) {\n"
1177 " g();\n"
1178 "} else\n"
1179 " g();",
1180 AllowsMergedIf);
1181 verifyFormat("MYIF (a) g();\n"
1182 "else {\n"
1183 " g();\n"
1184 "}",
1185 AllowsMergedIf);
1186 verifyFormat("MYIF (a) {\n"
1187 " g();\n"
1188 "} else {\n"
1189 " g();\n"
1190 "}",
1191 AllowsMergedIf);
1192 verifyFormat("MYIF (a) g();\n"
1193 "else MYIF (b)\n"
1194 " g();\n"
1195 "else\n"
1196 " g();",
1197 AllowsMergedIf);
1198 verifyFormat("MYIF (a) g();\n"
1199 "else if (b)\n"
1200 " g();\n"
1201 "else\n"
1202 " g();",
1203 AllowsMergedIf);
1204 verifyFormat("MYIF (a) {\n"
1205 " g();\n"
1206 "} else MYIF (b)\n"
1207 " g();\n"
1208 "else\n"
1209 " g();",
1210 AllowsMergedIf);
1211 verifyFormat("MYIF (a) {\n"
1212 " g();\n"
1213 "} else if (b)\n"
1214 " g();\n"
1215 "else\n"
1216 " g();",
1217 AllowsMergedIf);
1218 verifyFormat("MYIF (a) g();\n"
1219 "else MYIF (b) {\n"
1220 " g();\n"
1221 "} else\n"
1222 " g();",
1223 AllowsMergedIf);
1224 verifyFormat("MYIF (a) g();\n"
1225 "else if (b) {\n"
1226 " g();\n"
1227 "} else\n"
1228 " g();",
1229 AllowsMergedIf);
1230 verifyFormat("MYIF (a) g();\n"
1231 "else MYIF (b)\n"
1232 " g();\n"
1233 "else {\n"
1234 " g();\n"
1235 "}",
1236 AllowsMergedIf);
1237 verifyFormat("MYIF (a) g();\n"
1238 "else if (b)\n"
1239 " g();\n"
1240 "else {\n"
1241 " g();\n"
1242 "}",
1243 AllowsMergedIf);
1244 verifyFormat("MYIF (a) g();\n"
1245 "else MYIF (b) {\n"
1246 " g();\n"
1247 "} else {\n"
1248 " g();\n"
1249 "}",
1250 AllowsMergedIf);
1251 verifyFormat("MYIF (a) g();\n"
1252 "else if (b) {\n"
1253 " g();\n"
1254 "} else {\n"
1255 " g();\n"
1256 "}",
1257 AllowsMergedIf);
1258 verifyFormat("MYIF (a) {\n"
1259 " g();\n"
1260 "} else MYIF (b) {\n"
1261 " g();\n"
1262 "} else {\n"
1263 " g();\n"
1264 "}",
1265 AllowsMergedIf);
1266 verifyFormat("MYIF (a) {\n"
1267 " g();\n"
1268 "} else if (b) {\n"
1269 " g();\n"
1270 "} else {\n"
1271 " g();\n"
1272 "}",
1273 AllowsMergedIf);
1274
1275 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1276 FormatStyle::SIS_AllIfsAndElse;
1277
1278 verifyFormat("if (a) f();\n"
1279 "else {\n"
1280 " g();\n"
1281 "}",
1282 AllowsMergedIf);
1283 verifyFormat("if (a) f();\n"
1284 "else {\n"
1285 " if (a) f();\n"
1286 " else {\n"
1287 " g();\n"
1288 " }\n"
1289 " g();\n"
1290 "}",
1291 AllowsMergedIf);
1292
1293 verifyFormat("if (a) g();", AllowsMergedIf);
1294 verifyFormat("if (a) {\n"
1295 " g()\n"
1296 "};",
1297 AllowsMergedIf);
1298 verifyFormat("if (a) g();\n"
1299 "else g();",
1300 AllowsMergedIf);
1301 verifyFormat("if (a) {\n"
1302 " g();\n"
1303 "} else g();",
1304 AllowsMergedIf);
1305 verifyFormat("if (a) g();\n"
1306 "else {\n"
1307 " g();\n"
1308 "}",
1309 AllowsMergedIf);
1310 verifyFormat("if (a) {\n"
1311 " g();\n"
1312 "} else {\n"
1313 " g();\n"
1314 "}",
1315 AllowsMergedIf);
1316 verifyFormat("if (a) g();\n"
1317 "else if (b) g();\n"
1318 "else g();",
1319 AllowsMergedIf);
1320 verifyFormat("if (a) {\n"
1321 " g();\n"
1322 "} else if (b) g();\n"
1323 "else g();",
1324 AllowsMergedIf);
1325 verifyFormat("if (a) g();\n"
1326 "else if (b) {\n"
1327 " g();\n"
1328 "} else g();",
1329 AllowsMergedIf);
1330 verifyFormat("if (a) g();\n"
1331 "else if (b) g();\n"
1332 "else {\n"
1333 " g();\n"
1334 "}",
1335 AllowsMergedIf);
1336 verifyFormat("if (a) g();\n"
1337 "else if (b) {\n"
1338 " g();\n"
1339 "} else {\n"
1340 " g();\n"
1341 "}",
1342 AllowsMergedIf);
1343 verifyFormat("if (a) {\n"
1344 " g();\n"
1345 "} else if (b) {\n"
1346 " g();\n"
1347 "} else {\n"
1348 " g();\n"
1349 "}",
1350 AllowsMergedIf);
1351 verifyFormat("MYIF (a) f();\n"
1352 "else {\n"
1353 " g();\n"
1354 "}",
1355 AllowsMergedIf);
1356 verifyFormat("MYIF (a) f();\n"
1357 "else {\n"
1358 " if (a) f();\n"
1359 " else {\n"
1360 " g();\n"
1361 " }\n"
1362 " g();\n"
1363 "}",
1364 AllowsMergedIf);
1365
1366 verifyFormat("MYIF (a) g();", AllowsMergedIf);
1367 verifyFormat("MYIF (a) {\n"
1368 " g()\n"
1369 "};",
1370 AllowsMergedIf);
1371 verifyFormat("MYIF (a) g();\n"
1372 "else g();",
1373 AllowsMergedIf);
1374 verifyFormat("MYIF (a) {\n"
1375 " g();\n"
1376 "} else g();",
1377 AllowsMergedIf);
1378 verifyFormat("MYIF (a) g();\n"
1379 "else {\n"
1380 " g();\n"
1381 "}",
1382 AllowsMergedIf);
1383 verifyFormat("MYIF (a) {\n"
1384 " g();\n"
1385 "} else {\n"
1386 " g();\n"
1387 "}",
1388 AllowsMergedIf);
1389 verifyFormat("MYIF (a) g();\n"
1390 "else MYIF (b) g();\n"
1391 "else g();",
1392 AllowsMergedIf);
1393 verifyFormat("MYIF (a) g();\n"
1394 "else if (b) g();\n"
1395 "else g();",
1396 AllowsMergedIf);
1397 verifyFormat("MYIF (a) {\n"
1398 " g();\n"
1399 "} else MYIF (b) g();\n"
1400 "else g();",
1401 AllowsMergedIf);
1402 verifyFormat("MYIF (a) {\n"
1403 " g();\n"
1404 "} else if (b) g();\n"
1405 "else g();",
1406 AllowsMergedIf);
1407 verifyFormat("MYIF (a) g();\n"
1408 "else MYIF (b) {\n"
1409 " g();\n"
1410 "} else g();",
1411 AllowsMergedIf);
1412 verifyFormat("MYIF (a) g();\n"
1413 "else if (b) {\n"
1414 " g();\n"
1415 "} else g();",
1416 AllowsMergedIf);
1417 verifyFormat("MYIF (a) g();\n"
1418 "else MYIF (b) g();\n"
1419 "else {\n"
1420 " g();\n"
1421 "}",
1422 AllowsMergedIf);
1423 verifyFormat("MYIF (a) g();\n"
1424 "else if (b) g();\n"
1425 "else {\n"
1426 " g();\n"
1427 "}",
1428 AllowsMergedIf);
1429 verifyFormat("MYIF (a) g();\n"
1430 "else MYIF (b) {\n"
1431 " g();\n"
1432 "} else {\n"
1433 " g();\n"
1434 "}",
1435 AllowsMergedIf);
1436 verifyFormat("MYIF (a) g();\n"
1437 "else if (b) {\n"
1438 " g();\n"
1439 "} else {\n"
1440 " g();\n"
1441 "}",
1442 AllowsMergedIf);
1443 verifyFormat("MYIF (a) {\n"
1444 " g();\n"
1445 "} else MYIF (b) {\n"
1446 " g();\n"
1447 "} else {\n"
1448 " g();\n"
1449 "}",
1450 AllowsMergedIf);
1451 verifyFormat("MYIF (a) {\n"
1452 " g();\n"
1453 "} else if (b) {\n"
1454 " g();\n"
1455 "} else {\n"
1456 " g();\n"
1457 "}",
1458 AllowsMergedIf);
1459 }
1460
TEST_F(FormatTest,FormatLoopsWithoutCompoundStatement)1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1462 FormatStyle AllowsMergedLoops = getLLVMStyle();
1463 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1464 verifyFormat("while (true) continue;", AllowsMergedLoops);
1465 verifyFormat("for (;;) continue;", AllowsMergedLoops);
1466 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1467 verifyFormat("while (true)\n"
1468 " ;",
1469 AllowsMergedLoops);
1470 verifyFormat("for (;;)\n"
1471 " ;",
1472 AllowsMergedLoops);
1473 verifyFormat("for (;;)\n"
1474 " for (;;) continue;",
1475 AllowsMergedLoops);
1476 verifyFormat("for (;;) // Can't merge this\n"
1477 " continue;",
1478 AllowsMergedLoops);
1479 verifyFormat("for (;;) /* still don't merge */\n"
1480 " continue;",
1481 AllowsMergedLoops);
1482 verifyFormat("do a++;\n"
1483 "while (true);",
1484 AllowsMergedLoops);
1485 verifyFormat("do /* Don't merge */\n"
1486 " a++;\n"
1487 "while (true);",
1488 AllowsMergedLoops);
1489 verifyFormat("do // Don't merge\n"
1490 " a++;\n"
1491 "while (true);",
1492 AllowsMergedLoops);
1493 verifyFormat("do\n"
1494 " // Don't merge\n"
1495 " a++;\n"
1496 "while (true);",
1497 AllowsMergedLoops);
1498 // Without braces labels are interpreted differently.
1499 verifyFormat("{\n"
1500 " do\n"
1501 " label:\n"
1502 " a++;\n"
1503 " while (true);\n"
1504 "}",
1505 AllowsMergedLoops);
1506 }
1507
TEST_F(FormatTest,FormatShortBracedStatements)1508 TEST_F(FormatTest, FormatShortBracedStatements) {
1509 FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1510 AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1511 // Where line-lengths matter, a 2-letter synonym that maintains line length.
1512 // Not IF to avoid any confusion that IF is somehow special.
1513 AllowSimpleBracedStatements.IfMacros.push_back("FI");
1514 AllowSimpleBracedStatements.ColumnLimit = 40;
1515 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1516 FormatStyle::SBS_Always;
1517
1518 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1519 FormatStyle::SIS_WithoutElse;
1520 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1521
1522 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1523 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1524 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1525
1526 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1527 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1528 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1529 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1530 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1531 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1532 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1533 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1534 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1535 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1536 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1537 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1538 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1539 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1540 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1541 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1542 verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1543 AllowSimpleBracedStatements);
1544 verifyFormat("if (true) {\n"
1545 " ffffffffffffffffffffffff();\n"
1546 "}",
1547 AllowSimpleBracedStatements);
1548 verifyFormat("if (true) {\n"
1549 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1550 "}",
1551 AllowSimpleBracedStatements);
1552 verifyFormat("if (true) { //\n"
1553 " f();\n"
1554 "}",
1555 AllowSimpleBracedStatements);
1556 verifyFormat("if (true) {\n"
1557 " f();\n"
1558 " f();\n"
1559 "}",
1560 AllowSimpleBracedStatements);
1561 verifyFormat("if (true) {\n"
1562 " f();\n"
1563 "} else {\n"
1564 " f();\n"
1565 "}",
1566 AllowSimpleBracedStatements);
1567 verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1568 AllowSimpleBracedStatements);
1569 verifyFormat("MYIF (true) {\n"
1570 " ffffffffffffffffffffffff();\n"
1571 "}",
1572 AllowSimpleBracedStatements);
1573 verifyFormat("MYIF (true) {\n"
1574 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1575 "}",
1576 AllowSimpleBracedStatements);
1577 verifyFormat("MYIF (true) { //\n"
1578 " f();\n"
1579 "}",
1580 AllowSimpleBracedStatements);
1581 verifyFormat("MYIF (true) {\n"
1582 " f();\n"
1583 " f();\n"
1584 "}",
1585 AllowSimpleBracedStatements);
1586 verifyFormat("MYIF (true) {\n"
1587 " f();\n"
1588 "} else {\n"
1589 " f();\n"
1590 "}",
1591 AllowSimpleBracedStatements);
1592
1593 verifyFormat("struct A2 {\n"
1594 " int X;\n"
1595 "};",
1596 AllowSimpleBracedStatements);
1597 verifyFormat("typedef struct A2 {\n"
1598 " int X;\n"
1599 "} A2_t;",
1600 AllowSimpleBracedStatements);
1601 verifyFormat("template <int> struct A2 {\n"
1602 " struct B {};\n"
1603 "};",
1604 AllowSimpleBracedStatements);
1605
1606 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1607 FormatStyle::SIS_Never;
1608 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1609 verifyFormat("if (true) {\n"
1610 " f();\n"
1611 "}",
1612 AllowSimpleBracedStatements);
1613 verifyFormat("if (true) {\n"
1614 " f();\n"
1615 "} else {\n"
1616 " f();\n"
1617 "}",
1618 AllowSimpleBracedStatements);
1619 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1620 verifyFormat("MYIF (true) {\n"
1621 " f();\n"
1622 "}",
1623 AllowSimpleBracedStatements);
1624 verifyFormat("MYIF (true) {\n"
1625 " f();\n"
1626 "} else {\n"
1627 " f();\n"
1628 "}",
1629 AllowSimpleBracedStatements);
1630
1631 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1632 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1633 verifyFormat("while (true) {\n"
1634 " f();\n"
1635 "}",
1636 AllowSimpleBracedStatements);
1637 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1638 verifyFormat("for (;;) {\n"
1639 " f();\n"
1640 "}",
1641 AllowSimpleBracedStatements);
1642
1643 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1644 FormatStyle::SIS_WithoutElse;
1645 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1646 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1647 FormatStyle::BWACS_Always;
1648
1649 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1650 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1651 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1652 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1653 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1654 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1655 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1656 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1657 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1658 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1659 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1660 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1661 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1662 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1663 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1664 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1665 verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1666 AllowSimpleBracedStatements);
1667 verifyFormat("if (true)\n"
1668 "{\n"
1669 " ffffffffffffffffffffffff();\n"
1670 "}",
1671 AllowSimpleBracedStatements);
1672 verifyFormat("if (true)\n"
1673 "{\n"
1674 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1675 "}",
1676 AllowSimpleBracedStatements);
1677 verifyFormat("if (true)\n"
1678 "{ //\n"
1679 " f();\n"
1680 "}",
1681 AllowSimpleBracedStatements);
1682 verifyFormat("if (true)\n"
1683 "{\n"
1684 " f();\n"
1685 " f();\n"
1686 "}",
1687 AllowSimpleBracedStatements);
1688 verifyFormat("if (true)\n"
1689 "{\n"
1690 " f();\n"
1691 "} else\n"
1692 "{\n"
1693 " f();\n"
1694 "}",
1695 AllowSimpleBracedStatements);
1696 verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1697 AllowSimpleBracedStatements);
1698 verifyFormat("MYIF (true)\n"
1699 "{\n"
1700 " ffffffffffffffffffffffff();\n"
1701 "}",
1702 AllowSimpleBracedStatements);
1703 verifyFormat("MYIF (true)\n"
1704 "{\n"
1705 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1706 "}",
1707 AllowSimpleBracedStatements);
1708 verifyFormat("MYIF (true)\n"
1709 "{ //\n"
1710 " f();\n"
1711 "}",
1712 AllowSimpleBracedStatements);
1713 verifyFormat("MYIF (true)\n"
1714 "{\n"
1715 " f();\n"
1716 " f();\n"
1717 "}",
1718 AllowSimpleBracedStatements);
1719 verifyFormat("MYIF (true)\n"
1720 "{\n"
1721 " f();\n"
1722 "} else\n"
1723 "{\n"
1724 " f();\n"
1725 "}",
1726 AllowSimpleBracedStatements);
1727
1728 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1729 FormatStyle::SIS_Never;
1730 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1731 verifyFormat("if (true)\n"
1732 "{\n"
1733 " f();\n"
1734 "}",
1735 AllowSimpleBracedStatements);
1736 verifyFormat("if (true)\n"
1737 "{\n"
1738 " f();\n"
1739 "} else\n"
1740 "{\n"
1741 " f();\n"
1742 "}",
1743 AllowSimpleBracedStatements);
1744 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1745 verifyFormat("MYIF (true)\n"
1746 "{\n"
1747 " f();\n"
1748 "}",
1749 AllowSimpleBracedStatements);
1750 verifyFormat("MYIF (true)\n"
1751 "{\n"
1752 " f();\n"
1753 "} else\n"
1754 "{\n"
1755 " f();\n"
1756 "}",
1757 AllowSimpleBracedStatements);
1758
1759 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1760 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1761 verifyFormat("while (true)\n"
1762 "{\n"
1763 " f();\n"
1764 "}",
1765 AllowSimpleBracedStatements);
1766 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1767 verifyFormat("for (;;)\n"
1768 "{\n"
1769 " f();\n"
1770 "}",
1771 AllowSimpleBracedStatements);
1772 }
1773
TEST_F(FormatTest,ShortBlocksInMacrosDontMergeWithCodeAfterMacro)1774 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1775 FormatStyle Style = getLLVMStyleWithColumns(60);
1776 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1777 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1778 Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1779 EXPECT_EQ("#define A \\\n"
1780 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
1781 " { \\\n"
1782 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1783 " }\n"
1784 "X;",
1785 format("#define A \\\n"
1786 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1787 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1788 " }\n"
1789 "X;",
1790 Style));
1791 }
1792
TEST_F(FormatTest,ParseIfElse)1793 TEST_F(FormatTest, ParseIfElse) {
1794 verifyFormat("if (true)\n"
1795 " if (true)\n"
1796 " if (true)\n"
1797 " f();\n"
1798 " else\n"
1799 " g();\n"
1800 " else\n"
1801 " h();\n"
1802 "else\n"
1803 " i();");
1804 verifyFormat("if (true)\n"
1805 " if (true)\n"
1806 " if (true) {\n"
1807 " if (true)\n"
1808 " f();\n"
1809 " } else {\n"
1810 " g();\n"
1811 " }\n"
1812 " else\n"
1813 " h();\n"
1814 "else {\n"
1815 " i();\n"
1816 "}");
1817 verifyFormat("if (true)\n"
1818 " if constexpr (true)\n"
1819 " if (true) {\n"
1820 " if constexpr (true)\n"
1821 " f();\n"
1822 " } else {\n"
1823 " g();\n"
1824 " }\n"
1825 " else\n"
1826 " h();\n"
1827 "else {\n"
1828 " i();\n"
1829 "}");
1830 verifyFormat("if (true)\n"
1831 " if CONSTEXPR (true)\n"
1832 " if (true) {\n"
1833 " if CONSTEXPR (true)\n"
1834 " f();\n"
1835 " } else {\n"
1836 " g();\n"
1837 " }\n"
1838 " else\n"
1839 " h();\n"
1840 "else {\n"
1841 " i();\n"
1842 "}");
1843 verifyFormat("void f() {\n"
1844 " if (a) {\n"
1845 " } else {\n"
1846 " }\n"
1847 "}");
1848 }
1849
TEST_F(FormatTest,ElseIf)1850 TEST_F(FormatTest, ElseIf) {
1851 verifyFormat("if (a) {\n} else if (b) {\n}");
1852 verifyFormat("if (a)\n"
1853 " f();\n"
1854 "else if (b)\n"
1855 " g();\n"
1856 "else\n"
1857 " h();");
1858 verifyFormat("if (a)\n"
1859 " f();\n"
1860 "else // comment\n"
1861 " if (b) {\n"
1862 " g();\n"
1863 " h();\n"
1864 " }");
1865 verifyFormat("if constexpr (a)\n"
1866 " f();\n"
1867 "else if constexpr (b)\n"
1868 " g();\n"
1869 "else\n"
1870 " h();");
1871 verifyFormat("if CONSTEXPR (a)\n"
1872 " f();\n"
1873 "else if CONSTEXPR (b)\n"
1874 " g();\n"
1875 "else\n"
1876 " h();");
1877 verifyFormat("if (a) {\n"
1878 " f();\n"
1879 "}\n"
1880 "// or else ..\n"
1881 "else {\n"
1882 " g()\n"
1883 "}");
1884
1885 verifyFormat("if (a) {\n"
1886 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1887 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1888 "}");
1889 verifyFormat("if (a) {\n"
1890 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1891 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1892 "}");
1893 verifyFormat("if (a) {\n"
1894 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1895 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1896 "}");
1897 verifyFormat("if (a) {\n"
1898 "} else if (\n"
1899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1900 "}",
1901 getLLVMStyleWithColumns(62));
1902 verifyFormat("if (a) {\n"
1903 "} else if constexpr (\n"
1904 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1905 "}",
1906 getLLVMStyleWithColumns(62));
1907 verifyFormat("if (a) {\n"
1908 "} else if CONSTEXPR (\n"
1909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1910 "}",
1911 getLLVMStyleWithColumns(62));
1912 }
1913
TEST_F(FormatTest,SeparatePointerReferenceAlignment)1914 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
1915 FormatStyle Style = getLLVMStyle();
1916 // Check first the default LLVM style
1917 // Style.PointerAlignment = FormatStyle::PAS_Right;
1918 // Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1919 verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
1920 verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
1921 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
1922 verifyFormat("int *f1(int &a) const &;", Style);
1923 verifyFormat("int *f1(int &a) const & = 0;", Style);
1924 verifyFormat("int *a = f1();", Style);
1925 verifyFormat("int &b = f2();", Style);
1926 verifyFormat("int &&c = f3();", Style);
1927
1928 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1929 verifyFormat("Const unsigned int *c;\n"
1930 "const unsigned int *d;\n"
1931 "Const unsigned int &e;\n"
1932 "const unsigned int &f;\n"
1933 "const unsigned &&g;\n"
1934 "Const unsigned h;",
1935 Style);
1936
1937 Style.PointerAlignment = FormatStyle::PAS_Left;
1938 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1939 verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
1940 verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
1941 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
1942 verifyFormat("int* f1(int& a) const& = 0;", Style);
1943 verifyFormat("int* a = f1();", Style);
1944 verifyFormat("int& b = f2();", Style);
1945 verifyFormat("int&& c = f3();", Style);
1946
1947 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1948 verifyFormat("Const unsigned int* c;\n"
1949 "const unsigned int* d;\n"
1950 "Const unsigned int& e;\n"
1951 "const unsigned int& f;\n"
1952 "const unsigned&& g;\n"
1953 "Const unsigned h;",
1954 Style);
1955
1956 Style.PointerAlignment = FormatStyle::PAS_Right;
1957 Style.ReferenceAlignment = FormatStyle::RAS_Left;
1958 verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
1959 verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
1960 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
1961 verifyFormat("int *a = f1();", Style);
1962 verifyFormat("int& b = f2();", Style);
1963 verifyFormat("int&& c = f3();", Style);
1964
1965 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1966 verifyFormat("Const unsigned int *c;\n"
1967 "const unsigned int *d;\n"
1968 "Const unsigned int& e;\n"
1969 "const unsigned int& f;\n"
1970 "const unsigned g;\n"
1971 "Const unsigned h;",
1972 Style);
1973
1974 Style.PointerAlignment = FormatStyle::PAS_Left;
1975 Style.ReferenceAlignment = FormatStyle::RAS_Middle;
1976 verifyFormat("int* f1(int* a, int & b, int && c);", Style);
1977 verifyFormat("int & f2(int && c, int* a, int & b);", Style);
1978 verifyFormat("int && f3(int & b, int && c, int* a);", Style);
1979 verifyFormat("int* a = f1();", Style);
1980 verifyFormat("int & b = f2();", Style);
1981 verifyFormat("int && c = f3();", Style);
1982
1983 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1984 verifyFormat("Const unsigned int* c;\n"
1985 "const unsigned int* d;\n"
1986 "Const unsigned int & e;\n"
1987 "const unsigned int & f;\n"
1988 "const unsigned && g;\n"
1989 "Const unsigned h;",
1990 Style);
1991
1992 Style.PointerAlignment = FormatStyle::PAS_Middle;
1993 Style.ReferenceAlignment = FormatStyle::RAS_Right;
1994 verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
1995 verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
1996 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
1997 verifyFormat("int * a = f1();", Style);
1998 verifyFormat("int &b = f2();", Style);
1999 verifyFormat("int &&c = f3();", Style);
2000
2001 // FIXME: we don't handle this yet, so output may be arbitrary until it's
2002 // specifically handled
2003 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2004 }
2005
TEST_F(FormatTest,FormatsForLoop)2006 TEST_F(FormatTest, FormatsForLoop) {
2007 verifyFormat(
2008 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2009 " ++VeryVeryLongLoopVariable)\n"
2010 " ;");
2011 verifyFormat("for (;;)\n"
2012 " f();");
2013 verifyFormat("for (;;) {\n}");
2014 verifyFormat("for (;;) {\n"
2015 " f();\n"
2016 "}");
2017 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2018
2019 verifyFormat(
2020 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2021 " E = UnwrappedLines.end();\n"
2022 " I != E; ++I) {\n}");
2023
2024 verifyFormat(
2025 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2026 " ++IIIII) {\n}");
2027 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2028 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2029 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2030 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2031 " I = FD->getDeclsInPrototypeScope().begin(),\n"
2032 " E = FD->getDeclsInPrototypeScope().end();\n"
2033 " I != E; ++I) {\n}");
2034 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2035 " I = Container.begin(),\n"
2036 " E = Container.end();\n"
2037 " I != E; ++I) {\n}",
2038 getLLVMStyleWithColumns(76));
2039
2040 verifyFormat(
2041 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2042 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2044 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2045 " ++aaaaaaaaaaa) {\n}");
2046 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2047 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2048 " ++i) {\n}");
2049 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2050 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2051 "}");
2052 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2053 " aaaaaaaaaa);\n"
2054 " iter; ++iter) {\n"
2055 "}");
2056 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2057 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2058 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2059 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2060
2061 // These should not be formatted as Objective-C for-in loops.
2062 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2063 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2064 verifyFormat("Foo *x;\nfor (x in y) {\n}");
2065 verifyFormat(
2066 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2067
2068 FormatStyle NoBinPacking = getLLVMStyle();
2069 NoBinPacking.BinPackParameters = false;
2070 verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2071 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2072 " aaaaaaaaaaaaaaaa,\n"
2073 " aaaaaaaaaaaaaaaa,\n"
2074 " aaaaaaaaaaaaaaaa);\n"
2075 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2076 "}",
2077 NoBinPacking);
2078 verifyFormat(
2079 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2080 " E = UnwrappedLines.end();\n"
2081 " I != E;\n"
2082 " ++I) {\n}",
2083 NoBinPacking);
2084
2085 FormatStyle AlignLeft = getLLVMStyle();
2086 AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2087 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2088 }
2089
TEST_F(FormatTest,RangeBasedForLoops)2090 TEST_F(FormatTest, RangeBasedForLoops) {
2091 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2092 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2093 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2094 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2095 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2096 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2097 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2098 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2099 }
2100
TEST_F(FormatTest,ForEachLoops)2101 TEST_F(FormatTest, ForEachLoops) {
2102 verifyFormat("void f() {\n"
2103 " foreach (Item *item, itemlist) {}\n"
2104 " Q_FOREACH (Item *item, itemlist) {}\n"
2105 " BOOST_FOREACH (Item *item, itemlist) {}\n"
2106 " UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2107 "}");
2108
2109 FormatStyle Style = getLLVMStyle();
2110 Style.SpaceBeforeParens =
2111 FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2112 verifyFormat("void f() {\n"
2113 " foreach(Item *item, itemlist) {}\n"
2114 " Q_FOREACH(Item *item, itemlist) {}\n"
2115 " BOOST_FOREACH(Item *item, itemlist) {}\n"
2116 " UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2117 "}",
2118 Style);
2119
2120 // As function-like macros.
2121 verifyFormat("#define foreach(x, y)\n"
2122 "#define Q_FOREACH(x, y)\n"
2123 "#define BOOST_FOREACH(x, y)\n"
2124 "#define UNKNOWN_FOREACH(x, y)\n");
2125
2126 // Not as function-like macros.
2127 verifyFormat("#define foreach (x, y)\n"
2128 "#define Q_FOREACH (x, y)\n"
2129 "#define BOOST_FOREACH (x, y)\n"
2130 "#define UNKNOWN_FOREACH (x, y)\n");
2131
2132 // handle microsoft non standard extension
2133 verifyFormat("for each (char c in x->MyStringProperty)");
2134 }
2135
TEST_F(FormatTest,FormatsWhileLoop)2136 TEST_F(FormatTest, FormatsWhileLoop) {
2137 verifyFormat("while (true) {\n}");
2138 verifyFormat("while (true)\n"
2139 " f();");
2140 verifyFormat("while () {\n}");
2141 verifyFormat("while () {\n"
2142 " f();\n"
2143 "}");
2144 }
2145
TEST_F(FormatTest,FormatsDoWhile)2146 TEST_F(FormatTest, FormatsDoWhile) {
2147 verifyFormat("do {\n"
2148 " do_something();\n"
2149 "} while (something());");
2150 verifyFormat("do\n"
2151 " do_something();\n"
2152 "while (something());");
2153 }
2154
TEST_F(FormatTest,FormatsSwitchStatement)2155 TEST_F(FormatTest, FormatsSwitchStatement) {
2156 verifyFormat("switch (x) {\n"
2157 "case 1:\n"
2158 " f();\n"
2159 " break;\n"
2160 "case kFoo:\n"
2161 "case ns::kBar:\n"
2162 "case kBaz:\n"
2163 " break;\n"
2164 "default:\n"
2165 " g();\n"
2166 " break;\n"
2167 "}");
2168 verifyFormat("switch (x) {\n"
2169 "case 1: {\n"
2170 " f();\n"
2171 " break;\n"
2172 "}\n"
2173 "case 2: {\n"
2174 " break;\n"
2175 "}\n"
2176 "}");
2177 verifyFormat("switch (x) {\n"
2178 "case 1: {\n"
2179 " f();\n"
2180 " {\n"
2181 " g();\n"
2182 " h();\n"
2183 " }\n"
2184 " break;\n"
2185 "}\n"
2186 "}");
2187 verifyFormat("switch (x) {\n"
2188 "case 1: {\n"
2189 " f();\n"
2190 " if (foo) {\n"
2191 " g();\n"
2192 " h();\n"
2193 " }\n"
2194 " break;\n"
2195 "}\n"
2196 "}");
2197 verifyFormat("switch (x) {\n"
2198 "case 1: {\n"
2199 " f();\n"
2200 " g();\n"
2201 "} break;\n"
2202 "}");
2203 verifyFormat("switch (test)\n"
2204 " ;");
2205 verifyFormat("switch (x) {\n"
2206 "default: {\n"
2207 " // Do nothing.\n"
2208 "}\n"
2209 "}");
2210 verifyFormat("switch (x) {\n"
2211 "// comment\n"
2212 "// if 1, do f()\n"
2213 "case 1:\n"
2214 " f();\n"
2215 "}");
2216 verifyFormat("switch (x) {\n"
2217 "case 1:\n"
2218 " // Do amazing stuff\n"
2219 " {\n"
2220 " f();\n"
2221 " g();\n"
2222 " }\n"
2223 " break;\n"
2224 "}");
2225 verifyFormat("#define A \\\n"
2226 " switch (x) { \\\n"
2227 " case a: \\\n"
2228 " foo = b; \\\n"
2229 " }",
2230 getLLVMStyleWithColumns(20));
2231 verifyFormat("#define OPERATION_CASE(name) \\\n"
2232 " case OP_name: \\\n"
2233 " return operations::Operation##name\n",
2234 getLLVMStyleWithColumns(40));
2235 verifyFormat("switch (x) {\n"
2236 "case 1:;\n"
2237 "default:;\n"
2238 " int i;\n"
2239 "}");
2240
2241 verifyGoogleFormat("switch (x) {\n"
2242 " case 1:\n"
2243 " f();\n"
2244 " break;\n"
2245 " case kFoo:\n"
2246 " case ns::kBar:\n"
2247 " case kBaz:\n"
2248 " break;\n"
2249 " default:\n"
2250 " g();\n"
2251 " break;\n"
2252 "}");
2253 verifyGoogleFormat("switch (x) {\n"
2254 " case 1: {\n"
2255 " f();\n"
2256 " break;\n"
2257 " }\n"
2258 "}");
2259 verifyGoogleFormat("switch (test)\n"
2260 " ;");
2261
2262 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2263 " case OP_name: \\\n"
2264 " return operations::Operation##name\n");
2265 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2266 " // Get the correction operation class.\n"
2267 " switch (OpCode) {\n"
2268 " CASE(Add);\n"
2269 " CASE(Subtract);\n"
2270 " default:\n"
2271 " return operations::Unknown;\n"
2272 " }\n"
2273 "#undef OPERATION_CASE\n"
2274 "}");
2275 verifyFormat("DEBUG({\n"
2276 " switch (x) {\n"
2277 " case A:\n"
2278 " f();\n"
2279 " break;\n"
2280 " // fallthrough\n"
2281 " case B:\n"
2282 " g();\n"
2283 " break;\n"
2284 " }\n"
2285 "});");
2286 EXPECT_EQ("DEBUG({\n"
2287 " switch (x) {\n"
2288 " case A:\n"
2289 " f();\n"
2290 " break;\n"
2291 " // On B:\n"
2292 " case B:\n"
2293 " g();\n"
2294 " break;\n"
2295 " }\n"
2296 "});",
2297 format("DEBUG({\n"
2298 " switch (x) {\n"
2299 " case A:\n"
2300 " f();\n"
2301 " break;\n"
2302 " // On B:\n"
2303 " case B:\n"
2304 " g();\n"
2305 " break;\n"
2306 " }\n"
2307 "});",
2308 getLLVMStyle()));
2309 EXPECT_EQ("switch (n) {\n"
2310 "case 0: {\n"
2311 " return false;\n"
2312 "}\n"
2313 "default: {\n"
2314 " return true;\n"
2315 "}\n"
2316 "}",
2317 format("switch (n)\n"
2318 "{\n"
2319 "case 0: {\n"
2320 " return false;\n"
2321 "}\n"
2322 "default: {\n"
2323 " return true;\n"
2324 "}\n"
2325 "}",
2326 getLLVMStyle()));
2327 verifyFormat("switch (a) {\n"
2328 "case (b):\n"
2329 " return;\n"
2330 "}");
2331
2332 verifyFormat("switch (a) {\n"
2333 "case some_namespace::\n"
2334 " some_constant:\n"
2335 " return;\n"
2336 "}",
2337 getLLVMStyleWithColumns(34));
2338
2339 FormatStyle Style = getLLVMStyle();
2340 Style.IndentCaseLabels = true;
2341 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2342 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2343 Style.BraceWrapping.AfterCaseLabel = true;
2344 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2345 EXPECT_EQ("switch (n)\n"
2346 "{\n"
2347 " case 0:\n"
2348 " {\n"
2349 " return false;\n"
2350 " }\n"
2351 " default:\n"
2352 " {\n"
2353 " return true;\n"
2354 " }\n"
2355 "}",
2356 format("switch (n) {\n"
2357 " case 0: {\n"
2358 " return false;\n"
2359 " }\n"
2360 " default: {\n"
2361 " return true;\n"
2362 " }\n"
2363 "}",
2364 Style));
2365 Style.BraceWrapping.AfterCaseLabel = false;
2366 EXPECT_EQ("switch (n)\n"
2367 "{\n"
2368 " case 0: {\n"
2369 " return false;\n"
2370 " }\n"
2371 " default: {\n"
2372 " return true;\n"
2373 " }\n"
2374 "}",
2375 format("switch (n) {\n"
2376 " case 0:\n"
2377 " {\n"
2378 " return false;\n"
2379 " }\n"
2380 " default:\n"
2381 " {\n"
2382 " return true;\n"
2383 " }\n"
2384 "}",
2385 Style));
2386 Style.IndentCaseLabels = false;
2387 Style.IndentCaseBlocks = true;
2388 EXPECT_EQ("switch (n)\n"
2389 "{\n"
2390 "case 0:\n"
2391 " {\n"
2392 " return false;\n"
2393 " }\n"
2394 "case 1:\n"
2395 " break;\n"
2396 "default:\n"
2397 " {\n"
2398 " return true;\n"
2399 " }\n"
2400 "}",
2401 format("switch (n) {\n"
2402 "case 0: {\n"
2403 " return false;\n"
2404 "}\n"
2405 "case 1:\n"
2406 " break;\n"
2407 "default: {\n"
2408 " return true;\n"
2409 "}\n"
2410 "}",
2411 Style));
2412 Style.IndentCaseLabels = true;
2413 Style.IndentCaseBlocks = true;
2414 EXPECT_EQ("switch (n)\n"
2415 "{\n"
2416 " case 0:\n"
2417 " {\n"
2418 " return false;\n"
2419 " }\n"
2420 " case 1:\n"
2421 " break;\n"
2422 " default:\n"
2423 " {\n"
2424 " return true;\n"
2425 " }\n"
2426 "}",
2427 format("switch (n) {\n"
2428 "case 0: {\n"
2429 " return false;\n"
2430 "}\n"
2431 "case 1:\n"
2432 " break;\n"
2433 "default: {\n"
2434 " return true;\n"
2435 "}\n"
2436 "}",
2437 Style));
2438 }
2439
TEST_F(FormatTest,CaseRanges)2440 TEST_F(FormatTest, CaseRanges) {
2441 verifyFormat("switch (x) {\n"
2442 "case 'A' ... 'Z':\n"
2443 "case 1 ... 5:\n"
2444 "case a ... b:\n"
2445 " break;\n"
2446 "}");
2447 }
2448
TEST_F(FormatTest,ShortEnums)2449 TEST_F(FormatTest, ShortEnums) {
2450 FormatStyle Style = getLLVMStyle();
2451 Style.AllowShortEnumsOnASingleLine = true;
2452 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2453 Style.AllowShortEnumsOnASingleLine = false;
2454 verifyFormat("enum {\n"
2455 " A,\n"
2456 " B,\n"
2457 " C\n"
2458 "} ShortEnum1, ShortEnum2;",
2459 Style);
2460 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2461 Style.BraceWrapping.AfterEnum = true;
2462 verifyFormat("enum\n"
2463 "{\n"
2464 " A,\n"
2465 " B,\n"
2466 " C\n"
2467 "} ShortEnum1, ShortEnum2;",
2468 Style);
2469 }
2470
TEST_F(FormatTest,ShortCaseLabels)2471 TEST_F(FormatTest, ShortCaseLabels) {
2472 FormatStyle Style = getLLVMStyle();
2473 Style.AllowShortCaseLabelsOnASingleLine = true;
2474 verifyFormat("switch (a) {\n"
2475 "case 1: x = 1; break;\n"
2476 "case 2: return;\n"
2477 "case 3:\n"
2478 "case 4:\n"
2479 "case 5: return;\n"
2480 "case 6: // comment\n"
2481 " return;\n"
2482 "case 7:\n"
2483 " // comment\n"
2484 " return;\n"
2485 "case 8:\n"
2486 " x = 8; // comment\n"
2487 " break;\n"
2488 "default: y = 1; break;\n"
2489 "}",
2490 Style);
2491 verifyFormat("switch (a) {\n"
2492 "case 0: return; // comment\n"
2493 "case 1: break; // comment\n"
2494 "case 2: return;\n"
2495 "// comment\n"
2496 "case 3: return;\n"
2497 "// comment 1\n"
2498 "// comment 2\n"
2499 "// comment 3\n"
2500 "case 4: break; /* comment */\n"
2501 "case 5:\n"
2502 " // comment\n"
2503 " break;\n"
2504 "case 6: /* comment */ x = 1; break;\n"
2505 "case 7: x = /* comment */ 1; break;\n"
2506 "case 8:\n"
2507 " x = 1; /* comment */\n"
2508 " break;\n"
2509 "case 9:\n"
2510 " break; // comment line 1\n"
2511 " // comment line 2\n"
2512 "}",
2513 Style);
2514 EXPECT_EQ("switch (a) {\n"
2515 "case 1:\n"
2516 " x = 8;\n"
2517 " // fall through\n"
2518 "case 2: x = 8;\n"
2519 "// comment\n"
2520 "case 3:\n"
2521 " return; /* comment line 1\n"
2522 " * comment line 2 */\n"
2523 "case 4: i = 8;\n"
2524 "// something else\n"
2525 "#if FOO\n"
2526 "case 5: break;\n"
2527 "#endif\n"
2528 "}",
2529 format("switch (a) {\n"
2530 "case 1: x = 8;\n"
2531 " // fall through\n"
2532 "case 2:\n"
2533 " x = 8;\n"
2534 "// comment\n"
2535 "case 3:\n"
2536 " return; /* comment line 1\n"
2537 " * comment line 2 */\n"
2538 "case 4:\n"
2539 " i = 8;\n"
2540 "// something else\n"
2541 "#if FOO\n"
2542 "case 5: break;\n"
2543 "#endif\n"
2544 "}",
2545 Style));
2546 EXPECT_EQ("switch (a) {\n"
2547 "case 0:\n"
2548 " return; // long long long long long long long long long long "
2549 "long long comment\n"
2550 " // line\n"
2551 "}",
2552 format("switch (a) {\n"
2553 "case 0: return; // long long long long long long long long "
2554 "long long long long comment line\n"
2555 "}",
2556 Style));
2557 EXPECT_EQ("switch (a) {\n"
2558 "case 0:\n"
2559 " return; /* long long long long long long long long long long "
2560 "long long comment\n"
2561 " line */\n"
2562 "}",
2563 format("switch (a) {\n"
2564 "case 0: return; /* long long long long long long long long "
2565 "long long long long comment line */\n"
2566 "}",
2567 Style));
2568 verifyFormat("switch (a) {\n"
2569 "#if FOO\n"
2570 "case 0: return 0;\n"
2571 "#endif\n"
2572 "}",
2573 Style);
2574 verifyFormat("switch (a) {\n"
2575 "case 1: {\n"
2576 "}\n"
2577 "case 2: {\n"
2578 " return;\n"
2579 "}\n"
2580 "case 3: {\n"
2581 " x = 1;\n"
2582 " return;\n"
2583 "}\n"
2584 "case 4:\n"
2585 " if (x)\n"
2586 " return;\n"
2587 "}",
2588 Style);
2589 Style.ColumnLimit = 21;
2590 verifyFormat("switch (a) {\n"
2591 "case 1: x = 1; break;\n"
2592 "case 2: return;\n"
2593 "case 3:\n"
2594 "case 4:\n"
2595 "case 5: return;\n"
2596 "default:\n"
2597 " y = 1;\n"
2598 " break;\n"
2599 "}",
2600 Style);
2601 Style.ColumnLimit = 80;
2602 Style.AllowShortCaseLabelsOnASingleLine = false;
2603 Style.IndentCaseLabels = true;
2604 EXPECT_EQ("switch (n) {\n"
2605 " default /*comments*/:\n"
2606 " return true;\n"
2607 " case 0:\n"
2608 " return false;\n"
2609 "}",
2610 format("switch (n) {\n"
2611 "default/*comments*/:\n"
2612 " return true;\n"
2613 "case 0:\n"
2614 " return false;\n"
2615 "}",
2616 Style));
2617 Style.AllowShortCaseLabelsOnASingleLine = true;
2618 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2619 Style.BraceWrapping.AfterCaseLabel = true;
2620 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2621 EXPECT_EQ("switch (n)\n"
2622 "{\n"
2623 " case 0:\n"
2624 " {\n"
2625 " return false;\n"
2626 " }\n"
2627 " default:\n"
2628 " {\n"
2629 " return true;\n"
2630 " }\n"
2631 "}",
2632 format("switch (n) {\n"
2633 " case 0: {\n"
2634 " return false;\n"
2635 " }\n"
2636 " default:\n"
2637 " {\n"
2638 " return true;\n"
2639 " }\n"
2640 "}",
2641 Style));
2642 }
2643
TEST_F(FormatTest,FormatsLabels)2644 TEST_F(FormatTest, FormatsLabels) {
2645 verifyFormat("void f() {\n"
2646 " some_code();\n"
2647 "test_label:\n"
2648 " some_other_code();\n"
2649 " {\n"
2650 " some_more_code();\n"
2651 " another_label:\n"
2652 " some_more_code();\n"
2653 " }\n"
2654 "}");
2655 verifyFormat("{\n"
2656 " some_code();\n"
2657 "test_label:\n"
2658 " some_other_code();\n"
2659 "}");
2660 verifyFormat("{\n"
2661 " some_code();\n"
2662 "test_label:;\n"
2663 " int i = 0;\n"
2664 "}");
2665 FormatStyle Style = getLLVMStyle();
2666 Style.IndentGotoLabels = false;
2667 verifyFormat("void f() {\n"
2668 " some_code();\n"
2669 "test_label:\n"
2670 " some_other_code();\n"
2671 " {\n"
2672 " some_more_code();\n"
2673 "another_label:\n"
2674 " some_more_code();\n"
2675 " }\n"
2676 "}",
2677 Style);
2678 verifyFormat("{\n"
2679 " some_code();\n"
2680 "test_label:\n"
2681 " some_other_code();\n"
2682 "}",
2683 Style);
2684 verifyFormat("{\n"
2685 " some_code();\n"
2686 "test_label:;\n"
2687 " int i = 0;\n"
2688 "}");
2689 }
2690
TEST_F(FormatTest,MultiLineControlStatements)2691 TEST_F(FormatTest, MultiLineControlStatements) {
2692 FormatStyle Style = getLLVMStyle();
2693 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2694 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2695 Style.ColumnLimit = 20;
2696 // Short lines should keep opening brace on same line.
2697 EXPECT_EQ("if (foo) {\n"
2698 " bar();\n"
2699 "}",
2700 format("if(foo){bar();}", Style));
2701 EXPECT_EQ("if (foo) {\n"
2702 " bar();\n"
2703 "} else {\n"
2704 " baz();\n"
2705 "}",
2706 format("if(foo){bar();}else{baz();}", Style));
2707 EXPECT_EQ("if (foo && bar) {\n"
2708 " baz();\n"
2709 "}",
2710 format("if(foo&&bar){baz();}", Style));
2711 EXPECT_EQ("if (foo) {\n"
2712 " bar();\n"
2713 "} else if (baz) {\n"
2714 " quux();\n"
2715 "}",
2716 format("if(foo){bar();}else if(baz){quux();}", Style));
2717 EXPECT_EQ(
2718 "if (foo) {\n"
2719 " bar();\n"
2720 "} else if (baz) {\n"
2721 " quux();\n"
2722 "} else {\n"
2723 " foobar();\n"
2724 "}",
2725 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2726 EXPECT_EQ("for (;;) {\n"
2727 " foo();\n"
2728 "}",
2729 format("for(;;){foo();}"));
2730 EXPECT_EQ("while (1) {\n"
2731 " foo();\n"
2732 "}",
2733 format("while(1){foo();}", Style));
2734 EXPECT_EQ("switch (foo) {\n"
2735 "case bar:\n"
2736 " return;\n"
2737 "}",
2738 format("switch(foo){case bar:return;}", Style));
2739 EXPECT_EQ("try {\n"
2740 " foo();\n"
2741 "} catch (...) {\n"
2742 " bar();\n"
2743 "}",
2744 format("try{foo();}catch(...){bar();}", Style));
2745 EXPECT_EQ("do {\n"
2746 " foo();\n"
2747 "} while (bar &&\n"
2748 " baz);",
2749 format("do{foo();}while(bar&&baz);", Style));
2750 // Long lines should put opening brace on new line.
2751 EXPECT_EQ("if (foo && bar &&\n"
2752 " baz)\n"
2753 "{\n"
2754 " quux();\n"
2755 "}",
2756 format("if(foo&&bar&&baz){quux();}", Style));
2757 EXPECT_EQ("if (foo && bar &&\n"
2758 " baz)\n"
2759 "{\n"
2760 " quux();\n"
2761 "}",
2762 format("if (foo && bar &&\n"
2763 " baz) {\n"
2764 " quux();\n"
2765 "}",
2766 Style));
2767 EXPECT_EQ("if (foo) {\n"
2768 " bar();\n"
2769 "} else if (baz ||\n"
2770 " quux)\n"
2771 "{\n"
2772 " foobar();\n"
2773 "}",
2774 format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2775 EXPECT_EQ(
2776 "if (foo) {\n"
2777 " bar();\n"
2778 "} else if (baz ||\n"
2779 " quux)\n"
2780 "{\n"
2781 " foobar();\n"
2782 "} else {\n"
2783 " barbaz();\n"
2784 "}",
2785 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2786 Style));
2787 EXPECT_EQ("for (int i = 0;\n"
2788 " i < 10; ++i)\n"
2789 "{\n"
2790 " foo();\n"
2791 "}",
2792 format("for(int i=0;i<10;++i){foo();}", Style));
2793 EXPECT_EQ("foreach (int i,\n"
2794 " list)\n"
2795 "{\n"
2796 " foo();\n"
2797 "}",
2798 format("foreach(int i, list){foo();}", Style));
2799 Style.ColumnLimit =
2800 40; // to concentrate at brace wrapping, not line wrap due to column limit
2801 EXPECT_EQ("foreach (int i, list) {\n"
2802 " foo();\n"
2803 "}",
2804 format("foreach(int i, list){foo();}", Style));
2805 Style.ColumnLimit =
2806 20; // to concentrate at brace wrapping, not line wrap due to column limit
2807 EXPECT_EQ("while (foo || bar ||\n"
2808 " baz)\n"
2809 "{\n"
2810 " quux();\n"
2811 "}",
2812 format("while(foo||bar||baz){quux();}", Style));
2813 EXPECT_EQ("switch (\n"
2814 " foo = barbaz)\n"
2815 "{\n"
2816 "case quux:\n"
2817 " return;\n"
2818 "}",
2819 format("switch(foo=barbaz){case quux:return;}", Style));
2820 EXPECT_EQ("try {\n"
2821 " foo();\n"
2822 "} catch (\n"
2823 " Exception &bar)\n"
2824 "{\n"
2825 " baz();\n"
2826 "}",
2827 format("try{foo();}catch(Exception&bar){baz();}", Style));
2828 Style.ColumnLimit =
2829 40; // to concentrate at brace wrapping, not line wrap due to column limit
2830 EXPECT_EQ("try {\n"
2831 " foo();\n"
2832 "} catch (Exception &bar) {\n"
2833 " baz();\n"
2834 "}",
2835 format("try{foo();}catch(Exception&bar){baz();}", Style));
2836 Style.ColumnLimit =
2837 20; // to concentrate at brace wrapping, not line wrap due to column limit
2838
2839 Style.BraceWrapping.BeforeElse = true;
2840 EXPECT_EQ(
2841 "if (foo) {\n"
2842 " bar();\n"
2843 "}\n"
2844 "else if (baz ||\n"
2845 " quux)\n"
2846 "{\n"
2847 " foobar();\n"
2848 "}\n"
2849 "else {\n"
2850 " barbaz();\n"
2851 "}",
2852 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2853 Style));
2854
2855 Style.BraceWrapping.BeforeCatch = true;
2856 EXPECT_EQ("try {\n"
2857 " foo();\n"
2858 "}\n"
2859 "catch (...) {\n"
2860 " baz();\n"
2861 "}",
2862 format("try{foo();}catch(...){baz();}", Style));
2863 }
2864
TEST_F(FormatTest,BeforeWhile)2865 TEST_F(FormatTest, BeforeWhile) {
2866 FormatStyle Style = getLLVMStyle();
2867 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2868
2869 verifyFormat("do {\n"
2870 " foo();\n"
2871 "} while (1);",
2872 Style);
2873 Style.BraceWrapping.BeforeWhile = true;
2874 verifyFormat("do {\n"
2875 " foo();\n"
2876 "}\n"
2877 "while (1);",
2878 Style);
2879 }
2880
2881 //===----------------------------------------------------------------------===//
2882 // Tests for classes, namespaces, etc.
2883 //===----------------------------------------------------------------------===//
2884
TEST_F(FormatTest,DoesNotBreakSemiAfterClassDecl)2885 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
2886 verifyFormat("class A {};");
2887 }
2888
TEST_F(FormatTest,UnderstandsAccessSpecifiers)2889 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
2890 verifyFormat("class A {\n"
2891 "public:\n"
2892 "public: // comment\n"
2893 "protected:\n"
2894 "private:\n"
2895 " void f() {}\n"
2896 "};");
2897 verifyFormat("export class A {\n"
2898 "public:\n"
2899 "public: // comment\n"
2900 "protected:\n"
2901 "private:\n"
2902 " void f() {}\n"
2903 "};");
2904 verifyGoogleFormat("class A {\n"
2905 " public:\n"
2906 " protected:\n"
2907 " private:\n"
2908 " void f() {}\n"
2909 "};");
2910 verifyGoogleFormat("export class A {\n"
2911 " public:\n"
2912 " protected:\n"
2913 " private:\n"
2914 " void f() {}\n"
2915 "};");
2916 verifyFormat("class A {\n"
2917 "public slots:\n"
2918 " void f1() {}\n"
2919 "public Q_SLOTS:\n"
2920 " void f2() {}\n"
2921 "protected slots:\n"
2922 " void f3() {}\n"
2923 "protected Q_SLOTS:\n"
2924 " void f4() {}\n"
2925 "private slots:\n"
2926 " void f5() {}\n"
2927 "private Q_SLOTS:\n"
2928 " void f6() {}\n"
2929 "signals:\n"
2930 " void g1();\n"
2931 "Q_SIGNALS:\n"
2932 " void g2();\n"
2933 "};");
2934
2935 // Don't interpret 'signals' the wrong way.
2936 verifyFormat("signals.set();");
2937 verifyFormat("for (Signals signals : f()) {\n}");
2938 verifyFormat("{\n"
2939 " signals.set(); // This needs indentation.\n"
2940 "}");
2941 verifyFormat("void f() {\n"
2942 "label:\n"
2943 " signals.baz();\n"
2944 "}");
2945 }
2946
TEST_F(FormatTest,SeparatesLogicalBlocks)2947 TEST_F(FormatTest, SeparatesLogicalBlocks) {
2948 EXPECT_EQ("class A {\n"
2949 "public:\n"
2950 " void f();\n"
2951 "\n"
2952 "private:\n"
2953 " void g() {}\n"
2954 " // test\n"
2955 "protected:\n"
2956 " int h;\n"
2957 "};",
2958 format("class A {\n"
2959 "public:\n"
2960 "void f();\n"
2961 "private:\n"
2962 "void g() {}\n"
2963 "// test\n"
2964 "protected:\n"
2965 "int h;\n"
2966 "};"));
2967 EXPECT_EQ("class A {\n"
2968 "protected:\n"
2969 "public:\n"
2970 " void f();\n"
2971 "};",
2972 format("class A {\n"
2973 "protected:\n"
2974 "\n"
2975 "public:\n"
2976 "\n"
2977 " void f();\n"
2978 "};"));
2979
2980 // Even ensure proper spacing inside macros.
2981 EXPECT_EQ("#define B \\\n"
2982 " class A { \\\n"
2983 " protected: \\\n"
2984 " public: \\\n"
2985 " void f(); \\\n"
2986 " };",
2987 format("#define B \\\n"
2988 " class A { \\\n"
2989 " protected: \\\n"
2990 " \\\n"
2991 " public: \\\n"
2992 " \\\n"
2993 " void f(); \\\n"
2994 " };",
2995 getGoogleStyle()));
2996 // But don't remove empty lines after macros ending in access specifiers.
2997 EXPECT_EQ("#define A private:\n"
2998 "\n"
2999 "int i;",
3000 format("#define A private:\n"
3001 "\n"
3002 "int i;"));
3003 }
3004
TEST_F(FormatTest,FormatsClasses)3005 TEST_F(FormatTest, FormatsClasses) {
3006 verifyFormat("class A : public B {};");
3007 verifyFormat("class A : public ::B {};");
3008
3009 verifyFormat(
3010 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3011 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3012 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3013 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3014 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3015 verifyFormat(
3016 "class A : public B, public C, public D, public E, public F {};");
3017 verifyFormat("class AAAAAAAAAAAA : public B,\n"
3018 " public C,\n"
3019 " public D,\n"
3020 " public E,\n"
3021 " public F,\n"
3022 " public G {};");
3023
3024 verifyFormat("class\n"
3025 " ReallyReallyLongClassName {\n"
3026 " int i;\n"
3027 "};",
3028 getLLVMStyleWithColumns(32));
3029 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3030 " aaaaaaaaaaaaaaaa> {};");
3031 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3032 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3033 " aaaaaaaaaaaaaaaaaaaaaa> {};");
3034 verifyFormat("template <class R, class C>\n"
3035 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3036 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3037 verifyFormat("class ::A::B {};");
3038 }
3039
TEST_F(FormatTest,BreakInheritanceStyle)3040 TEST_F(FormatTest, BreakInheritanceStyle) {
3041 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3042 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3043 FormatStyle::BILS_BeforeComma;
3044 verifyFormat("class MyClass : public X {};",
3045 StyleWithInheritanceBreakBeforeComma);
3046 verifyFormat("class MyClass\n"
3047 " : public X\n"
3048 " , public Y {};",
3049 StyleWithInheritanceBreakBeforeComma);
3050 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3051 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3052 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3053 StyleWithInheritanceBreakBeforeComma);
3054 verifyFormat("struct aaaaaaaaaaaaa\n"
3055 " : public aaaaaaaaaaaaaaaaaaa< // break\n"
3056 " aaaaaaaaaaaaaaaa> {};",
3057 StyleWithInheritanceBreakBeforeComma);
3058
3059 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3060 StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3061 FormatStyle::BILS_AfterColon;
3062 verifyFormat("class MyClass : public X {};",
3063 StyleWithInheritanceBreakAfterColon);
3064 verifyFormat("class MyClass : public X, public Y {};",
3065 StyleWithInheritanceBreakAfterColon);
3066 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3067 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3068 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3069 StyleWithInheritanceBreakAfterColon);
3070 verifyFormat("struct aaaaaaaaaaaaa :\n"
3071 " public aaaaaaaaaaaaaaaaaaa< // break\n"
3072 " aaaaaaaaaaaaaaaa> {};",
3073 StyleWithInheritanceBreakAfterColon);
3074
3075 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3076 StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3077 FormatStyle::BILS_AfterComma;
3078 verifyFormat("class MyClass : public X {};",
3079 StyleWithInheritanceBreakAfterComma);
3080 verifyFormat("class MyClass : public X,\n"
3081 " public Y {};",
3082 StyleWithInheritanceBreakAfterComma);
3083 verifyFormat(
3084 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3085 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3086 "{};",
3087 StyleWithInheritanceBreakAfterComma);
3088 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3089 " aaaaaaaaaaaaaaaa> {};",
3090 StyleWithInheritanceBreakAfterComma);
3091 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3092 " : public OnceBreak,\n"
3093 " public AlwaysBreak,\n"
3094 " EvenBasesFitInOneLine {};",
3095 StyleWithInheritanceBreakAfterComma);
3096 }
3097
TEST_F(FormatTest,FormatsVariableDeclarationsAfterStructOrClass)3098 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3099 verifyFormat("class A {\n} a, b;");
3100 verifyFormat("struct A {\n} a, b;");
3101 verifyFormat("union A {\n} a;");
3102 }
3103
TEST_F(FormatTest,FormatsEnum)3104 TEST_F(FormatTest, FormatsEnum) {
3105 verifyFormat("enum {\n"
3106 " Zero,\n"
3107 " One = 1,\n"
3108 " Two = One + 1,\n"
3109 " Three = (One + Two),\n"
3110 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
3111 " Five = (One, Two, Three, Four, 5)\n"
3112 "};");
3113 verifyGoogleFormat("enum {\n"
3114 " Zero,\n"
3115 " One = 1,\n"
3116 " Two = One + 1,\n"
3117 " Three = (One + Two),\n"
3118 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
3119 " Five = (One, Two, Three, Four, 5)\n"
3120 "};");
3121 verifyFormat("enum Enum {};");
3122 verifyFormat("enum {};");
3123 verifyFormat("enum X E {} d;");
3124 verifyFormat("enum __attribute__((...)) E {} d;");
3125 verifyFormat("enum __declspec__((...)) E {} d;");
3126 verifyFormat("enum {\n"
3127 " Bar = Foo<int, int>::value\n"
3128 "};",
3129 getLLVMStyleWithColumns(30));
3130
3131 verifyFormat("enum ShortEnum { A, B, C };");
3132 verifyGoogleFormat("enum ShortEnum { A, B, C };");
3133
3134 EXPECT_EQ("enum KeepEmptyLines {\n"
3135 " ONE,\n"
3136 "\n"
3137 " TWO,\n"
3138 "\n"
3139 " THREE\n"
3140 "}",
3141 format("enum KeepEmptyLines {\n"
3142 " ONE,\n"
3143 "\n"
3144 " TWO,\n"
3145 "\n"
3146 "\n"
3147 " THREE\n"
3148 "}"));
3149 verifyFormat("enum E { // comment\n"
3150 " ONE,\n"
3151 " TWO\n"
3152 "};\n"
3153 "int i;");
3154
3155 FormatStyle EightIndent = getLLVMStyle();
3156 EightIndent.IndentWidth = 8;
3157 verifyFormat("enum {\n"
3158 " VOID,\n"
3159 " CHAR,\n"
3160 " SHORT,\n"
3161 " INT,\n"
3162 " LONG,\n"
3163 " SIGNED,\n"
3164 " UNSIGNED,\n"
3165 " BOOL,\n"
3166 " FLOAT,\n"
3167 " DOUBLE,\n"
3168 " COMPLEX\n"
3169 "};",
3170 EightIndent);
3171
3172 // Not enums.
3173 verifyFormat("enum X f() {\n"
3174 " a();\n"
3175 " return 42;\n"
3176 "}");
3177 verifyFormat("enum X Type::f() {\n"
3178 " a();\n"
3179 " return 42;\n"
3180 "}");
3181 verifyFormat("enum ::X f() {\n"
3182 " a();\n"
3183 " return 42;\n"
3184 "}");
3185 verifyFormat("enum ns::X f() {\n"
3186 " a();\n"
3187 " return 42;\n"
3188 "}");
3189 }
3190
TEST_F(FormatTest,FormatsEnumsWithErrors)3191 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3192 verifyFormat("enum Type {\n"
3193 " One = 0; // These semicolons should be commas.\n"
3194 " Two = 1;\n"
3195 "};");
3196 verifyFormat("namespace n {\n"
3197 "enum Type {\n"
3198 " One,\n"
3199 " Two, // missing };\n"
3200 " int i;\n"
3201 "}\n"
3202 "void g() {}");
3203 }
3204
TEST_F(FormatTest,FormatsEnumStruct)3205 TEST_F(FormatTest, FormatsEnumStruct) {
3206 verifyFormat("enum struct {\n"
3207 " Zero,\n"
3208 " One = 1,\n"
3209 " Two = One + 1,\n"
3210 " Three = (One + Two),\n"
3211 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
3212 " Five = (One, Two, Three, Four, 5)\n"
3213 "};");
3214 verifyFormat("enum struct Enum {};");
3215 verifyFormat("enum struct {};");
3216 verifyFormat("enum struct X E {} d;");
3217 verifyFormat("enum struct __attribute__((...)) E {} d;");
3218 verifyFormat("enum struct __declspec__((...)) E {} d;");
3219 verifyFormat("enum struct X f() {\n a();\n return 42;\n}");
3220 }
3221
TEST_F(FormatTest,FormatsEnumClass)3222 TEST_F(FormatTest, FormatsEnumClass) {
3223 verifyFormat("enum class {\n"
3224 " Zero,\n"
3225 " One = 1,\n"
3226 " Two = One + 1,\n"
3227 " Three = (One + Two),\n"
3228 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
3229 " Five = (One, Two, Three, Four, 5)\n"
3230 "};");
3231 verifyFormat("enum class Enum {};");
3232 verifyFormat("enum class {};");
3233 verifyFormat("enum class X E {} d;");
3234 verifyFormat("enum class __attribute__((...)) E {} d;");
3235 verifyFormat("enum class __declspec__((...)) E {} d;");
3236 verifyFormat("enum class X f() {\n a();\n return 42;\n}");
3237 }
3238
TEST_F(FormatTest,FormatsEnumTypes)3239 TEST_F(FormatTest, FormatsEnumTypes) {
3240 verifyFormat("enum X : int {\n"
3241 " A, // Force multiple lines.\n"
3242 " B\n"
3243 "};");
3244 verifyFormat("enum X : int { A, B };");
3245 verifyFormat("enum X : std::uint32_t { A, B };");
3246 }
3247
TEST_F(FormatTest,FormatsTypedefEnum)3248 TEST_F(FormatTest, FormatsTypedefEnum) {
3249 FormatStyle Style = getLLVMStyle();
3250 Style.ColumnLimit = 40;
3251 verifyFormat("typedef enum {} EmptyEnum;");
3252 verifyFormat("typedef enum { A, B, C } ShortEnum;");
3253 verifyFormat("typedef enum {\n"
3254 " ZERO = 0,\n"
3255 " ONE = 1,\n"
3256 " TWO = 2,\n"
3257 " THREE = 3\n"
3258 "} LongEnum;",
3259 Style);
3260 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3261 Style.BraceWrapping.AfterEnum = true;
3262 verifyFormat("typedef enum {} EmptyEnum;");
3263 verifyFormat("typedef enum { A, B, C } ShortEnum;");
3264 verifyFormat("typedef enum\n"
3265 "{\n"
3266 " ZERO = 0,\n"
3267 " ONE = 1,\n"
3268 " TWO = 2,\n"
3269 " THREE = 3\n"
3270 "} LongEnum;",
3271 Style);
3272 }
3273
TEST_F(FormatTest,FormatsNSEnums)3274 TEST_F(FormatTest, FormatsNSEnums) {
3275 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3276 verifyGoogleFormat(
3277 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3278 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3279 " // Information about someDecentlyLongValue.\n"
3280 " someDecentlyLongValue,\n"
3281 " // Information about anotherDecentlyLongValue.\n"
3282 " anotherDecentlyLongValue,\n"
3283 " // Information about aThirdDecentlyLongValue.\n"
3284 " aThirdDecentlyLongValue\n"
3285 "};");
3286 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3287 " // Information about someDecentlyLongValue.\n"
3288 " someDecentlyLongValue,\n"
3289 " // Information about anotherDecentlyLongValue.\n"
3290 " anotherDecentlyLongValue,\n"
3291 " // Information about aThirdDecentlyLongValue.\n"
3292 " aThirdDecentlyLongValue\n"
3293 "};");
3294 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3295 " a = 1,\n"
3296 " b = 2,\n"
3297 " c = 3,\n"
3298 "};");
3299 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3300 " a = 1,\n"
3301 " b = 2,\n"
3302 " c = 3,\n"
3303 "};");
3304 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3305 " a = 1,\n"
3306 " b = 2,\n"
3307 " c = 3,\n"
3308 "};");
3309 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3310 " a = 1,\n"
3311 " b = 2,\n"
3312 " c = 3,\n"
3313 "};");
3314 }
3315
TEST_F(FormatTest,FormatsBitfields)3316 TEST_F(FormatTest, FormatsBitfields) {
3317 verifyFormat("struct Bitfields {\n"
3318 " unsigned sClass : 8;\n"
3319 " unsigned ValueKind : 2;\n"
3320 "};");
3321 verifyFormat("struct A {\n"
3322 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3323 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3324 "};");
3325 verifyFormat("struct MyStruct {\n"
3326 " uchar data;\n"
3327 " uchar : 8;\n"
3328 " uchar : 8;\n"
3329 " uchar other;\n"
3330 "};");
3331 FormatStyle Style = getLLVMStyle();
3332 Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3333 verifyFormat("struct Bitfields {\n"
3334 " unsigned sClass:8;\n"
3335 " unsigned ValueKind:2;\n"
3336 " uchar other;\n"
3337 "};",
3338 Style);
3339 verifyFormat("struct A {\n"
3340 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3341 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3342 "};",
3343 Style);
3344 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3345 verifyFormat("struct Bitfields {\n"
3346 " unsigned sClass :8;\n"
3347 " unsigned ValueKind :2;\n"
3348 " uchar other;\n"
3349 "};",
3350 Style);
3351 Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3352 verifyFormat("struct Bitfields {\n"
3353 " unsigned sClass: 8;\n"
3354 " unsigned ValueKind: 2;\n"
3355 " uchar other;\n"
3356 "};",
3357 Style);
3358 }
3359
TEST_F(FormatTest,FormatsNamespaces)3360 TEST_F(FormatTest, FormatsNamespaces) {
3361 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3362 LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3363
3364 verifyFormat("namespace some_namespace {\n"
3365 "class A {};\n"
3366 "void f() { f(); }\n"
3367 "}",
3368 LLVMWithNoNamespaceFix);
3369 verifyFormat("namespace N::inline D {\n"
3370 "class A {};\n"
3371 "void f() { f(); }\n"
3372 "}",
3373 LLVMWithNoNamespaceFix);
3374 verifyFormat("namespace N::inline D::E {\n"
3375 "class A {};\n"
3376 "void f() { f(); }\n"
3377 "}",
3378 LLVMWithNoNamespaceFix);
3379 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3380 "class A {};\n"
3381 "void f() { f(); }\n"
3382 "}",
3383 LLVMWithNoNamespaceFix);
3384 verifyFormat("/* something */ namespace some_namespace {\n"
3385 "class A {};\n"
3386 "void f() { f(); }\n"
3387 "}",
3388 LLVMWithNoNamespaceFix);
3389 verifyFormat("namespace {\n"
3390 "class A {};\n"
3391 "void f() { f(); }\n"
3392 "}",
3393 LLVMWithNoNamespaceFix);
3394 verifyFormat("/* something */ namespace {\n"
3395 "class A {};\n"
3396 "void f() { f(); }\n"
3397 "}",
3398 LLVMWithNoNamespaceFix);
3399 verifyFormat("inline namespace X {\n"
3400 "class A {};\n"
3401 "void f() { f(); }\n"
3402 "}",
3403 LLVMWithNoNamespaceFix);
3404 verifyFormat("/* something */ inline namespace X {\n"
3405 "class A {};\n"
3406 "void f() { f(); }\n"
3407 "}",
3408 LLVMWithNoNamespaceFix);
3409 verifyFormat("export namespace X {\n"
3410 "class A {};\n"
3411 "void f() { f(); }\n"
3412 "}",
3413 LLVMWithNoNamespaceFix);
3414 verifyFormat("using namespace some_namespace;\n"
3415 "class A {};\n"
3416 "void f() { f(); }",
3417 LLVMWithNoNamespaceFix);
3418
3419 // This code is more common than we thought; if we
3420 // layout this correctly the semicolon will go into
3421 // its own line, which is undesirable.
3422 verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3423 verifyFormat("namespace {\n"
3424 "class A {};\n"
3425 "};",
3426 LLVMWithNoNamespaceFix);
3427
3428 verifyFormat("namespace {\n"
3429 "int SomeVariable = 0; // comment\n"
3430 "} // namespace",
3431 LLVMWithNoNamespaceFix);
3432 EXPECT_EQ("#ifndef HEADER_GUARD\n"
3433 "#define HEADER_GUARD\n"
3434 "namespace my_namespace {\n"
3435 "int i;\n"
3436 "} // my_namespace\n"
3437 "#endif // HEADER_GUARD",
3438 format("#ifndef HEADER_GUARD\n"
3439 " #define HEADER_GUARD\n"
3440 " namespace my_namespace {\n"
3441 "int i;\n"
3442 "} // my_namespace\n"
3443 "#endif // HEADER_GUARD",
3444 LLVMWithNoNamespaceFix));
3445
3446 EXPECT_EQ("namespace A::B {\n"
3447 "class C {};\n"
3448 "}",
3449 format("namespace A::B {\n"
3450 "class C {};\n"
3451 "}",
3452 LLVMWithNoNamespaceFix));
3453
3454 FormatStyle Style = getLLVMStyle();
3455 Style.NamespaceIndentation = FormatStyle::NI_All;
3456 EXPECT_EQ("namespace out {\n"
3457 " int i;\n"
3458 " namespace in {\n"
3459 " int i;\n"
3460 " } // namespace in\n"
3461 "} // namespace out",
3462 format("namespace out {\n"
3463 "int i;\n"
3464 "namespace in {\n"
3465 "int i;\n"
3466 "} // namespace in\n"
3467 "} // namespace out",
3468 Style));
3469
3470 Style.NamespaceIndentation = FormatStyle::NI_Inner;
3471 EXPECT_EQ("namespace out {\n"
3472 "int i;\n"
3473 "namespace in {\n"
3474 " int i;\n"
3475 "} // namespace in\n"
3476 "} // namespace out",
3477 format("namespace out {\n"
3478 "int i;\n"
3479 "namespace in {\n"
3480 "int i;\n"
3481 "} // namespace in\n"
3482 "} // namespace out",
3483 Style));
3484 }
3485
TEST_F(FormatTest,NamespaceMacros)3486 TEST_F(FormatTest, NamespaceMacros) {
3487 FormatStyle Style = getLLVMStyle();
3488 Style.NamespaceMacros.push_back("TESTSUITE");
3489
3490 verifyFormat("TESTSUITE(A) {\n"
3491 "int foo();\n"
3492 "} // TESTSUITE(A)",
3493 Style);
3494
3495 verifyFormat("TESTSUITE(A, B) {\n"
3496 "int foo();\n"
3497 "} // TESTSUITE(A)",
3498 Style);
3499
3500 // Properly indent according to NamespaceIndentation style
3501 Style.NamespaceIndentation = FormatStyle::NI_All;
3502 verifyFormat("TESTSUITE(A) {\n"
3503 " int foo();\n"
3504 "} // TESTSUITE(A)",
3505 Style);
3506 verifyFormat("TESTSUITE(A) {\n"
3507 " namespace B {\n"
3508 " int foo();\n"
3509 " } // namespace B\n"
3510 "} // TESTSUITE(A)",
3511 Style);
3512 verifyFormat("namespace A {\n"
3513 " TESTSUITE(B) {\n"
3514 " int foo();\n"
3515 " } // TESTSUITE(B)\n"
3516 "} // namespace A",
3517 Style);
3518
3519 Style.NamespaceIndentation = FormatStyle::NI_Inner;
3520 verifyFormat("TESTSUITE(A) {\n"
3521 "TESTSUITE(B) {\n"
3522 " int foo();\n"
3523 "} // TESTSUITE(B)\n"
3524 "} // TESTSUITE(A)",
3525 Style);
3526 verifyFormat("TESTSUITE(A) {\n"
3527 "namespace B {\n"
3528 " int foo();\n"
3529 "} // namespace B\n"
3530 "} // TESTSUITE(A)",
3531 Style);
3532 verifyFormat("namespace A {\n"
3533 "TESTSUITE(B) {\n"
3534 " int foo();\n"
3535 "} // TESTSUITE(B)\n"
3536 "} // namespace A",
3537 Style);
3538
3539 // Properly merge namespace-macros blocks in CompactNamespaces mode
3540 Style.NamespaceIndentation = FormatStyle::NI_None;
3541 Style.CompactNamespaces = true;
3542 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3543 "}} // TESTSUITE(A::B)",
3544 Style);
3545
3546 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3547 "}} // TESTSUITE(out::in)",
3548 format("TESTSUITE(out) {\n"
3549 "TESTSUITE(in) {\n"
3550 "} // TESTSUITE(in)\n"
3551 "} // TESTSUITE(out)",
3552 Style));
3553
3554 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3555 "}} // TESTSUITE(out::in)",
3556 format("TESTSUITE(out) {\n"
3557 "TESTSUITE(in) {\n"
3558 "} // TESTSUITE(in)\n"
3559 "} // TESTSUITE(out)",
3560 Style));
3561
3562 // Do not merge different namespaces/macros
3563 EXPECT_EQ("namespace out {\n"
3564 "TESTSUITE(in) {\n"
3565 "} // TESTSUITE(in)\n"
3566 "} // namespace out",
3567 format("namespace out {\n"
3568 "TESTSUITE(in) {\n"
3569 "} // TESTSUITE(in)\n"
3570 "} // namespace out",
3571 Style));
3572 EXPECT_EQ("TESTSUITE(out) {\n"
3573 "namespace in {\n"
3574 "} // namespace in\n"
3575 "} // TESTSUITE(out)",
3576 format("TESTSUITE(out) {\n"
3577 "namespace in {\n"
3578 "} // namespace in\n"
3579 "} // TESTSUITE(out)",
3580 Style));
3581 Style.NamespaceMacros.push_back("FOOBAR");
3582 EXPECT_EQ("TESTSUITE(out) {\n"
3583 "FOOBAR(in) {\n"
3584 "} // FOOBAR(in)\n"
3585 "} // TESTSUITE(out)",
3586 format("TESTSUITE(out) {\n"
3587 "FOOBAR(in) {\n"
3588 "} // FOOBAR(in)\n"
3589 "} // TESTSUITE(out)",
3590 Style));
3591 }
3592
TEST_F(FormatTest,FormatsCompactNamespaces)3593 TEST_F(FormatTest, FormatsCompactNamespaces) {
3594 FormatStyle Style = getLLVMStyle();
3595 Style.CompactNamespaces = true;
3596 Style.NamespaceMacros.push_back("TESTSUITE");
3597
3598 verifyFormat("namespace A { namespace B {\n"
3599 "}} // namespace A::B",
3600 Style);
3601
3602 EXPECT_EQ("namespace out { namespace in {\n"
3603 "}} // namespace out::in",
3604 format("namespace out {\n"
3605 "namespace in {\n"
3606 "} // namespace in\n"
3607 "} // namespace out",
3608 Style));
3609
3610 // Only namespaces which have both consecutive opening and end get compacted
3611 EXPECT_EQ("namespace out {\n"
3612 "namespace in1 {\n"
3613 "} // namespace in1\n"
3614 "namespace in2 {\n"
3615 "} // namespace in2\n"
3616 "} // namespace out",
3617 format("namespace out {\n"
3618 "namespace in1 {\n"
3619 "} // namespace in1\n"
3620 "namespace in2 {\n"
3621 "} // namespace in2\n"
3622 "} // namespace out",
3623 Style));
3624
3625 EXPECT_EQ("namespace out {\n"
3626 "int i;\n"
3627 "namespace in {\n"
3628 "int j;\n"
3629 "} // namespace in\n"
3630 "int k;\n"
3631 "} // namespace out",
3632 format("namespace out { int i;\n"
3633 "namespace in { int j; } // namespace in\n"
3634 "int k; } // namespace out",
3635 Style));
3636
3637 EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3638 "}}} // namespace A::B::C\n",
3639 format("namespace A { namespace B {\n"
3640 "namespace C {\n"
3641 "}} // namespace B::C\n"
3642 "} // namespace A\n",
3643 Style));
3644
3645 Style.ColumnLimit = 40;
3646 EXPECT_EQ("namespace aaaaaaaaaa {\n"
3647 "namespace bbbbbbbbbb {\n"
3648 "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3649 format("namespace aaaaaaaaaa {\n"
3650 "namespace bbbbbbbbbb {\n"
3651 "} // namespace bbbbbbbbbb\n"
3652 "} // namespace aaaaaaaaaa",
3653 Style));
3654
3655 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3656 "namespace cccccc {\n"
3657 "}}} // namespace aaaaaa::bbbbbb::cccccc",
3658 format("namespace aaaaaa {\n"
3659 "namespace bbbbbb {\n"
3660 "namespace cccccc {\n"
3661 "} // namespace cccccc\n"
3662 "} // namespace bbbbbb\n"
3663 "} // namespace aaaaaa",
3664 Style));
3665 Style.ColumnLimit = 80;
3666
3667 // Extra semicolon after 'inner' closing brace prevents merging
3668 EXPECT_EQ("namespace out { namespace in {\n"
3669 "}; } // namespace out::in",
3670 format("namespace out {\n"
3671 "namespace in {\n"
3672 "}; // namespace in\n"
3673 "} // namespace out",
3674 Style));
3675
3676 // Extra semicolon after 'outer' closing brace is conserved
3677 EXPECT_EQ("namespace out { namespace in {\n"
3678 "}}; // namespace out::in",
3679 format("namespace out {\n"
3680 "namespace in {\n"
3681 "} // namespace in\n"
3682 "}; // namespace out",
3683 Style));
3684
3685 Style.NamespaceIndentation = FormatStyle::NI_All;
3686 EXPECT_EQ("namespace out { namespace in {\n"
3687 " int i;\n"
3688 "}} // namespace out::in",
3689 format("namespace out {\n"
3690 "namespace in {\n"
3691 "int i;\n"
3692 "} // namespace in\n"
3693 "} // namespace out",
3694 Style));
3695 EXPECT_EQ("namespace out { namespace mid {\n"
3696 " namespace in {\n"
3697 " int j;\n"
3698 " } // namespace in\n"
3699 " int k;\n"
3700 "}} // namespace out::mid",
3701 format("namespace out { namespace mid {\n"
3702 "namespace in { int j; } // namespace in\n"
3703 "int k; }} // namespace out::mid",
3704 Style));
3705
3706 Style.NamespaceIndentation = FormatStyle::NI_Inner;
3707 EXPECT_EQ("namespace out { namespace in {\n"
3708 " int i;\n"
3709 "}} // namespace out::in",
3710 format("namespace out {\n"
3711 "namespace in {\n"
3712 "int i;\n"
3713 "} // namespace in\n"
3714 "} // namespace out",
3715 Style));
3716 EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3717 " int i;\n"
3718 "}}} // namespace out::mid::in",
3719 format("namespace out {\n"
3720 "namespace mid {\n"
3721 "namespace in {\n"
3722 "int i;\n"
3723 "} // namespace in\n"
3724 "} // namespace mid\n"
3725 "} // namespace out",
3726 Style));
3727 }
3728
TEST_F(FormatTest,FormatsExternC)3729 TEST_F(FormatTest, FormatsExternC) {
3730 verifyFormat("extern \"C\" {\nint a;");
3731 verifyFormat("extern \"C\" {}");
3732 verifyFormat("extern \"C\" {\n"
3733 "int foo();\n"
3734 "}");
3735 verifyFormat("extern \"C\" int foo() {}");
3736 verifyFormat("extern \"C\" int foo();");
3737 verifyFormat("extern \"C\" int foo() {\n"
3738 " int i = 42;\n"
3739 " return i;\n"
3740 "}");
3741
3742 FormatStyle Style = getLLVMStyle();
3743 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3744 Style.BraceWrapping.AfterFunction = true;
3745 verifyFormat("extern \"C\" int foo() {}", Style);
3746 verifyFormat("extern \"C\" int foo();", Style);
3747 verifyFormat("extern \"C\" int foo()\n"
3748 "{\n"
3749 " int i = 42;\n"
3750 " return i;\n"
3751 "}",
3752 Style);
3753
3754 Style.BraceWrapping.AfterExternBlock = true;
3755 Style.BraceWrapping.SplitEmptyRecord = false;
3756 verifyFormat("extern \"C\"\n"
3757 "{}",
3758 Style);
3759 verifyFormat("extern \"C\"\n"
3760 "{\n"
3761 " int foo();\n"
3762 "}",
3763 Style);
3764 }
3765
TEST_F(FormatTest,IndentExternBlockStyle)3766 TEST_F(FormatTest, IndentExternBlockStyle) {
3767 FormatStyle Style = getLLVMStyle();
3768 Style.IndentWidth = 2;
3769
3770 Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3771 verifyFormat("extern \"C\" { /*9*/\n}", Style);
3772 verifyFormat("extern \"C\" {\n"
3773 " int foo10();\n"
3774 "}",
3775 Style);
3776
3777 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3778 verifyFormat("extern \"C\" { /*11*/\n}", Style);
3779 verifyFormat("extern \"C\" {\n"
3780 "int foo12();\n"
3781 "}",
3782 Style);
3783
3784 Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3785 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3786 Style.BraceWrapping.AfterExternBlock = true;
3787 verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
3788 verifyFormat("extern \"C\"\n{\n"
3789 " int foo14();\n"
3790 "}",
3791 Style);
3792
3793 Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3794 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3795 Style.BraceWrapping.AfterExternBlock = false;
3796 verifyFormat("extern \"C\" { /*15*/\n}", Style);
3797 verifyFormat("extern \"C\" {\n"
3798 "int foo16();\n"
3799 "}",
3800 Style);
3801 }
3802
TEST_F(FormatTest,FormatsInlineASM)3803 TEST_F(FormatTest, FormatsInlineASM) {
3804 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
3805 verifyFormat("asm(\"nop\" ::: \"memory\");");
3806 verifyFormat(
3807 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
3808 " \"cpuid\\n\\t\"\n"
3809 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
3810 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
3811 " : \"a\"(value));");
3812 EXPECT_EQ(
3813 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
3814 " __asm {\n"
3815 " mov edx,[that] // vtable in edx\n"
3816 " mov eax,methodIndex\n"
3817 " call [edx][eax*4] // stdcall\n"
3818 " }\n"
3819 "}",
3820 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
3821 " __asm {\n"
3822 " mov edx,[that] // vtable in edx\n"
3823 " mov eax,methodIndex\n"
3824 " call [edx][eax*4] // stdcall\n"
3825 " }\n"
3826 "}"));
3827 EXPECT_EQ("_asm {\n"
3828 " xor eax, eax;\n"
3829 " cpuid;\n"
3830 "}",
3831 format("_asm {\n"
3832 " xor eax, eax;\n"
3833 " cpuid;\n"
3834 "}"));
3835 verifyFormat("void function() {\n"
3836 " // comment\n"
3837 " asm(\"\");\n"
3838 "}");
3839 EXPECT_EQ("__asm {\n"
3840 "}\n"
3841 "int i;",
3842 format("__asm {\n"
3843 "}\n"
3844 "int i;"));
3845 }
3846
TEST_F(FormatTest,FormatTryCatch)3847 TEST_F(FormatTest, FormatTryCatch) {
3848 verifyFormat("try {\n"
3849 " throw a * b;\n"
3850 "} catch (int a) {\n"
3851 " // Do nothing.\n"
3852 "} catch (...) {\n"
3853 " exit(42);\n"
3854 "}");
3855
3856 // Function-level try statements.
3857 verifyFormat("int f() try { return 4; } catch (...) {\n"
3858 " return 5;\n"
3859 "}");
3860 verifyFormat("class A {\n"
3861 " int a;\n"
3862 " A() try : a(0) {\n"
3863 " } catch (...) {\n"
3864 " throw;\n"
3865 " }\n"
3866 "};\n");
3867 verifyFormat("class A {\n"
3868 " int a;\n"
3869 " A() try : a(0), b{1} {\n"
3870 " } catch (...) {\n"
3871 " throw;\n"
3872 " }\n"
3873 "};\n");
3874 verifyFormat("class A {\n"
3875 " int a;\n"
3876 " A() try : a(0), b{1}, c{2} {\n"
3877 " } catch (...) {\n"
3878 " throw;\n"
3879 " }\n"
3880 "};\n");
3881 verifyFormat("class A {\n"
3882 " int a;\n"
3883 " A() try : a(0), b{1}, c{2} {\n"
3884 " { // New scope.\n"
3885 " }\n"
3886 " } catch (...) {\n"
3887 " throw;\n"
3888 " }\n"
3889 "};\n");
3890
3891 // Incomplete try-catch blocks.
3892 verifyIncompleteFormat("try {} catch (");
3893 }
3894
TEST_F(FormatTest,FormatTryAsAVariable)3895 TEST_F(FormatTest, FormatTryAsAVariable) {
3896 verifyFormat("int try;");
3897 verifyFormat("int try, size;");
3898 verifyFormat("try = foo();");
3899 verifyFormat("if (try < size) {\n return true;\n}");
3900
3901 verifyFormat("int catch;");
3902 verifyFormat("int catch, size;");
3903 verifyFormat("catch = foo();");
3904 verifyFormat("if (catch < size) {\n return true;\n}");
3905
3906 FormatStyle Style = getLLVMStyle();
3907 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3908 Style.BraceWrapping.AfterFunction = true;
3909 Style.BraceWrapping.BeforeCatch = true;
3910 verifyFormat("try {\n"
3911 " int bar = 1;\n"
3912 "}\n"
3913 "catch (...) {\n"
3914 " int bar = 1;\n"
3915 "}",
3916 Style);
3917 verifyFormat("#if NO_EX\n"
3918 "try\n"
3919 "#endif\n"
3920 "{\n"
3921 "}\n"
3922 "#if NO_EX\n"
3923 "catch (...) {\n"
3924 "}",
3925 Style);
3926 verifyFormat("try /* abc */ {\n"
3927 " int bar = 1;\n"
3928 "}\n"
3929 "catch (...) {\n"
3930 " int bar = 1;\n"
3931 "}",
3932 Style);
3933 verifyFormat("try\n"
3934 "// abc\n"
3935 "{\n"
3936 " int bar = 1;\n"
3937 "}\n"
3938 "catch (...) {\n"
3939 " int bar = 1;\n"
3940 "}",
3941 Style);
3942 }
3943
TEST_F(FormatTest,FormatSEHTryCatch)3944 TEST_F(FormatTest, FormatSEHTryCatch) {
3945 verifyFormat("__try {\n"
3946 " int a = b * c;\n"
3947 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
3948 " // Do nothing.\n"
3949 "}");
3950
3951 verifyFormat("__try {\n"
3952 " int a = b * c;\n"
3953 "} __finally {\n"
3954 " // Do nothing.\n"
3955 "}");
3956
3957 verifyFormat("DEBUG({\n"
3958 " __try {\n"
3959 " } __finally {\n"
3960 " }\n"
3961 "});\n");
3962 }
3963
TEST_F(FormatTest,IncompleteTryCatchBlocks)3964 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
3965 verifyFormat("try {\n"
3966 " f();\n"
3967 "} catch {\n"
3968 " g();\n"
3969 "}");
3970 verifyFormat("try {\n"
3971 " f();\n"
3972 "} catch (A a) MACRO(x) {\n"
3973 " g();\n"
3974 "} catch (B b) MACRO(x) {\n"
3975 " g();\n"
3976 "}");
3977 }
3978
TEST_F(FormatTest,FormatTryCatchBraceStyles)3979 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
3980 FormatStyle Style = getLLVMStyle();
3981 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
3982 FormatStyle::BS_WebKit}) {
3983 Style.BreakBeforeBraces = BraceStyle;
3984 verifyFormat("try {\n"
3985 " // something\n"
3986 "} catch (...) {\n"
3987 " // something\n"
3988 "}",
3989 Style);
3990 }
3991 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
3992 verifyFormat("try {\n"
3993 " // something\n"
3994 "}\n"
3995 "catch (...) {\n"
3996 " // something\n"
3997 "}",
3998 Style);
3999 verifyFormat("__try {\n"
4000 " // something\n"
4001 "}\n"
4002 "__finally {\n"
4003 " // something\n"
4004 "}",
4005 Style);
4006 verifyFormat("@try {\n"
4007 " // something\n"
4008 "}\n"
4009 "@finally {\n"
4010 " // something\n"
4011 "}",
4012 Style);
4013 Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4014 verifyFormat("try\n"
4015 "{\n"
4016 " // something\n"
4017 "}\n"
4018 "catch (...)\n"
4019 "{\n"
4020 " // something\n"
4021 "}",
4022 Style);
4023 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4024 verifyFormat("try\n"
4025 " {\n"
4026 " // something white\n"
4027 " }\n"
4028 "catch (...)\n"
4029 " {\n"
4030 " // something white\n"
4031 " }",
4032 Style);
4033 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4034 verifyFormat("try\n"
4035 " {\n"
4036 " // something\n"
4037 " }\n"
4038 "catch (...)\n"
4039 " {\n"
4040 " // something\n"
4041 " }",
4042 Style);
4043 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4044 Style.BraceWrapping.BeforeCatch = true;
4045 verifyFormat("try {\n"
4046 " // something\n"
4047 "}\n"
4048 "catch (...) {\n"
4049 " // something\n"
4050 "}",
4051 Style);
4052 }
4053
TEST_F(FormatTest,StaticInitializers)4054 TEST_F(FormatTest, StaticInitializers) {
4055 verifyFormat("static SomeClass SC = {1, 'a'};");
4056
4057 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4058 " 100000000, "
4059 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4060
4061 // Here, everything other than the "}" would fit on a line.
4062 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4063 " 10000000000000000000000000};");
4064 EXPECT_EQ("S s = {a,\n"
4065 "\n"
4066 " b};",
4067 format("S s = {\n"
4068 " a,\n"
4069 "\n"
4070 " b\n"
4071 "};"));
4072
4073 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4074 // line. However, the formatting looks a bit off and this probably doesn't
4075 // happen often in practice.
4076 verifyFormat("static int Variable[1] = {\n"
4077 " {1000000000000000000000000000000000000}};",
4078 getLLVMStyleWithColumns(40));
4079 }
4080
TEST_F(FormatTest,DesignatedInitializers)4081 TEST_F(FormatTest, DesignatedInitializers) {
4082 verifyFormat("const struct A a = {.a = 1, .b = 2};");
4083 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4084 " .bbbbbbbbbb = 2,\n"
4085 " .cccccccccc = 3,\n"
4086 " .dddddddddd = 4,\n"
4087 " .eeeeeeeeee = 5};");
4088 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4089 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4090 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4091 " .ccccccccccccccccccccccccccc = 3,\n"
4092 " .ddddddddddddddddddddddddddd = 4,\n"
4093 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4094
4095 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4096
4097 verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4098 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4099 " [2] = bbbbbbbbbb,\n"
4100 " [3] = cccccccccc,\n"
4101 " [4] = dddddddddd,\n"
4102 " [5] = eeeeeeeeee};");
4103 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4104 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4105 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4106 " [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4107 " [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4108 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4109 }
4110
TEST_F(FormatTest,NestedStaticInitializers)4111 TEST_F(FormatTest, NestedStaticInitializers) {
4112 verifyFormat("static A x = {{{}}};\n");
4113 verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4114 " {init1, init2, init3, init4}}};",
4115 getLLVMStyleWithColumns(50));
4116
4117 verifyFormat("somes Status::global_reps[3] = {\n"
4118 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4119 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4120 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4121 getLLVMStyleWithColumns(60));
4122 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4123 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4124 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4125 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4126 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4127 " {rect.fRight - rect.fLeft, rect.fBottom - "
4128 "rect.fTop}};");
4129
4130 verifyFormat(
4131 "SomeArrayOfSomeType a = {\n"
4132 " {{1, 2, 3},\n"
4133 " {1, 2, 3},\n"
4134 " {111111111111111111111111111111, 222222222222222222222222222222,\n"
4135 " 333333333333333333333333333333},\n"
4136 " {1, 2, 3},\n"
4137 " {1, 2, 3}}};");
4138 verifyFormat(
4139 "SomeArrayOfSomeType a = {\n"
4140 " {{1, 2, 3}},\n"
4141 " {{1, 2, 3}},\n"
4142 " {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4143 " 333333333333333333333333333333}},\n"
4144 " {{1, 2, 3}},\n"
4145 " {{1, 2, 3}}};");
4146
4147 verifyFormat("struct {\n"
4148 " unsigned bit;\n"
4149 " const char *const name;\n"
4150 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4151 " {kOsWin, \"Windows\"},\n"
4152 " {kOsLinux, \"Linux\"},\n"
4153 " {kOsCrOS, \"Chrome OS\"}};");
4154 verifyFormat("struct {\n"
4155 " unsigned bit;\n"
4156 " const char *const name;\n"
4157 "} kBitsToOs[] = {\n"
4158 " {kOsMac, \"Mac\"},\n"
4159 " {kOsWin, \"Windows\"},\n"
4160 " {kOsLinux, \"Linux\"},\n"
4161 " {kOsCrOS, \"Chrome OS\"},\n"
4162 "};");
4163 }
4164
TEST_F(FormatTest,FormatsSmallMacroDefinitionsInSingleLine)4165 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4166 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4167 " \\\n"
4168 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4169 }
4170
TEST_F(FormatTest,DoesNotBreakPureVirtualFunctionDefinition)4171 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4172 verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4173 " OwningPtr<FileOutputBuffer> &buffer) = 0;");
4174
4175 // Do break defaulted and deleted functions.
4176 verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4177 " default;",
4178 getLLVMStyleWithColumns(40));
4179 verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4180 " delete;",
4181 getLLVMStyleWithColumns(40));
4182 }
4183
TEST_F(FormatTest,BreaksStringLiteralsOnlyInDefine)4184 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4185 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4186 getLLVMStyleWithColumns(40));
4187 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4188 getLLVMStyleWithColumns(40));
4189 EXPECT_EQ("#define Q \\\n"
4190 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n"
4191 " \"aaaaaaaa.cpp\"",
4192 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4193 getLLVMStyleWithColumns(40)));
4194 }
4195
TEST_F(FormatTest,UnderstandsLinePPDirective)4196 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4197 EXPECT_EQ("# 123 \"A string literal\"",
4198 format(" # 123 \"A string literal\""));
4199 }
4200
TEST_F(FormatTest,LayoutUnknownPPDirective)4201 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4202 EXPECT_EQ("#;", format("#;"));
4203 verifyFormat("#\n;\n;\n;");
4204 }
4205
TEST_F(FormatTest,UnescapedEndOfLineEndsPPDirective)4206 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4207 EXPECT_EQ("#line 42 \"test\"\n",
4208 format("# \\\n line \\\n 42 \\\n \"test\"\n"));
4209 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n",
4210 getLLVMStyleWithColumns(12)));
4211 }
4212
TEST_F(FormatTest,EndOfFileEndsPPDirective)4213 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4214 EXPECT_EQ("#line 42 \"test\"",
4215 format("# \\\n line \\\n 42 \\\n \"test\""));
4216 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B"));
4217 }
4218
TEST_F(FormatTest,DoesntRemoveUnknownTokens)4219 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4220 verifyFormat("#define A \\x20");
4221 verifyFormat("#define A \\ x20");
4222 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20"));
4223 verifyFormat("#define A ''");
4224 verifyFormat("#define A ''qqq");
4225 verifyFormat("#define A `qqq");
4226 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4227 EXPECT_EQ("const char *c = STRINGIFY(\n"
4228 "\\na : b);",
4229 format("const char * c = STRINGIFY(\n"
4230 "\\na : b);"));
4231
4232 verifyFormat("a\r\\");
4233 verifyFormat("a\v\\");
4234 verifyFormat("a\f\\");
4235 }
4236
TEST_F(FormatTest,IndentsPPDirectiveWithPPIndentWidth)4237 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4238 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4239 style.IndentWidth = 4;
4240 style.PPIndentWidth = 1;
4241
4242 style.IndentPPDirectives = FormatStyle::PPDIS_None;
4243 verifyFormat("#ifdef __linux__\n"
4244 "void foo() {\n"
4245 " int x = 0;\n"
4246 "}\n"
4247 "#define FOO\n"
4248 "#endif\n"
4249 "void bar() {\n"
4250 " int y = 0;\n"
4251 "}\n",
4252 style);
4253
4254 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4255 verifyFormat("#ifdef __linux__\n"
4256 "void foo() {\n"
4257 " int x = 0;\n"
4258 "}\n"
4259 "# define FOO foo\n"
4260 "#endif\n"
4261 "void bar() {\n"
4262 " int y = 0;\n"
4263 "}\n",
4264 style);
4265
4266 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4267 verifyFormat("#ifdef __linux__\n"
4268 "void foo() {\n"
4269 " int x = 0;\n"
4270 "}\n"
4271 " #define FOO foo\n"
4272 "#endif\n"
4273 "void bar() {\n"
4274 " int y = 0;\n"
4275 "}\n",
4276 style);
4277 }
4278
TEST_F(FormatTest,IndentsPPDirectiveInReducedSpace)4279 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4280 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4281 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12));
4282 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12));
4283 // FIXME: We never break before the macro name.
4284 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12));
4285
4286 verifyFormat("#define A A\n#define A A");
4287 verifyFormat("#define A(X) A\n#define A A");
4288
4289 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4290 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22));
4291 }
4292
TEST_F(FormatTest,HandlePreprocessorDirectiveContext)4293 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4294 EXPECT_EQ("// somecomment\n"
4295 "#include \"a.h\"\n"
4296 "#define A( \\\n"
4297 " A, B)\n"
4298 "#include \"b.h\"\n"
4299 "// somecomment\n",
4300 format(" // somecomment\n"
4301 " #include \"a.h\"\n"
4302 "#define A(A,\\\n"
4303 " B)\n"
4304 " #include \"b.h\"\n"
4305 " // somecomment\n",
4306 getLLVMStyleWithColumns(13)));
4307 }
4308
TEST_F(FormatTest,LayoutSingleHash)4309 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4310
TEST_F(FormatTest,LayoutCodeInMacroDefinitions)4311 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4312 EXPECT_EQ("#define A \\\n"
4313 " c; \\\n"
4314 " e;\n"
4315 "f;",
4316 format("#define A c; e;\n"
4317 "f;",
4318 getLLVMStyleWithColumns(14)));
4319 }
4320
TEST_F(FormatTest,LayoutRemainingTokens)4321 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4322
TEST_F(FormatTest,MacroDefinitionInsideStatement)4323 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4324 EXPECT_EQ("int x,\n"
4325 "#define A\n"
4326 " y;",
4327 format("int x,\n#define A\ny;"));
4328 }
4329
TEST_F(FormatTest,HashInMacroDefinition)4330 TEST_F(FormatTest, HashInMacroDefinition) {
4331 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4332 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11));
4333 verifyFormat("#define A \\\n"
4334 " { \\\n"
4335 " f(#c); \\\n"
4336 " }",
4337 getLLVMStyleWithColumns(11));
4338
4339 verifyFormat("#define A(X) \\\n"
4340 " void function##X()",
4341 getLLVMStyleWithColumns(22));
4342
4343 verifyFormat("#define A(a, b, c) \\\n"
4344 " void a##b##c()",
4345 getLLVMStyleWithColumns(22));
4346
4347 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4348 }
4349
TEST_F(FormatTest,RespectWhitespaceInMacroDefinitions)4350 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4351 EXPECT_EQ("#define A (x)", format("#define A (x)"));
4352 EXPECT_EQ("#define A(x)", format("#define A(x)"));
4353
4354 FormatStyle Style = getLLVMStyle();
4355 Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4356 verifyFormat("#define true ((foo)1)", Style);
4357 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4358 verifyFormat("#define false((foo)0)", Style);
4359 }
4360
TEST_F(FormatTest,EmptyLinesInMacroDefinitions)4361 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4362 EXPECT_EQ("#define A b;", format("#define A \\\n"
4363 " \\\n"
4364 " b;",
4365 getLLVMStyleWithColumns(25)));
4366 EXPECT_EQ("#define A \\\n"
4367 " \\\n"
4368 " a; \\\n"
4369 " b;",
4370 format("#define A \\\n"
4371 " \\\n"
4372 " a; \\\n"
4373 " b;",
4374 getLLVMStyleWithColumns(11)));
4375 EXPECT_EQ("#define A \\\n"
4376 " a; \\\n"
4377 " \\\n"
4378 " b;",
4379 format("#define A \\\n"
4380 " a; \\\n"
4381 " \\\n"
4382 " b;",
4383 getLLVMStyleWithColumns(11)));
4384 }
4385
TEST_F(FormatTest,MacroDefinitionsWithIncompleteCode)4386 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4387 verifyIncompleteFormat("#define A :");
4388 verifyFormat("#define SOMECASES \\\n"
4389 " case 1: \\\n"
4390 " case 2\n",
4391 getLLVMStyleWithColumns(20));
4392 verifyFormat("#define MACRO(a) \\\n"
4393 " if (a) \\\n"
4394 " f(); \\\n"
4395 " else \\\n"
4396 " g()",
4397 getLLVMStyleWithColumns(18));
4398 verifyFormat("#define A template <typename T>");
4399 verifyIncompleteFormat("#define STR(x) #x\n"
4400 "f(STR(this_is_a_string_literal{));");
4401 verifyFormat("#pragma omp threadprivate( \\\n"
4402 " y)), // expected-warning",
4403 getLLVMStyleWithColumns(28));
4404 verifyFormat("#d, = };");
4405 verifyFormat("#if \"a");
4406 verifyIncompleteFormat("({\n"
4407 "#define b \\\n"
4408 " } \\\n"
4409 " a\n"
4410 "a",
4411 getLLVMStyleWithColumns(15));
4412 verifyFormat("#define A \\\n"
4413 " { \\\n"
4414 " {\n"
4415 "#define B \\\n"
4416 " } \\\n"
4417 " }",
4418 getLLVMStyleWithColumns(15));
4419 verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4420 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4421 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4422 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}");
4423 }
4424
TEST_F(FormatTest,MacrosWithoutTrailingSemicolon)4425 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4426 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4427 EXPECT_EQ("class A : public QObject {\n"
4428 " Q_OBJECT\n"
4429 "\n"
4430 " A() {}\n"
4431 "};",
4432 format("class A : public QObject {\n"
4433 " Q_OBJECT\n"
4434 "\n"
4435 " A() {\n}\n"
4436 "} ;"));
4437 EXPECT_EQ("MACRO\n"
4438 "/*static*/ int i;",
4439 format("MACRO\n"
4440 " /*static*/ int i;"));
4441 EXPECT_EQ("SOME_MACRO\n"
4442 "namespace {\n"
4443 "void f();\n"
4444 "} // namespace",
4445 format("SOME_MACRO\n"
4446 " namespace {\n"
4447 "void f( );\n"
4448 "} // namespace"));
4449 // Only if the identifier contains at least 5 characters.
4450 EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4451 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4452 // Only if everything is upper case.
4453 EXPECT_EQ("class A : public QObject {\n"
4454 " Q_Object A() {}\n"
4455 "};",
4456 format("class A : public QObject {\n"
4457 " Q_Object\n"
4458 " A() {\n}\n"
4459 "} ;"));
4460
4461 // Only if the next line can actually start an unwrapped line.
4462 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4463 format("SOME_WEIRD_LOG_MACRO\n"
4464 "<< SomeThing;"));
4465
4466 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4467 "(n, buffers))\n",
4468 getChromiumStyle(FormatStyle::LK_Cpp));
4469
4470 // See PR41483
4471 EXPECT_EQ("/**/ FOO(a)\n"
4472 "FOO(b)",
4473 format("/**/ FOO(a)\n"
4474 "FOO(b)"));
4475 }
4476
TEST_F(FormatTest,MacroCallsWithoutTrailingSemicolon)4477 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4478 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4479 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4480 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4481 "class X {};\n"
4482 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4483 "int *createScopDetectionPass() { return 0; }",
4484 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4485 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4486 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4487 " class X {};\n"
4488 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4489 " int *createScopDetectionPass() { return 0; }"));
4490 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4491 // braces, so that inner block is indented one level more.
4492 EXPECT_EQ("int q() {\n"
4493 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4494 " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4495 " IPC_END_MESSAGE_MAP()\n"
4496 "}",
4497 format("int q() {\n"
4498 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4499 " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4500 " IPC_END_MESSAGE_MAP()\n"
4501 "}"));
4502
4503 // Same inside macros.
4504 EXPECT_EQ("#define LIST(L) \\\n"
4505 " L(A) \\\n"
4506 " L(B) \\\n"
4507 " L(C)",
4508 format("#define LIST(L) \\\n"
4509 " L(A) \\\n"
4510 " L(B) \\\n"
4511 " L(C)",
4512 getGoogleStyle()));
4513
4514 // These must not be recognized as macros.
4515 EXPECT_EQ("int q() {\n"
4516 " f(x);\n"
4517 " f(x) {}\n"
4518 " f(x)->g();\n"
4519 " f(x)->*g();\n"
4520 " f(x).g();\n"
4521 " f(x) = x;\n"
4522 " f(x) += x;\n"
4523 " f(x) -= x;\n"
4524 " f(x) *= x;\n"
4525 " f(x) /= x;\n"
4526 " f(x) %= x;\n"
4527 " f(x) &= x;\n"
4528 " f(x) |= x;\n"
4529 " f(x) ^= x;\n"
4530 " f(x) >>= x;\n"
4531 " f(x) <<= x;\n"
4532 " f(x)[y].z();\n"
4533 " LOG(INFO) << x;\n"
4534 " ifstream(x) >> x;\n"
4535 "}\n",
4536 format("int q() {\n"
4537 " f(x)\n;\n"
4538 " f(x)\n {}\n"
4539 " f(x)\n->g();\n"
4540 " f(x)\n->*g();\n"
4541 " f(x)\n.g();\n"
4542 " f(x)\n = x;\n"
4543 " f(x)\n += x;\n"
4544 " f(x)\n -= x;\n"
4545 " f(x)\n *= x;\n"
4546 " f(x)\n /= x;\n"
4547 " f(x)\n %= x;\n"
4548 " f(x)\n &= x;\n"
4549 " f(x)\n |= x;\n"
4550 " f(x)\n ^= x;\n"
4551 " f(x)\n >>= x;\n"
4552 " f(x)\n <<= x;\n"
4553 " f(x)\n[y].z();\n"
4554 " LOG(INFO)\n << x;\n"
4555 " ifstream(x)\n >> x;\n"
4556 "}\n"));
4557 EXPECT_EQ("int q() {\n"
4558 " F(x)\n"
4559 " if (1) {\n"
4560 " }\n"
4561 " F(x)\n"
4562 " while (1) {\n"
4563 " }\n"
4564 " F(x)\n"
4565 " G(x);\n"
4566 " F(x)\n"
4567 " try {\n"
4568 " Q();\n"
4569 " } catch (...) {\n"
4570 " }\n"
4571 "}\n",
4572 format("int q() {\n"
4573 "F(x)\n"
4574 "if (1) {}\n"
4575 "F(x)\n"
4576 "while (1) {}\n"
4577 "F(x)\n"
4578 "G(x);\n"
4579 "F(x)\n"
4580 "try { Q(); } catch (...) {}\n"
4581 "}\n"));
4582 EXPECT_EQ("class A {\n"
4583 " A() : t(0) {}\n"
4584 " A(int i) noexcept() : {}\n"
4585 " A(X x)\n" // FIXME: function-level try blocks are broken.
4586 " try : t(0) {\n"
4587 " } catch (...) {\n"
4588 " }\n"
4589 "};",
4590 format("class A {\n"
4591 " A()\n : t(0) {}\n"
4592 " A(int i)\n noexcept() : {}\n"
4593 " A(X x)\n"
4594 " try : t(0) {} catch (...) {}\n"
4595 "};"));
4596 FormatStyle Style = getLLVMStyle();
4597 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4598 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4599 Style.BraceWrapping.AfterFunction = true;
4600 EXPECT_EQ("void f()\n"
4601 "try\n"
4602 "{\n"
4603 "}",
4604 format("void f() try {\n"
4605 "}",
4606 Style));
4607 EXPECT_EQ("class SomeClass {\n"
4608 "public:\n"
4609 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4610 "};",
4611 format("class SomeClass {\n"
4612 "public:\n"
4613 " SomeClass()\n"
4614 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4615 "};"));
4616 EXPECT_EQ("class SomeClass {\n"
4617 "public:\n"
4618 " SomeClass()\n"
4619 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4620 "};",
4621 format("class SomeClass {\n"
4622 "public:\n"
4623 " SomeClass()\n"
4624 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4625 "};",
4626 getLLVMStyleWithColumns(40)));
4627
4628 verifyFormat("MACRO(>)");
4629
4630 // Some macros contain an implicit semicolon.
4631 Style = getLLVMStyle();
4632 Style.StatementMacros.push_back("FOO");
4633 verifyFormat("FOO(a) int b = 0;");
4634 verifyFormat("FOO(a)\n"
4635 "int b = 0;",
4636 Style);
4637 verifyFormat("FOO(a);\n"
4638 "int b = 0;",
4639 Style);
4640 verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4641 "int b = 0;",
4642 Style);
4643 verifyFormat("FOO()\n"
4644 "int b = 0;",
4645 Style);
4646 verifyFormat("FOO\n"
4647 "int b = 0;",
4648 Style);
4649 verifyFormat("void f() {\n"
4650 " FOO(a)\n"
4651 " return a;\n"
4652 "}",
4653 Style);
4654 verifyFormat("FOO(a)\n"
4655 "FOO(b)",
4656 Style);
4657 verifyFormat("int a = 0;\n"
4658 "FOO(b)\n"
4659 "int c = 0;",
4660 Style);
4661 verifyFormat("int a = 0;\n"
4662 "int x = FOO(a)\n"
4663 "int b = 0;",
4664 Style);
4665 verifyFormat("void foo(int a) { FOO(a) }\n"
4666 "uint32_t bar() {}",
4667 Style);
4668 }
4669
TEST_F(FormatTest,LayoutMacroDefinitionsStatementsSpanningBlocks)4670 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
4671 verifyFormat("#define A \\\n"
4672 " f({ \\\n"
4673 " g(); \\\n"
4674 " });",
4675 getLLVMStyleWithColumns(11));
4676 }
4677
TEST_F(FormatTest,IndentPreprocessorDirectives)4678 TEST_F(FormatTest, IndentPreprocessorDirectives) {
4679 FormatStyle Style = getLLVMStyle();
4680 Style.IndentPPDirectives = FormatStyle::PPDIS_None;
4681 Style.ColumnLimit = 40;
4682 verifyFormat("#ifdef _WIN32\n"
4683 "#define A 0\n"
4684 "#ifdef VAR2\n"
4685 "#define B 1\n"
4686 "#include <someheader.h>\n"
4687 "#define MACRO \\\n"
4688 " some_very_long_func_aaaaaaaaaa();\n"
4689 "#endif\n"
4690 "#else\n"
4691 "#define A 1\n"
4692 "#endif",
4693 Style);
4694 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4695 verifyFormat("#ifdef _WIN32\n"
4696 "# define A 0\n"
4697 "# ifdef VAR2\n"
4698 "# define B 1\n"
4699 "# include <someheader.h>\n"
4700 "# define MACRO \\\n"
4701 " some_very_long_func_aaaaaaaaaa();\n"
4702 "# endif\n"
4703 "#else\n"
4704 "# define A 1\n"
4705 "#endif",
4706 Style);
4707 verifyFormat("#if A\n"
4708 "# define MACRO \\\n"
4709 " void a(int x) { \\\n"
4710 " b(); \\\n"
4711 " c(); \\\n"
4712 " d(); \\\n"
4713 " e(); \\\n"
4714 " f(); \\\n"
4715 " }\n"
4716 "#endif",
4717 Style);
4718 // Comments before include guard.
4719 verifyFormat("// file comment\n"
4720 "// file comment\n"
4721 "#ifndef HEADER_H\n"
4722 "#define HEADER_H\n"
4723 "code();\n"
4724 "#endif",
4725 Style);
4726 // Test with include guards.
4727 verifyFormat("#ifndef HEADER_H\n"
4728 "#define HEADER_H\n"
4729 "code();\n"
4730 "#endif",
4731 Style);
4732 // Include guards must have a #define with the same variable immediately
4733 // after #ifndef.
4734 verifyFormat("#ifndef NOT_GUARD\n"
4735 "# define FOO\n"
4736 "code();\n"
4737 "#endif",
4738 Style);
4739
4740 // Include guards must cover the entire file.
4741 verifyFormat("code();\n"
4742 "code();\n"
4743 "#ifndef NOT_GUARD\n"
4744 "# define NOT_GUARD\n"
4745 "code();\n"
4746 "#endif",
4747 Style);
4748 verifyFormat("#ifndef NOT_GUARD\n"
4749 "# define NOT_GUARD\n"
4750 "code();\n"
4751 "#endif\n"
4752 "code();",
4753 Style);
4754 // Test with trailing blank lines.
4755 verifyFormat("#ifndef HEADER_H\n"
4756 "#define HEADER_H\n"
4757 "code();\n"
4758 "#endif\n",
4759 Style);
4760 // Include guards don't have #else.
4761 verifyFormat("#ifndef NOT_GUARD\n"
4762 "# define NOT_GUARD\n"
4763 "code();\n"
4764 "#else\n"
4765 "#endif",
4766 Style);
4767 verifyFormat("#ifndef NOT_GUARD\n"
4768 "# define NOT_GUARD\n"
4769 "code();\n"
4770 "#elif FOO\n"
4771 "#endif",
4772 Style);
4773 // Non-identifier #define after potential include guard.
4774 verifyFormat("#ifndef FOO\n"
4775 "# define 1\n"
4776 "#endif\n",
4777 Style);
4778 // #if closes past last non-preprocessor line.
4779 verifyFormat("#ifndef FOO\n"
4780 "#define FOO\n"
4781 "#if 1\n"
4782 "int i;\n"
4783 "# define A 0\n"
4784 "#endif\n"
4785 "#endif\n",
4786 Style);
4787 // Don't crash if there is an #elif directive without a condition.
4788 verifyFormat("#if 1\n"
4789 "int x;\n"
4790 "#elif\n"
4791 "int y;\n"
4792 "#else\n"
4793 "int z;\n"
4794 "#endif",
4795 Style);
4796 // FIXME: This doesn't handle the case where there's code between the
4797 // #ifndef and #define but all other conditions hold. This is because when
4798 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
4799 // previous code line yet, so we can't detect it.
4800 EXPECT_EQ("#ifndef NOT_GUARD\n"
4801 "code();\n"
4802 "#define NOT_GUARD\n"
4803 "code();\n"
4804 "#endif",
4805 format("#ifndef NOT_GUARD\n"
4806 "code();\n"
4807 "# define NOT_GUARD\n"
4808 "code();\n"
4809 "#endif",
4810 Style));
4811 // FIXME: This doesn't handle cases where legitimate preprocessor lines may
4812 // be outside an include guard. Examples are #pragma once and
4813 // #pragma GCC diagnostic, or anything else that does not change the meaning
4814 // of the file if it's included multiple times.
4815 EXPECT_EQ("#ifdef WIN32\n"
4816 "# pragma once\n"
4817 "#endif\n"
4818 "#ifndef HEADER_H\n"
4819 "# define HEADER_H\n"
4820 "code();\n"
4821 "#endif",
4822 format("#ifdef WIN32\n"
4823 "# pragma once\n"
4824 "#endif\n"
4825 "#ifndef HEADER_H\n"
4826 "#define HEADER_H\n"
4827 "code();\n"
4828 "#endif",
4829 Style));
4830 // FIXME: This does not detect when there is a single non-preprocessor line
4831 // in front of an include-guard-like structure where other conditions hold
4832 // because ScopedLineState hides the line.
4833 EXPECT_EQ("code();\n"
4834 "#ifndef HEADER_H\n"
4835 "#define HEADER_H\n"
4836 "code();\n"
4837 "#endif",
4838 format("code();\n"
4839 "#ifndef HEADER_H\n"
4840 "# define HEADER_H\n"
4841 "code();\n"
4842 "#endif",
4843 Style));
4844 // Keep comments aligned with #, otherwise indent comments normally. These
4845 // tests cannot use verifyFormat because messUp manipulates leading
4846 // whitespace.
4847 {
4848 const char *Expected = ""
4849 "void f() {\n"
4850 "#if 1\n"
4851 "// Preprocessor aligned.\n"
4852 "# define A 0\n"
4853 " // Code. Separated by blank line.\n"
4854 "\n"
4855 "# define B 0\n"
4856 " // Code. Not aligned with #\n"
4857 "# define C 0\n"
4858 "#endif";
4859 const char *ToFormat = ""
4860 "void f() {\n"
4861 "#if 1\n"
4862 "// Preprocessor aligned.\n"
4863 "# define A 0\n"
4864 "// Code. Separated by blank line.\n"
4865 "\n"
4866 "# define B 0\n"
4867 " // Code. Not aligned with #\n"
4868 "# define C 0\n"
4869 "#endif";
4870 EXPECT_EQ(Expected, format(ToFormat, Style));
4871 EXPECT_EQ(Expected, format(Expected, Style));
4872 }
4873 // Keep block quotes aligned.
4874 {
4875 const char *Expected = ""
4876 "void f() {\n"
4877 "#if 1\n"
4878 "/* Preprocessor aligned. */\n"
4879 "# define A 0\n"
4880 " /* Code. Separated by blank line. */\n"
4881 "\n"
4882 "# define B 0\n"
4883 " /* Code. Not aligned with # */\n"
4884 "# define C 0\n"
4885 "#endif";
4886 const char *ToFormat = ""
4887 "void f() {\n"
4888 "#if 1\n"
4889 "/* Preprocessor aligned. */\n"
4890 "# define A 0\n"
4891 "/* Code. Separated by blank line. */\n"
4892 "\n"
4893 "# define B 0\n"
4894 " /* Code. Not aligned with # */\n"
4895 "# define C 0\n"
4896 "#endif";
4897 EXPECT_EQ(Expected, format(ToFormat, Style));
4898 EXPECT_EQ(Expected, format(Expected, Style));
4899 }
4900 // Keep comments aligned with un-indented directives.
4901 {
4902 const char *Expected = ""
4903 "void f() {\n"
4904 "// Preprocessor aligned.\n"
4905 "#define A 0\n"
4906 " // Code. Separated by blank line.\n"
4907 "\n"
4908 "#define B 0\n"
4909 " // Code. Not aligned with #\n"
4910 "#define C 0\n";
4911 const char *ToFormat = ""
4912 "void f() {\n"
4913 "// Preprocessor aligned.\n"
4914 "#define A 0\n"
4915 "// Code. Separated by blank line.\n"
4916 "\n"
4917 "#define B 0\n"
4918 " // Code. Not aligned with #\n"
4919 "#define C 0\n";
4920 EXPECT_EQ(Expected, format(ToFormat, Style));
4921 EXPECT_EQ(Expected, format(Expected, Style));
4922 }
4923 // Test AfterHash with tabs.
4924 {
4925 FormatStyle Tabbed = Style;
4926 Tabbed.UseTab = FormatStyle::UT_Always;
4927 Tabbed.IndentWidth = 8;
4928 Tabbed.TabWidth = 8;
4929 verifyFormat("#ifdef _WIN32\n"
4930 "#\tdefine A 0\n"
4931 "#\tifdef VAR2\n"
4932 "#\t\tdefine B 1\n"
4933 "#\t\tinclude <someheader.h>\n"
4934 "#\t\tdefine MACRO \\\n"
4935 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
4936 "#\tendif\n"
4937 "#else\n"
4938 "#\tdefine A 1\n"
4939 "#endif",
4940 Tabbed);
4941 }
4942
4943 // Regression test: Multiline-macro inside include guards.
4944 verifyFormat("#ifndef HEADER_H\n"
4945 "#define HEADER_H\n"
4946 "#define A() \\\n"
4947 " int i; \\\n"
4948 " int j;\n"
4949 "#endif // HEADER_H",
4950 getLLVMStyleWithColumns(20));
4951
4952 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4953 // Basic before hash indent tests
4954 verifyFormat("#ifdef _WIN32\n"
4955 " #define A 0\n"
4956 " #ifdef VAR2\n"
4957 " #define B 1\n"
4958 " #include <someheader.h>\n"
4959 " #define MACRO \\\n"
4960 " some_very_long_func_aaaaaaaaaa();\n"
4961 " #endif\n"
4962 "#else\n"
4963 " #define A 1\n"
4964 "#endif",
4965 Style);
4966 verifyFormat("#if A\n"
4967 " #define MACRO \\\n"
4968 " void a(int x) { \\\n"
4969 " b(); \\\n"
4970 " c(); \\\n"
4971 " d(); \\\n"
4972 " e(); \\\n"
4973 " f(); \\\n"
4974 " }\n"
4975 "#endif",
4976 Style);
4977 // Keep comments aligned with indented directives. These
4978 // tests cannot use verifyFormat because messUp manipulates leading
4979 // whitespace.
4980 {
4981 const char *Expected = "void f() {\n"
4982 "// Aligned to preprocessor.\n"
4983 "#if 1\n"
4984 " // Aligned to code.\n"
4985 " int a;\n"
4986 " #if 1\n"
4987 " // Aligned to preprocessor.\n"
4988 " #define A 0\n"
4989 " // Aligned to code.\n"
4990 " int b;\n"
4991 " #endif\n"
4992 "#endif\n"
4993 "}";
4994 const char *ToFormat = "void f() {\n"
4995 "// Aligned to preprocessor.\n"
4996 "#if 1\n"
4997 "// Aligned to code.\n"
4998 "int a;\n"
4999 "#if 1\n"
5000 "// Aligned to preprocessor.\n"
5001 "#define A 0\n"
5002 "// Aligned to code.\n"
5003 "int b;\n"
5004 "#endif\n"
5005 "#endif\n"
5006 "}";
5007 EXPECT_EQ(Expected, format(ToFormat, Style));
5008 EXPECT_EQ(Expected, format(Expected, Style));
5009 }
5010 {
5011 const char *Expected = "void f() {\n"
5012 "/* Aligned to preprocessor. */\n"
5013 "#if 1\n"
5014 " /* Aligned to code. */\n"
5015 " int a;\n"
5016 " #if 1\n"
5017 " /* Aligned to preprocessor. */\n"
5018 " #define A 0\n"
5019 " /* Aligned to code. */\n"
5020 " int b;\n"
5021 " #endif\n"
5022 "#endif\n"
5023 "}";
5024 const char *ToFormat = "void f() {\n"
5025 "/* Aligned to preprocessor. */\n"
5026 "#if 1\n"
5027 "/* Aligned to code. */\n"
5028 "int a;\n"
5029 "#if 1\n"
5030 "/* Aligned to preprocessor. */\n"
5031 "#define A 0\n"
5032 "/* Aligned to code. */\n"
5033 "int b;\n"
5034 "#endif\n"
5035 "#endif\n"
5036 "}";
5037 EXPECT_EQ(Expected, format(ToFormat, Style));
5038 EXPECT_EQ(Expected, format(Expected, Style));
5039 }
5040
5041 // Test single comment before preprocessor
5042 verifyFormat("// Comment\n"
5043 "\n"
5044 "#if 1\n"
5045 "#endif",
5046 Style);
5047 }
5048
TEST_F(FormatTest,FormatHashIfNotAtStartOfLine)5049 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5050 verifyFormat("{\n { a #c; }\n}");
5051 }
5052
TEST_F(FormatTest,FormatUnbalancedStructuralElements)5053 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5054 EXPECT_EQ("#define A \\\n { \\\n {\nint i;",
5055 format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5056 EXPECT_EQ("#define A \\\n } \\\n }\nint i;",
5057 format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5058 }
5059
TEST_F(FormatTest,EscapedNewlines)5060 TEST_F(FormatTest, EscapedNewlines) {
5061 FormatStyle Narrow = getLLVMStyleWithColumns(11);
5062 EXPECT_EQ("#define A \\\n int i; \\\n int j;",
5063 format("#define A \\\nint i;\\\n int j;", Narrow));
5064 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5065 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5066 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */"));
5067 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5068
5069 FormatStyle AlignLeft = getLLVMStyle();
5070 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5071 EXPECT_EQ("#define MACRO(x) \\\n"
5072 "private: \\\n"
5073 " int x(int a);\n",
5074 format("#define MACRO(x) \\\n"
5075 "private: \\\n"
5076 " int x(int a);\n",
5077 AlignLeft));
5078
5079 // CRLF line endings
5080 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;",
5081 format("#define A \\\r\nint i;\\\r\n int j;", Narrow));
5082 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5083 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5084 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */"));
5085 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5086 EXPECT_EQ("#define MACRO(x) \\\r\n"
5087 "private: \\\r\n"
5088 " int x(int a);\r\n",
5089 format("#define MACRO(x) \\\r\n"
5090 "private: \\\r\n"
5091 " int x(int a);\r\n",
5092 AlignLeft));
5093
5094 FormatStyle DontAlign = getLLVMStyle();
5095 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5096 DontAlign.MaxEmptyLinesToKeep = 3;
5097 // FIXME: can't use verifyFormat here because the newline before
5098 // "public:" is not inserted the first time it's reformatted
5099 EXPECT_EQ("#define A \\\n"
5100 " class Foo { \\\n"
5101 " void bar(); \\\n"
5102 "\\\n"
5103 "\\\n"
5104 "\\\n"
5105 " public: \\\n"
5106 " void baz(); \\\n"
5107 " };",
5108 format("#define A \\\n"
5109 " class Foo { \\\n"
5110 " void bar(); \\\n"
5111 "\\\n"
5112 "\\\n"
5113 "\\\n"
5114 " public: \\\n"
5115 " void baz(); \\\n"
5116 " };",
5117 DontAlign));
5118 }
5119
TEST_F(FormatTest,CalculateSpaceOnConsecutiveLinesInMacro)5120 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5121 verifyFormat("#define A \\\n"
5122 " int v( \\\n"
5123 " a); \\\n"
5124 " int i;",
5125 getLLVMStyleWithColumns(11));
5126 }
5127
TEST_F(FormatTest,MixingPreprocessorDirectivesAndNormalCode)5128 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5129 EXPECT_EQ(
5130 "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5131 " \\\n"
5132 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5133 "\n"
5134 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5135 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5136 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro("
5137 "\\\n"
5138 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5139 " \n"
5140 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5141 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5142 }
5143
TEST_F(FormatTest,LayoutStatementsAroundPreprocessorDirectives)5144 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5145 EXPECT_EQ("int\n"
5146 "#define A\n"
5147 " a;",
5148 format("int\n#define A\na;"));
5149 verifyFormat("functionCallTo(\n"
5150 " someOtherFunction(\n"
5151 " withSomeParameters, whichInSequence,\n"
5152 " areLongerThanALine(andAnotherCall,\n"
5153 "#define A B\n"
5154 " withMoreParamters,\n"
5155 " whichStronglyInfluenceTheLayout),\n"
5156 " andMoreParameters),\n"
5157 " trailing);",
5158 getLLVMStyleWithColumns(69));
5159 verifyFormat("Foo::Foo()\n"
5160 "#ifdef BAR\n"
5161 " : baz(0)\n"
5162 "#endif\n"
5163 "{\n"
5164 "}");
5165 verifyFormat("void f() {\n"
5166 " if (true)\n"
5167 "#ifdef A\n"
5168 " f(42);\n"
5169 " x();\n"
5170 "#else\n"
5171 " g();\n"
5172 " x();\n"
5173 "#endif\n"
5174 "}");
5175 verifyFormat("void f(param1, param2,\n"
5176 " param3,\n"
5177 "#ifdef A\n"
5178 " param4(param5,\n"
5179 "#ifdef A1\n"
5180 " param6,\n"
5181 "#ifdef A2\n"
5182 " param7),\n"
5183 "#else\n"
5184 " param8),\n"
5185 " param9,\n"
5186 "#endif\n"
5187 " param10,\n"
5188 "#endif\n"
5189 " param11)\n"
5190 "#else\n"
5191 " param12)\n"
5192 "#endif\n"
5193 "{\n"
5194 " x();\n"
5195 "}",
5196 getLLVMStyleWithColumns(28));
5197 verifyFormat("#if 1\n"
5198 "int i;");
5199 verifyFormat("#if 1\n"
5200 "#endif\n"
5201 "#if 1\n"
5202 "#else\n"
5203 "#endif\n");
5204 verifyFormat("DEBUG({\n"
5205 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5207 "});\n"
5208 "#if a\n"
5209 "#else\n"
5210 "#endif");
5211
5212 verifyIncompleteFormat("void f(\n"
5213 "#if A\n"
5214 ");\n"
5215 "#else\n"
5216 "#endif");
5217 }
5218
TEST_F(FormatTest,GraciouslyHandleIncorrectPreprocessorConditions)5219 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5220 verifyFormat("#endif\n"
5221 "#if B");
5222 }
5223
TEST_F(FormatTest,FormatsJoinedLinesOnSubsequentRuns)5224 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5225 FormatStyle SingleLine = getLLVMStyle();
5226 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5227 verifyFormat("#if 0\n"
5228 "#elif 1\n"
5229 "#endif\n"
5230 "void foo() {\n"
5231 " if (test) foo2();\n"
5232 "}",
5233 SingleLine);
5234 }
5235
TEST_F(FormatTest,LayoutBlockInsideParens)5236 TEST_F(FormatTest, LayoutBlockInsideParens) {
5237 verifyFormat("functionCall({ int i; });");
5238 verifyFormat("functionCall({\n"
5239 " int i;\n"
5240 " int j;\n"
5241 "});");
5242 verifyFormat("functionCall(\n"
5243 " {\n"
5244 " int i;\n"
5245 " int j;\n"
5246 " },\n"
5247 " aaaa, bbbb, cccc);");
5248 verifyFormat("functionA(functionB({\n"
5249 " int i;\n"
5250 " int j;\n"
5251 " }),\n"
5252 " aaaa, bbbb, cccc);");
5253 verifyFormat("functionCall(\n"
5254 " {\n"
5255 " int i;\n"
5256 " int j;\n"
5257 " },\n"
5258 " aaaa, bbbb, // comment\n"
5259 " cccc);");
5260 verifyFormat("functionA(functionB({\n"
5261 " int i;\n"
5262 " int j;\n"
5263 " }),\n"
5264 " aaaa, bbbb, // comment\n"
5265 " cccc);");
5266 verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5267 verifyFormat("functionCall(aaaa, bbbb, {\n"
5268 " int i;\n"
5269 " int j;\n"
5270 "});");
5271 verifyFormat(
5272 "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5273 " {\n"
5274 " int i; // break\n"
5275 " },\n"
5276 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5277 " ccccccccccccccccc));");
5278 verifyFormat("DEBUG({\n"
5279 " if (a)\n"
5280 " f();\n"
5281 "});");
5282 }
5283
TEST_F(FormatTest,LayoutBlockInsideStatement)5284 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5285 EXPECT_EQ("SOME_MACRO { int i; }\n"
5286 "int i;",
5287 format(" SOME_MACRO {int i;} int i;"));
5288 }
5289
TEST_F(FormatTest,LayoutNestedBlocks)5290 TEST_F(FormatTest, LayoutNestedBlocks) {
5291 verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5292 " struct s {\n"
5293 " int i;\n"
5294 " };\n"
5295 " s kBitsToOs[] = {{10}};\n"
5296 " for (int i = 0; i < 10; ++i)\n"
5297 " return;\n"
5298 "}");
5299 verifyFormat("call(parameter, {\n"
5300 " something();\n"
5301 " // Comment using all columns.\n"
5302 " somethingelse();\n"
5303 "});",
5304 getLLVMStyleWithColumns(40));
5305 verifyFormat("DEBUG( //\n"
5306 " { f(); }, a);");
5307 verifyFormat("DEBUG( //\n"
5308 " {\n"
5309 " f(); //\n"
5310 " },\n"
5311 " a);");
5312
5313 EXPECT_EQ("call(parameter, {\n"
5314 " something();\n"
5315 " // Comment too\n"
5316 " // looooooooooong.\n"
5317 " somethingElse();\n"
5318 "});",
5319 format("call(parameter, {\n"
5320 " something();\n"
5321 " // Comment too looooooooooong.\n"
5322 " somethingElse();\n"
5323 "});",
5324 getLLVMStyleWithColumns(29)));
5325 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });"));
5326 EXPECT_EQ("DEBUG({ // comment\n"
5327 " int i;\n"
5328 "});",
5329 format("DEBUG({ // comment\n"
5330 "int i;\n"
5331 "});"));
5332 EXPECT_EQ("DEBUG({\n"
5333 " int i;\n"
5334 "\n"
5335 " // comment\n"
5336 " int j;\n"
5337 "});",
5338 format("DEBUG({\n"
5339 " int i;\n"
5340 "\n"
5341 " // comment\n"
5342 " int j;\n"
5343 "});"));
5344
5345 verifyFormat("DEBUG({\n"
5346 " if (a)\n"
5347 " return;\n"
5348 "});");
5349 verifyGoogleFormat("DEBUG({\n"
5350 " if (a) return;\n"
5351 "});");
5352 FormatStyle Style = getGoogleStyle();
5353 Style.ColumnLimit = 45;
5354 verifyFormat("Debug(\n"
5355 " aaaaa,\n"
5356 " {\n"
5357 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5358 " },\n"
5359 " a);",
5360 Style);
5361
5362 verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5363
5364 verifyNoCrash("^{v^{a}}");
5365 }
5366
TEST_F(FormatTest,FormatNestedBlocksInMacros)5367 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5368 EXPECT_EQ("#define MACRO() \\\n"
5369 " Debug(aaa, /* force line break */ \\\n"
5370 " { \\\n"
5371 " int i; \\\n"
5372 " int j; \\\n"
5373 " })",
5374 format("#define MACRO() Debug(aaa, /* force line break */ \\\n"
5375 " { int i; int j; })",
5376 getGoogleStyle()));
5377
5378 EXPECT_EQ("#define A \\\n"
5379 " [] { \\\n"
5380 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5381 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5382 " }",
5383 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5384 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5385 getGoogleStyle()));
5386 }
5387
TEST_F(FormatTest,PutEmptyBlocksIntoOneLine)5388 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5389 EXPECT_EQ("{}", format("{}"));
5390 verifyFormat("enum E {};");
5391 verifyFormat("enum E {}");
5392 FormatStyle Style = getLLVMStyle();
5393 Style.SpaceInEmptyBlock = true;
5394 EXPECT_EQ("void f() { }", format("void f() {}", Style));
5395 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5396 EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5397 }
5398
TEST_F(FormatTest,FormatBeginBlockEndMacros)5399 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5400 FormatStyle Style = getLLVMStyle();
5401 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5402 Style.MacroBlockEnd = "^[A-Z_]+_END$";
5403 verifyFormat("FOO_BEGIN\n"
5404 " FOO_ENTRY\n"
5405 "FOO_END",
5406 Style);
5407 verifyFormat("FOO_BEGIN\n"
5408 " NESTED_FOO_BEGIN\n"
5409 " NESTED_FOO_ENTRY\n"
5410 " NESTED_FOO_END\n"
5411 "FOO_END",
5412 Style);
5413 verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5414 " int x;\n"
5415 " x = 1;\n"
5416 "FOO_END(Baz)",
5417 Style);
5418 }
5419
5420 //===----------------------------------------------------------------------===//
5421 // Line break tests.
5422 //===----------------------------------------------------------------------===//
5423
TEST_F(FormatTest,PreventConfusingIndents)5424 TEST_F(FormatTest, PreventConfusingIndents) {
5425 verifyFormat(
5426 "void f() {\n"
5427 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5428 " parameter, parameter, parameter)),\n"
5429 " SecondLongCall(parameter));\n"
5430 "}");
5431 verifyFormat(
5432 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5433 " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5434 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5435 " aaaaaaaaaaaaaaaaaaaaaaaa);");
5436 verifyFormat(
5437 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5438 " [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5439 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5440 " [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5441 verifyFormat(
5442 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5443 " aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5444 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5445 " aaaaaaaaaaaaaaaaaaaaaaaa>;");
5446 verifyFormat("int a = bbbb && ccc &&\n"
5447 " fffff(\n"
5448 "#define A Just forcing a new line\n"
5449 " ddd);");
5450 }
5451
TEST_F(FormatTest,LineBreakingInBinaryExpressions)5452 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5453 verifyFormat(
5454 "bool aaaaaaa =\n"
5455 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5456 " bbbbbbbb();");
5457 verifyFormat(
5458 "bool aaaaaaa =\n"
5459 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5460 " bbbbbbbb();");
5461
5462 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5464 " ccccccccc == ddddddddddd;");
5465 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5466 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5467 " ccccccccc == ddddddddddd;");
5468 verifyFormat(
5469 "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5470 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5471 " ccccccccc == ddddddddddd;");
5472
5473 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5474 " aaaaaa) &&\n"
5475 " bbbbbb && cccccc;");
5476 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5477 " aaaaaa) >>\n"
5478 " bbbbbb;");
5479 verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5480 " SourceMgr.getSpellingColumnNumber(\n"
5481 " TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5482 " 1);");
5483
5484 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5485 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5486 " cccccc) {\n}");
5487 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5488 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5489 " cccccc) {\n}");
5490 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5491 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5492 " cccccc) {\n}");
5493 verifyFormat("b = a &&\n"
5494 " // Comment\n"
5495 " b.c && d;");
5496
5497 // If the LHS of a comparison is not a binary expression itself, the
5498 // additional linebreak confuses many people.
5499 verifyFormat(
5500 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5501 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5502 "}");
5503 verifyFormat(
5504 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5505 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5506 "}");
5507 verifyFormat(
5508 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5509 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5510 "}");
5511 verifyFormat(
5512 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5513 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5514 "}");
5515 // Even explicit parentheses stress the precedence enough to make the
5516 // additional break unnecessary.
5517 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5518 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5519 "}");
5520 // This cases is borderline, but with the indentation it is still readable.
5521 verifyFormat(
5522 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5523 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5524 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5525 "}",
5526 getLLVMStyleWithColumns(75));
5527
5528 // If the LHS is a binary expression, we should still use the additional break
5529 // as otherwise the formatting hides the operator precedence.
5530 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5531 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5532 " 5) {\n"
5533 "}");
5534 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5535 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5536 " 5) {\n"
5537 "}");
5538
5539 FormatStyle OnePerLine = getLLVMStyle();
5540 OnePerLine.BinPackParameters = false;
5541 verifyFormat(
5542 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5543 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5544 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5545 OnePerLine);
5546
5547 verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5548 " .aaa(aaaaaaaaaaaaa) *\n"
5549 " aaaaaaa +\n"
5550 " aaaaaaa;",
5551 getLLVMStyleWithColumns(40));
5552 }
5553
TEST_F(FormatTest,ExpressionIndentation)5554 TEST_F(FormatTest, ExpressionIndentation) {
5555 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5556 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5557 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5558 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5559 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5560 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5561 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5562 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5563 " ccccccccccccccccccccccccccccccccccccccccc;");
5564 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5565 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5566 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5567 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5568 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5569 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5570 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5571 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5572 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5573 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5574 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5575 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5576 verifyFormat("if () {\n"
5577 "} else if (aaaaa && bbbbb > // break\n"
5578 " ccccc) {\n"
5579 "}");
5580 verifyFormat("if () {\n"
5581 "} else if constexpr (aaaaa && bbbbb > // break\n"
5582 " ccccc) {\n"
5583 "}");
5584 verifyFormat("if () {\n"
5585 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
5586 " ccccc) {\n"
5587 "}");
5588 verifyFormat("if () {\n"
5589 "} else if (aaaaa &&\n"
5590 " bbbbb > // break\n"
5591 " ccccc &&\n"
5592 " ddddd) {\n"
5593 "}");
5594
5595 // Presence of a trailing comment used to change indentation of b.
5596 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5597 " b;\n"
5598 "return aaaaaaaaaaaaaaaaaaa +\n"
5599 " b; //",
5600 getLLVMStyleWithColumns(30));
5601 }
5602
TEST_F(FormatTest,ExpressionIndentationBreakingBeforeOperators)5603 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5604 // Not sure what the best system is here. Like this, the LHS can be found
5605 // immediately above an operator (everything with the same or a higher
5606 // indent). The RHS is aligned right of the operator and so compasses
5607 // everything until something with the same indent as the operator is found.
5608 // FIXME: Is this a good system?
5609 FormatStyle Style = getLLVMStyle();
5610 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5611 verifyFormat(
5612 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5613 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5614 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5615 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5616 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5617 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5618 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5619 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5620 " > ccccccccccccccccccccccccccccccccccccccccc;",
5621 Style);
5622 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5623 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5624 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5625 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5626 Style);
5627 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5628 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5629 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5630 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5631 Style);
5632 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5633 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5634 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5635 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5636 Style);
5637 verifyFormat("if () {\n"
5638 "} else if (aaaaa\n"
5639 " && bbbbb // break\n"
5640 " > ccccc) {\n"
5641 "}",
5642 Style);
5643 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5644 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5645 Style);
5646 verifyFormat("return (a)\n"
5647 " // comment\n"
5648 " + b;",
5649 Style);
5650 verifyFormat(
5651 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5652 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5653 " + cc;",
5654 Style);
5655
5656 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5657 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5658 Style);
5659
5660 // Forced by comments.
5661 verifyFormat(
5662 "unsigned ContentSize =\n"
5663 " sizeof(int16_t) // DWARF ARange version number\n"
5664 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5665 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
5666 " + sizeof(int8_t); // Segment Size (in bytes)");
5667
5668 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5669 " == boost::fusion::at_c<1>(iiii).second;",
5670 Style);
5671
5672 Style.ColumnLimit = 60;
5673 verifyFormat("zzzzzzzzzz\n"
5674 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5675 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5676 Style);
5677
5678 Style.ColumnLimit = 80;
5679 Style.IndentWidth = 4;
5680 Style.TabWidth = 4;
5681 Style.UseTab = FormatStyle::UT_Always;
5682 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5683 Style.AlignOperands = FormatStyle::OAS_DontAlign;
5684 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
5685 "\t&& (someOtherLongishConditionPart1\n"
5686 "\t\t|| someOtherEvenLongerNestedConditionPart2);",
5687 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
5688 "(someOtherLongishConditionPart1 || "
5689 "someOtherEvenLongerNestedConditionPart2);",
5690 Style));
5691 }
5692
TEST_F(FormatTest,ExpressionIndentationStrictAlign)5693 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
5694 FormatStyle Style = getLLVMStyle();
5695 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5696 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
5697
5698 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5699 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5700 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5701 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5702 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5703 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5704 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5705 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5706 " > ccccccccccccccccccccccccccccccccccccccccc;",
5707 Style);
5708 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5709 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5710 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5711 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5712 Style);
5713 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5714 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5715 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5716 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5717 Style);
5718 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5719 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5720 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5721 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5722 Style);
5723 verifyFormat("if () {\n"
5724 "} else if (aaaaa\n"
5725 " && bbbbb // break\n"
5726 " > ccccc) {\n"
5727 "}",
5728 Style);
5729 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5730 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5731 Style);
5732 verifyFormat("return (a)\n"
5733 " // comment\n"
5734 " + b;",
5735 Style);
5736 verifyFormat(
5737 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5738 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5739 " + cc;",
5740 Style);
5741 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
5742 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5743 " : 3333333333333333;",
5744 Style);
5745 verifyFormat(
5746 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
5747 " : ccccccccccccccc ? dddddddddddddddddd\n"
5748 " : eeeeeeeeeeeeeeeeee)\n"
5749 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5750 " : 3333333333333333;",
5751 Style);
5752 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5753 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5754 Style);
5755
5756 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5757 " == boost::fusion::at_c<1>(iiii).second;",
5758 Style);
5759
5760 Style.ColumnLimit = 60;
5761 verifyFormat("zzzzzzzzzzzzz\n"
5762 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5763 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5764 Style);
5765
5766 // Forced by comments.
5767 Style.ColumnLimit = 80;
5768 verifyFormat(
5769 "unsigned ContentSize\n"
5770 " = sizeof(int16_t) // DWARF ARange version number\n"
5771 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5772 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
5773 " + sizeof(int8_t); // Segment Size (in bytes)",
5774 Style);
5775
5776 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5777 verifyFormat(
5778 "unsigned ContentSize =\n"
5779 " sizeof(int16_t) // DWARF ARange version number\n"
5780 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5781 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
5782 " + sizeof(int8_t); // Segment Size (in bytes)",
5783 Style);
5784
5785 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5786 verifyFormat(
5787 "unsigned ContentSize =\n"
5788 " sizeof(int16_t) // DWARF ARange version number\n"
5789 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5790 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
5791 " + sizeof(int8_t); // Segment Size (in bytes)",
5792 Style);
5793 }
5794
TEST_F(FormatTest,EnforcedOperatorWraps)5795 TEST_F(FormatTest, EnforcedOperatorWraps) {
5796 // Here we'd like to wrap after the || operators, but a comment is forcing an
5797 // earlier wrap.
5798 verifyFormat("bool x = aaaaa //\n"
5799 " || bbbbb\n"
5800 " //\n"
5801 " || cccc;");
5802 }
5803
TEST_F(FormatTest,NoOperandAlignment)5804 TEST_F(FormatTest, NoOperandAlignment) {
5805 FormatStyle Style = getLLVMStyle();
5806 Style.AlignOperands = FormatStyle::OAS_DontAlign;
5807 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
5808 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5809 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5810 Style);
5811 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5812 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5813 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5814 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5815 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5816 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5817 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5818 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5819 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5820 " > ccccccccccccccccccccccccccccccccccccccccc;",
5821 Style);
5822
5823 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5824 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5825 " + cc;",
5826 Style);
5827 verifyFormat("int a = aa\n"
5828 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5829 " * cccccccccccccccccccccccccccccccccccc;\n",
5830 Style);
5831
5832 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5833 verifyFormat("return (a > b\n"
5834 " // comment1\n"
5835 " // comment2\n"
5836 " || c);",
5837 Style);
5838 }
5839
TEST_F(FormatTest,BreakingBeforeNonAssigmentOperators)5840 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
5841 FormatStyle Style = getLLVMStyle();
5842 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5843 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5844 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5845 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5846 Style);
5847 }
5848
TEST_F(FormatTest,AllowBinPackingInsideArguments)5849 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
5850 FormatStyle Style = getLLVMStyle();
5851 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5852 Style.BinPackArguments = false;
5853 Style.ColumnLimit = 40;
5854 verifyFormat("void test() {\n"
5855 " someFunction(\n"
5856 " this + argument + is + quite\n"
5857 " + long + so + it + gets + wrapped\n"
5858 " + but + remains + bin - packed);\n"
5859 "}",
5860 Style);
5861 verifyFormat("void test() {\n"
5862 " someFunction(arg1,\n"
5863 " this + argument + is\n"
5864 " + quite + long + so\n"
5865 " + it + gets + wrapped\n"
5866 " + but + remains + bin\n"
5867 " - packed,\n"
5868 " arg3);\n"
5869 "}",
5870 Style);
5871 verifyFormat("void test() {\n"
5872 " someFunction(\n"
5873 " arg1,\n"
5874 " this + argument + has\n"
5875 " + anotherFunc(nested,\n"
5876 " calls + whose\n"
5877 " + arguments\n"
5878 " + are + also\n"
5879 " + wrapped,\n"
5880 " in + addition)\n"
5881 " + to + being + bin - packed,\n"
5882 " arg3);\n"
5883 "}",
5884 Style);
5885
5886 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5887 verifyFormat("void test() {\n"
5888 " someFunction(\n"
5889 " arg1,\n"
5890 " this + argument + has +\n"
5891 " anotherFunc(nested,\n"
5892 " calls + whose +\n"
5893 " arguments +\n"
5894 " are + also +\n"
5895 " wrapped,\n"
5896 " in + addition) +\n"
5897 " to + being + bin - packed,\n"
5898 " arg3);\n"
5899 "}",
5900 Style);
5901 }
5902
TEST_F(FormatTest,ConstructorInitializers)5903 TEST_F(FormatTest, ConstructorInitializers) {
5904 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5905 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
5906 getLLVMStyleWithColumns(45));
5907 verifyFormat("Constructor()\n"
5908 " : Inttializer(FitsOnTheLine) {}",
5909 getLLVMStyleWithColumns(44));
5910 verifyFormat("Constructor()\n"
5911 " : Inttializer(FitsOnTheLine) {}",
5912 getLLVMStyleWithColumns(43));
5913
5914 verifyFormat("template <typename T>\n"
5915 "Constructor() : Initializer(FitsOnTheLine) {}",
5916 getLLVMStyleWithColumns(45));
5917
5918 verifyFormat(
5919 "SomeClass::Constructor()\n"
5920 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5921
5922 verifyFormat(
5923 "SomeClass::Constructor()\n"
5924 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5925 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
5926 verifyFormat(
5927 "SomeClass::Constructor()\n"
5928 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5929 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5930 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5931 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5932 " : aaaaaaaaaa(aaaaaa) {}");
5933
5934 verifyFormat("Constructor()\n"
5935 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5936 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5937 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5938 " aaaaaaaaaaaaaaaaaaaaaaa() {}");
5939
5940 verifyFormat("Constructor()\n"
5941 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5942 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5943
5944 verifyFormat("Constructor(int Parameter = 0)\n"
5945 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5946 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
5947 verifyFormat("Constructor()\n"
5948 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5949 "}",
5950 getLLVMStyleWithColumns(60));
5951 verifyFormat("Constructor()\n"
5952 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5953 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
5954
5955 // Here a line could be saved by splitting the second initializer onto two
5956 // lines, but that is not desirable.
5957 verifyFormat("Constructor()\n"
5958 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5959 " aaaaaaaaaaa(aaaaaaaaaaa),\n"
5960 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5961
5962 FormatStyle OnePerLine = getLLVMStyle();
5963 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5964 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
5965 verifyFormat("SomeClass::Constructor()\n"
5966 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5967 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5968 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5969 OnePerLine);
5970 verifyFormat("SomeClass::Constructor()\n"
5971 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5972 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5973 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5974 OnePerLine);
5975 verifyFormat("MyClass::MyClass(int var)\n"
5976 " : some_var_(var), // 4 space indent\n"
5977 " some_other_var_(var + 1) { // lined up\n"
5978 "}",
5979 OnePerLine);
5980 verifyFormat("Constructor()\n"
5981 " : aaaaa(aaaaaa),\n"
5982 " aaaaa(aaaaaa),\n"
5983 " aaaaa(aaaaaa),\n"
5984 " aaaaa(aaaaaa),\n"
5985 " aaaaa(aaaaaa) {}",
5986 OnePerLine);
5987 verifyFormat("Constructor()\n"
5988 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
5989 " aaaaaaaaaaaaaaaaaaaaaa) {}",
5990 OnePerLine);
5991 OnePerLine.BinPackParameters = false;
5992 verifyFormat(
5993 "Constructor()\n"
5994 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5995 " aaaaaaaaaaa().aaa(),\n"
5996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5997 OnePerLine);
5998 OnePerLine.ColumnLimit = 60;
5999 verifyFormat("Constructor()\n"
6000 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
6001 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6002 OnePerLine);
6003
6004 EXPECT_EQ("Constructor()\n"
6005 " : // Comment forcing unwanted break.\n"
6006 " aaaa(aaaa) {}",
6007 format("Constructor() :\n"
6008 " // Comment forcing unwanted break.\n"
6009 " aaaa(aaaa) {}"));
6010 }
6011
TEST_F(FormatTest,AllowAllConstructorInitializersOnNextLine)6012 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6013 FormatStyle Style = getLLVMStyle();
6014 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6015 Style.ColumnLimit = 60;
6016 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
6017 Style.AllowAllConstructorInitializersOnNextLine = true;
6018 Style.BinPackParameters = false;
6019
6020 for (int i = 0; i < 4; ++i) {
6021 // Test all combinations of parameters that should not have an effect.
6022 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6023 Style.AllowAllArgumentsOnNextLine = i & 2;
6024
6025 Style.AllowAllConstructorInitializersOnNextLine = true;
6026 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6027 verifyFormat("Constructor()\n"
6028 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6029 Style);
6030 verifyFormat("Constructor() : a(a), b(b) {}", Style);
6031
6032 Style.AllowAllConstructorInitializersOnNextLine = false;
6033 verifyFormat("Constructor()\n"
6034 " : aaaaaaaaaaaaaaaaaaaa(a)\n"
6035 " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6036 Style);
6037 verifyFormat("Constructor() : a(a), b(b) {}", Style);
6038
6039 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6040 Style.AllowAllConstructorInitializersOnNextLine = true;
6041 verifyFormat("Constructor()\n"
6042 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6043 Style);
6044
6045 Style.AllowAllConstructorInitializersOnNextLine = false;
6046 verifyFormat("Constructor()\n"
6047 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
6048 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
6049 Style);
6050
6051 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6052 Style.AllowAllConstructorInitializersOnNextLine = true;
6053 verifyFormat("Constructor() :\n"
6054 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6055 Style);
6056
6057 Style.AllowAllConstructorInitializersOnNextLine = false;
6058 verifyFormat("Constructor() :\n"
6059 " aaaaaaaaaaaaaaaaaa(a),\n"
6060 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
6061 Style);
6062 }
6063
6064 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6065 // AllowAllConstructorInitializersOnNextLine in all
6066 // BreakConstructorInitializers modes
6067 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6068 Style.AllowAllParametersOfDeclarationOnNextLine = true;
6069 Style.AllowAllConstructorInitializersOnNextLine = false;
6070 verifyFormat("SomeClassWithALongName::Constructor(\n"
6071 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6072 " : aaaaaaaaaaaaaaaaaaaa(a)\n"
6073 " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6074 Style);
6075
6076 Style.AllowAllConstructorInitializersOnNextLine = true;
6077 verifyFormat("SomeClassWithALongName::Constructor(\n"
6078 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6079 " int bbbbbbbbbbbbb,\n"
6080 " int cccccccccccccccc)\n"
6081 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6082 Style);
6083
6084 Style.AllowAllParametersOfDeclarationOnNextLine = false;
6085 Style.AllowAllConstructorInitializersOnNextLine = false;
6086 verifyFormat("SomeClassWithALongName::Constructor(\n"
6087 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6088 " int bbbbbbbbbbbbb)\n"
6089 " : aaaaaaaaaaaaaaaaaaaa(a)\n"
6090 " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6091 Style);
6092
6093 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6094
6095 Style.AllowAllParametersOfDeclarationOnNextLine = true;
6096 verifyFormat("SomeClassWithALongName::Constructor(\n"
6097 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6098 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
6099 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
6100 Style);
6101
6102 Style.AllowAllConstructorInitializersOnNextLine = true;
6103 verifyFormat("SomeClassWithALongName::Constructor(\n"
6104 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6105 " int bbbbbbbbbbbbb,\n"
6106 " int cccccccccccccccc)\n"
6107 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6108 Style);
6109
6110 Style.AllowAllParametersOfDeclarationOnNextLine = false;
6111 Style.AllowAllConstructorInitializersOnNextLine = false;
6112 verifyFormat("SomeClassWithALongName::Constructor(\n"
6113 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6114 " int bbbbbbbbbbbbb)\n"
6115 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
6116 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
6117 Style);
6118
6119 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6120 Style.AllowAllParametersOfDeclarationOnNextLine = true;
6121 verifyFormat("SomeClassWithALongName::Constructor(\n"
6122 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6123 " aaaaaaaaaaaaaaaaaaaa(a),\n"
6124 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
6125 Style);
6126
6127 Style.AllowAllConstructorInitializersOnNextLine = true;
6128 verifyFormat("SomeClassWithALongName::Constructor(\n"
6129 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6130 " int bbbbbbbbbbbbb,\n"
6131 " int cccccccccccccccc) :\n"
6132 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6133 Style);
6134
6135 Style.AllowAllParametersOfDeclarationOnNextLine = false;
6136 Style.AllowAllConstructorInitializersOnNextLine = false;
6137 verifyFormat("SomeClassWithALongName::Constructor(\n"
6138 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6139 " int bbbbbbbbbbbbb) :\n"
6140 " aaaaaaaaaaaaaaaaaaaa(a),\n"
6141 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
6142 Style);
6143 }
6144
TEST_F(FormatTest,AllowAllArgumentsOnNextLine)6145 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6146 FormatStyle Style = getLLVMStyle();
6147 Style.ColumnLimit = 60;
6148 Style.BinPackArguments = false;
6149 for (int i = 0; i < 4; ++i) {
6150 // Test all combinations of parameters that should not have an effect.
6151 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6152 Style.AllowAllConstructorInitializersOnNextLine = i & 2;
6153
6154 Style.AllowAllArgumentsOnNextLine = true;
6155 verifyFormat("void foo() {\n"
6156 " FunctionCallWithReallyLongName(\n"
6157 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6158 "}",
6159 Style);
6160 Style.AllowAllArgumentsOnNextLine = false;
6161 verifyFormat("void foo() {\n"
6162 " FunctionCallWithReallyLongName(\n"
6163 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6164 " bbbbbbbbbbbb);\n"
6165 "}",
6166 Style);
6167
6168 Style.AllowAllArgumentsOnNextLine = true;
6169 verifyFormat("void foo() {\n"
6170 " auto VariableWithReallyLongName = {\n"
6171 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6172 "}",
6173 Style);
6174 Style.AllowAllArgumentsOnNextLine = false;
6175 verifyFormat("void foo() {\n"
6176 " auto VariableWithReallyLongName = {\n"
6177 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6178 " bbbbbbbbbbbb};\n"
6179 "}",
6180 Style);
6181 }
6182
6183 // This parameter should not affect declarations.
6184 Style.BinPackParameters = false;
6185 Style.AllowAllArgumentsOnNextLine = false;
6186 Style.AllowAllParametersOfDeclarationOnNextLine = true;
6187 verifyFormat("void FunctionCallWithReallyLongName(\n"
6188 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6189 Style);
6190 Style.AllowAllParametersOfDeclarationOnNextLine = false;
6191 verifyFormat("void FunctionCallWithReallyLongName(\n"
6192 " int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6193 " int bbbbbbbbbbbb);",
6194 Style);
6195 }
6196
TEST_F(FormatTest,AllowAllArgumentsOnNextLineDontAlign)6197 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6198 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6199 // and BAS_Align.
6200 auto Style = getLLVMStyle();
6201 Style.ColumnLimit = 35;
6202 StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6203 "void functionDecl(int A, int B, int C);";
6204 Style.AllowAllArgumentsOnNextLine = false;
6205 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6206 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6207 " paramC);\n"
6208 "void functionDecl(int A, int B,\n"
6209 " int C);"),
6210 format(Input, Style));
6211 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6212 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6213 " paramC);\n"
6214 "void functionDecl(int A, int B,\n"
6215 " int C);"),
6216 format(Input, Style));
6217 // However, BAS_AlwaysBreak should take precedence over
6218 // AllowAllArgumentsOnNextLine.
6219 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6220 EXPECT_EQ(StringRef("functionCall(\n"
6221 " paramA, paramB, paramC);\n"
6222 "void functionDecl(\n"
6223 " int A, int B, int C);"),
6224 format(Input, Style));
6225
6226 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6227 // first argument.
6228 Style.AllowAllArgumentsOnNextLine = true;
6229 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6230 EXPECT_EQ(StringRef("functionCall(\n"
6231 " paramA, paramB, paramC);\n"
6232 "void functionDecl(\n"
6233 " int A, int B, int C);"),
6234 format(Input, Style));
6235 // It wouldn't fit on one line with aligned parameters so this setting
6236 // doesn't change anything for BAS_Align.
6237 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6238 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6239 " paramC);\n"
6240 "void functionDecl(int A, int B,\n"
6241 " int C);"),
6242 format(Input, Style));
6243 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6244 EXPECT_EQ(StringRef("functionCall(\n"
6245 " paramA, paramB, paramC);\n"
6246 "void functionDecl(\n"
6247 " int A, int B, int C);"),
6248 format(Input, Style));
6249 }
6250
TEST_F(FormatTest,BreakConstructorInitializersAfterColon)6251 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6252 FormatStyle Style = getLLVMStyle();
6253 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6254
6255 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6256 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6257 getStyleWithColumns(Style, 45));
6258 verifyFormat("Constructor() :\n"
6259 " Initializer(FitsOnTheLine) {}",
6260 getStyleWithColumns(Style, 44));
6261 verifyFormat("Constructor() :\n"
6262 " Initializer(FitsOnTheLine) {}",
6263 getStyleWithColumns(Style, 43));
6264
6265 verifyFormat("template <typename T>\n"
6266 "Constructor() : Initializer(FitsOnTheLine) {}",
6267 getStyleWithColumns(Style, 50));
6268 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
6269 verifyFormat(
6270 "SomeClass::Constructor() :\n"
6271 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6272 Style);
6273
6274 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
6275 verifyFormat(
6276 "SomeClass::Constructor() :\n"
6277 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6278 Style);
6279
6280 verifyFormat(
6281 "SomeClass::Constructor() :\n"
6282 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6283 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6284 Style);
6285 verifyFormat(
6286 "SomeClass::Constructor() :\n"
6287 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6288 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6289 Style);
6290 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6291 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6292 " aaaaaaaaaa(aaaaaa) {}",
6293 Style);
6294
6295 verifyFormat("Constructor() :\n"
6296 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6297 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6298 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6299 " aaaaaaaaaaaaaaaaaaaaaaa() {}",
6300 Style);
6301
6302 verifyFormat("Constructor() :\n"
6303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6304 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6305 Style);
6306
6307 verifyFormat("Constructor(int Parameter = 0) :\n"
6308 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6309 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6310 Style);
6311 verifyFormat("Constructor() :\n"
6312 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6313 "}",
6314 getStyleWithColumns(Style, 60));
6315 verifyFormat("Constructor() :\n"
6316 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6317 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6318 Style);
6319
6320 // Here a line could be saved by splitting the second initializer onto two
6321 // lines, but that is not desirable.
6322 verifyFormat("Constructor() :\n"
6323 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6324 " aaaaaaaaaaa(aaaaaaaaaaa),\n"
6325 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6326 Style);
6327
6328 FormatStyle OnePerLine = Style;
6329 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
6330 OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
6331 verifyFormat("SomeClass::Constructor() :\n"
6332 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6333 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6334 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6335 OnePerLine);
6336 verifyFormat("SomeClass::Constructor() :\n"
6337 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6338 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6339 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6340 OnePerLine);
6341 verifyFormat("MyClass::MyClass(int var) :\n"
6342 " some_var_(var), // 4 space indent\n"
6343 " some_other_var_(var + 1) { // lined up\n"
6344 "}",
6345 OnePerLine);
6346 verifyFormat("Constructor() :\n"
6347 " aaaaa(aaaaaa),\n"
6348 " aaaaa(aaaaaa),\n"
6349 " aaaaa(aaaaaa),\n"
6350 " aaaaa(aaaaaa),\n"
6351 " aaaaa(aaaaaa) {}",
6352 OnePerLine);
6353 verifyFormat("Constructor() :\n"
6354 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6355 " aaaaaaaaaaaaaaaaaaaaaa) {}",
6356 OnePerLine);
6357 OnePerLine.BinPackParameters = false;
6358 verifyFormat("Constructor() :\n"
6359 " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6360 " aaaaaaaaaaa().aaa(),\n"
6361 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6362 OnePerLine);
6363 OnePerLine.ColumnLimit = 60;
6364 verifyFormat("Constructor() :\n"
6365 " aaaaaaaaaaaaaaaaaaaa(a),\n"
6366 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6367 OnePerLine);
6368
6369 EXPECT_EQ("Constructor() :\n"
6370 " // Comment forcing unwanted break.\n"
6371 " aaaa(aaaa) {}",
6372 format("Constructor() :\n"
6373 " // Comment forcing unwanted break.\n"
6374 " aaaa(aaaa) {}",
6375 Style));
6376
6377 Style.ColumnLimit = 0;
6378 verifyFormat("SomeClass::Constructor() :\n"
6379 " a(a) {}",
6380 Style);
6381 verifyFormat("SomeClass::Constructor() noexcept :\n"
6382 " a(a) {}",
6383 Style);
6384 verifyFormat("SomeClass::Constructor() :\n"
6385 " a(a), b(b), c(c) {}",
6386 Style);
6387 verifyFormat("SomeClass::Constructor() :\n"
6388 " a(a) {\n"
6389 " foo();\n"
6390 " bar();\n"
6391 "}",
6392 Style);
6393
6394 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6395 verifyFormat("SomeClass::Constructor() :\n"
6396 " a(a), b(b), c(c) {\n"
6397 "}",
6398 Style);
6399 verifyFormat("SomeClass::Constructor() :\n"
6400 " a(a) {\n"
6401 "}",
6402 Style);
6403
6404 Style.ColumnLimit = 80;
6405 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6406 Style.ConstructorInitializerIndentWidth = 2;
6407 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6408 verifyFormat("SomeClass::Constructor() :\n"
6409 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6410 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6411 Style);
6412
6413 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6414 // well
6415 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6416 verifyFormat(
6417 "class SomeClass\n"
6418 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6419 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6420 Style);
6421 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6422 verifyFormat(
6423 "class SomeClass\n"
6424 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6425 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6426 Style);
6427 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6428 verifyFormat(
6429 "class SomeClass :\n"
6430 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6431 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6432 Style);
6433 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6434 verifyFormat(
6435 "class SomeClass\n"
6436 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6437 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6438 Style);
6439 }
6440
6441 #ifndef EXPENSIVE_CHECKS
6442 // Expensive checks enables libstdc++ checking which includes validating the
6443 // state of ranges used in std::priority_queue - this blows out the
6444 // runtime/scalability of the function and makes this test unacceptably slow.
TEST_F(FormatTest,MemoizationTests)6445 TEST_F(FormatTest, MemoizationTests) {
6446 // This breaks if the memoization lookup does not take \c Indent and
6447 // \c LastSpace into account.
6448 verifyFormat(
6449 "extern CFRunLoopTimerRef\n"
6450 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
6451 " CFTimeInterval interval, CFOptionFlags flags,\n"
6452 " CFIndex order, CFRunLoopTimerCallBack callout,\n"
6453 " CFRunLoopTimerContext *context) {}");
6454
6455 // Deep nesting somewhat works around our memoization.
6456 verifyFormat(
6457 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6458 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6459 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6460 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6461 " aaaaa())))))))))))))))))))))))))))))))))))))));",
6462 getLLVMStyleWithColumns(65));
6463 verifyFormat(
6464 "aaaaa(\n"
6465 " aaaaa,\n"
6466 " aaaaa(\n"
6467 " aaaaa,\n"
6468 " aaaaa(\n"
6469 " aaaaa,\n"
6470 " aaaaa(\n"
6471 " aaaaa,\n"
6472 " aaaaa(\n"
6473 " aaaaa,\n"
6474 " aaaaa(\n"
6475 " aaaaa,\n"
6476 " aaaaa(\n"
6477 " aaaaa,\n"
6478 " aaaaa(\n"
6479 " aaaaa,\n"
6480 " aaaaa(\n"
6481 " aaaaa,\n"
6482 " aaaaa(\n"
6483 " aaaaa,\n"
6484 " aaaaa(\n"
6485 " aaaaa,\n"
6486 " aaaaa(\n"
6487 " aaaaa,\n"
6488 " aaaaa))))))))))));",
6489 getLLVMStyleWithColumns(65));
6490 verifyFormat(
6491 "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
6492 " a),\n"
6493 " a),\n"
6494 " a),\n"
6495 " a),\n"
6496 " a),\n"
6497 " a),\n"
6498 " a),\n"
6499 " a),\n"
6500 " a),\n"
6501 " a),\n"
6502 " a),\n"
6503 " a),\n"
6504 " a),\n"
6505 " a),\n"
6506 " a),\n"
6507 " a),\n"
6508 " a)",
6509 getLLVMStyleWithColumns(65));
6510
6511 // This test takes VERY long when memoization is broken.
6512 FormatStyle OnePerLine = getLLVMStyle();
6513 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
6514 OnePerLine.BinPackParameters = false;
6515 std::string input = "Constructor()\n"
6516 " : aaaa(a,\n";
6517 for (unsigned i = 0, e = 80; i != e; ++i) {
6518 input += " a,\n";
6519 }
6520 input += " a) {}";
6521 verifyFormat(input, OnePerLine);
6522 }
6523 #endif
6524
TEST_F(FormatTest,BreaksAsHighAsPossible)6525 TEST_F(FormatTest, BreaksAsHighAsPossible) {
6526 verifyFormat(
6527 "void f() {\n"
6528 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
6529 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
6530 " f();\n"
6531 "}");
6532 verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
6533 " Intervals[i - 1].getRange().getLast()) {\n}");
6534 }
6535
TEST_F(FormatTest,BreaksFunctionDeclarations)6536 TEST_F(FormatTest, BreaksFunctionDeclarations) {
6537 // Principially, we break function declarations in a certain order:
6538 // 1) break amongst arguments.
6539 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
6540 " Cccccccccccccc cccccccccccccc);");
6541 verifyFormat("template <class TemplateIt>\n"
6542 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
6543 " TemplateIt *stop) {}");
6544
6545 // 2) break after return type.
6546 verifyFormat(
6547 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6548 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
6549 getGoogleStyle());
6550
6551 // 3) break after (.
6552 verifyFormat(
6553 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
6554 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
6555 getGoogleStyle());
6556
6557 // 4) break before after nested name specifiers.
6558 verifyFormat(
6559 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6560 "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
6561 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
6562 getGoogleStyle());
6563
6564 // However, there are exceptions, if a sufficient amount of lines can be
6565 // saved.
6566 // FIXME: The precise cut-offs wrt. the number of saved lines might need some
6567 // more adjusting.
6568 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6569 " Cccccccccccccc cccccccccc,\n"
6570 " Cccccccccccccc cccccccccc,\n"
6571 " Cccccccccccccc cccccccccc,\n"
6572 " Cccccccccccccc cccccccccc);");
6573 verifyFormat(
6574 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6575 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6576 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6577 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
6578 getGoogleStyle());
6579 verifyFormat(
6580 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6581 " Cccccccccccccc cccccccccc,\n"
6582 " Cccccccccccccc cccccccccc,\n"
6583 " Cccccccccccccc cccccccccc,\n"
6584 " Cccccccccccccc cccccccccc,\n"
6585 " Cccccccccccccc cccccccccc,\n"
6586 " Cccccccccccccc cccccccccc);");
6587 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6588 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6589 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6590 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6591 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
6592
6593 // Break after multi-line parameters.
6594 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6595 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6596 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6597 " bbbb bbbb);");
6598 verifyFormat("void SomeLoooooooooooongFunction(\n"
6599 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6600 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6601 " int bbbbbbbbbbbbb);");
6602
6603 // Treat overloaded operators like other functions.
6604 verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6605 "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
6606 verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6607 "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
6608 verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6609 "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
6610 verifyGoogleFormat(
6611 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
6612 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6613 verifyGoogleFormat(
6614 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
6615 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6616 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6617 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6618 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
6619 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6620 verifyGoogleFormat(
6621 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
6622 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6623 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
6624 verifyGoogleFormat("template <typename T>\n"
6625 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6626 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
6627 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
6628
6629 FormatStyle Style = getLLVMStyle();
6630 Style.PointerAlignment = FormatStyle::PAS_Left;
6631 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6632 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
6633 Style);
6634 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
6635 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6636 Style);
6637 }
6638
TEST_F(FormatTest,DontBreakBeforeQualifiedOperator)6639 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
6640 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
6641 // Prefer keeping `::` followed by `operator` together.
6642 EXPECT_EQ("const aaaa::bbbbbbb &\n"
6643 "ccccccccc::operator++() {\n"
6644 " stuff();\n"
6645 "}",
6646 format("const aaaa::bbbbbbb\n"
6647 "&ccccccccc::operator++() { stuff(); }",
6648 getLLVMStyleWithColumns(40)));
6649 }
6650
TEST_F(FormatTest,TrailingReturnType)6651 TEST_F(FormatTest, TrailingReturnType) {
6652 verifyFormat("auto foo() -> int;\n");
6653 // correct trailing return type spacing
6654 verifyFormat("auto operator->() -> int;\n");
6655 verifyFormat("auto operator++(int) -> int;\n");
6656
6657 verifyFormat("struct S {\n"
6658 " auto bar() const -> int;\n"
6659 "};");
6660 verifyFormat("template <size_t Order, typename T>\n"
6661 "auto load_img(const std::string &filename)\n"
6662 " -> alias::tensor<Order, T, mem::tag::cpu> {}");
6663 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
6664 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
6665 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
6666 verifyFormat("template <typename T>\n"
6667 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
6668 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
6669
6670 // Not trailing return types.
6671 verifyFormat("void f() { auto a = b->c(); }");
6672 }
6673
TEST_F(FormatTest,DeductionGuides)6674 TEST_F(FormatTest, DeductionGuides) {
6675 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
6676 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
6677 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
6678 verifyFormat(
6679 "template <class... T>\n"
6680 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
6681 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
6682 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
6683 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
6684 verifyFormat("template <class T> A() -> A<(3 < 2)>;");
6685 verifyFormat("template <class T> A() -> A<((3) < (2))>;");
6686 verifyFormat("template <class T> x() -> x<1>;");
6687 verifyFormat("template <class T> explicit x(T &) -> x<1>;");
6688
6689 // Ensure not deduction guides.
6690 verifyFormat("c()->f<int>();");
6691 verifyFormat("x()->foo<1>;");
6692 verifyFormat("x = p->foo<3>();");
6693 verifyFormat("x()->x<1>();");
6694 verifyFormat("x()->x<1>;");
6695 }
6696
TEST_F(FormatTest,BreaksFunctionDeclarationsWithTrailingTokens)6697 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
6698 // Avoid breaking before trailing 'const' or other trailing annotations, if
6699 // they are not function-like.
6700 FormatStyle Style = getGoogleStyle();
6701 Style.ColumnLimit = 47;
6702 verifyFormat("void someLongFunction(\n"
6703 " int someLoooooooooooooongParameter) const {\n}",
6704 getLLVMStyleWithColumns(47));
6705 verifyFormat("LoooooongReturnType\n"
6706 "someLoooooooongFunction() const {}",
6707 getLLVMStyleWithColumns(47));
6708 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
6709 " const {}",
6710 Style);
6711 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6712 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
6713 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6714 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
6715 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6716 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
6717 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
6718 " aaaaaaaaaaa aaaaa) const override;");
6719 verifyGoogleFormat(
6720 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6721 " const override;");
6722
6723 // Even if the first parameter has to be wrapped.
6724 verifyFormat("void someLongFunction(\n"
6725 " int someLongParameter) const {}",
6726 getLLVMStyleWithColumns(46));
6727 verifyFormat("void someLongFunction(\n"
6728 " int someLongParameter) const {}",
6729 Style);
6730 verifyFormat("void someLongFunction(\n"
6731 " int someLongParameter) override {}",
6732 Style);
6733 verifyFormat("void someLongFunction(\n"
6734 " int someLongParameter) OVERRIDE {}",
6735 Style);
6736 verifyFormat("void someLongFunction(\n"
6737 " int someLongParameter) final {}",
6738 Style);
6739 verifyFormat("void someLongFunction(\n"
6740 " int someLongParameter) FINAL {}",
6741 Style);
6742 verifyFormat("void someLongFunction(\n"
6743 " int parameter) const override {}",
6744 Style);
6745
6746 Style.BreakBeforeBraces = FormatStyle::BS_Allman;
6747 verifyFormat("void someLongFunction(\n"
6748 " int someLongParameter) const\n"
6749 "{\n"
6750 "}",
6751 Style);
6752
6753 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
6754 verifyFormat("void someLongFunction(\n"
6755 " int someLongParameter) const\n"
6756 " {\n"
6757 " }",
6758 Style);
6759
6760 // Unless these are unknown annotations.
6761 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
6762 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6763 " LONG_AND_UGLY_ANNOTATION;");
6764
6765 // Breaking before function-like trailing annotations is fine to keep them
6766 // close to their arguments.
6767 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6768 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6769 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6770 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6771 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6772 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
6773 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
6774 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
6775 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
6776
6777 verifyFormat(
6778 "void aaaaaaaaaaaaaaaaaa()\n"
6779 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
6780 " aaaaaaaaaaaaaaaaaaaaaaaaa));");
6781 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6782 " __attribute__((unused));");
6783 verifyGoogleFormat(
6784 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6785 " GUARDED_BY(aaaaaaaaaaaa);");
6786 verifyGoogleFormat(
6787 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6788 " GUARDED_BY(aaaaaaaaaaaa);");
6789 verifyGoogleFormat(
6790 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6791 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6792 verifyGoogleFormat(
6793 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6794 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
6795 }
6796
TEST_F(FormatTest,FunctionAnnotations)6797 TEST_F(FormatTest, FunctionAnnotations) {
6798 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6799 "int OldFunction(const string ¶meter) {}");
6800 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6801 "string OldFunction(const string ¶meter) {}");
6802 verifyFormat("template <typename T>\n"
6803 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6804 "string OldFunction(const string ¶meter) {}");
6805
6806 // Not function annotations.
6807 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6808 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
6809 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
6810 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
6811 verifyFormat("MACRO(abc).function() // wrap\n"
6812 " << abc;");
6813 verifyFormat("MACRO(abc)->function() // wrap\n"
6814 " << abc;");
6815 verifyFormat("MACRO(abc)::function() // wrap\n"
6816 " << abc;");
6817 }
6818
TEST_F(FormatTest,BreaksDesireably)6819 TEST_F(FormatTest, BreaksDesireably) {
6820 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6821 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6822 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
6823 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6824 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
6825 "}");
6826
6827 verifyFormat(
6828 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6829 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6830
6831 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6832 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6833 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6834
6835 verifyFormat(
6836 "aaaaaaaa(aaaaaaaaaaaaa,\n"
6837 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6838 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6839 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6840 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
6841
6842 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6843 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6844
6845 verifyFormat(
6846 "void f() {\n"
6847 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
6848 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6849 "}");
6850 verifyFormat(
6851 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6852 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6853 verifyFormat(
6854 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6855 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6856 verifyFormat(
6857 "aaaaaa(aaa,\n"
6858 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6859 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6860 " aaaa);");
6861 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6862 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6863 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6864
6865 // Indent consistently independent of call expression and unary operator.
6866 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6867 " dddddddddddddddddddddddddddddd));");
6868 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6869 " dddddddddddddddddddddddddddddd));");
6870 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
6871 " dddddddddddddddddddddddddddddd));");
6872
6873 // This test case breaks on an incorrect memoization, i.e. an optimization not
6874 // taking into account the StopAt value.
6875 verifyFormat(
6876 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6877 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6878 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6879 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6880
6881 verifyFormat("{\n {\n {\n"
6882 " Annotation.SpaceRequiredBefore =\n"
6883 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
6884 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
6885 " }\n }\n}");
6886
6887 // Break on an outer level if there was a break on an inner level.
6888 EXPECT_EQ("f(g(h(a, // comment\n"
6889 " b, c),\n"
6890 " d, e),\n"
6891 " x, y);",
6892 format("f(g(h(a, // comment\n"
6893 " b, c), d, e), x, y);"));
6894
6895 // Prefer breaking similar line breaks.
6896 verifyFormat(
6897 "const int kTrackingOptions = NSTrackingMouseMoved |\n"
6898 " NSTrackingMouseEnteredAndExited |\n"
6899 " NSTrackingActiveAlways;");
6900 }
6901
TEST_F(FormatTest,FormatsDeclarationsOnePerLine)6902 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
6903 FormatStyle NoBinPacking = getGoogleStyle();
6904 NoBinPacking.BinPackParameters = false;
6905 NoBinPacking.BinPackArguments = true;
6906 verifyFormat("void f() {\n"
6907 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
6908 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6909 "}",
6910 NoBinPacking);
6911 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
6912 " int aaaaaaaaaaaaaaaaaaaa,\n"
6913 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6914 NoBinPacking);
6915
6916 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6917 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6918 " vector<int> bbbbbbbbbbbbbbb);",
6919 NoBinPacking);
6920 // FIXME: This behavior difference is probably not wanted. However, currently
6921 // we cannot distinguish BreakBeforeParameter being set because of the wrapped
6922 // template arguments from BreakBeforeParameter being set because of the
6923 // one-per-line formatting.
6924 verifyFormat(
6925 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6926 " aaaaaaaaaa> aaaaaaaaaa);",
6927 NoBinPacking);
6928 verifyFormat(
6929 "void fffffffffff(\n"
6930 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
6931 " aaaaaaaaaa);");
6932 }
6933
TEST_F(FormatTest,FormatsOneParameterPerLineIfNecessary)6934 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
6935 FormatStyle NoBinPacking = getGoogleStyle();
6936 NoBinPacking.BinPackParameters = false;
6937 NoBinPacking.BinPackArguments = false;
6938 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
6939 " aaaaaaaaaaaaaaaaaaaa,\n"
6940 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
6941 NoBinPacking);
6942 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
6943 " aaaaaaaaaaaaa,\n"
6944 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
6945 NoBinPacking);
6946 verifyFormat(
6947 "aaaaaaaa(aaaaaaaaaaaaa,\n"
6948 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6949 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6950 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6951 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
6952 NoBinPacking);
6953 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
6954 " .aaaaaaaaaaaaaaaaaa();",
6955 NoBinPacking);
6956 verifyFormat("void f() {\n"
6957 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6958 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
6959 "}",
6960 NoBinPacking);
6961
6962 verifyFormat(
6963 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6964 " aaaaaaaaaaaa,\n"
6965 " aaaaaaaaaaaa);",
6966 NoBinPacking);
6967 verifyFormat(
6968 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
6969 " ddddddddddddddddddddddddddddd),\n"
6970 " test);",
6971 NoBinPacking);
6972
6973 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6974 " aaaaaaaaaaaaaaaaaaaaaaa,\n"
6975 " aaaaaaaaaaaaaaaaaaaaaaa>\n"
6976 " aaaaaaaaaaaaaaaaaa;",
6977 NoBinPacking);
6978 verifyFormat("a(\"a\"\n"
6979 " \"a\",\n"
6980 " a);");
6981
6982 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6983 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
6984 " aaaaaaaaa,\n"
6985 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6986 NoBinPacking);
6987 verifyFormat(
6988 "void f() {\n"
6989 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
6990 " .aaaaaaa();\n"
6991 "}",
6992 NoBinPacking);
6993 verifyFormat(
6994 "template <class SomeType, class SomeOtherType>\n"
6995 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
6996 NoBinPacking);
6997 }
6998
TEST_F(FormatTest,AdaptiveOnePerLineFormatting)6999 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7000 FormatStyle Style = getLLVMStyleWithColumns(15);
7001 Style.ExperimentalAutoDetectBinPacking = true;
7002 EXPECT_EQ("aaa(aaaa,\n"
7003 " aaaa,\n"
7004 " aaaa);\n"
7005 "aaa(aaaa,\n"
7006 " aaaa,\n"
7007 " aaaa);",
7008 format("aaa(aaaa,\n" // one-per-line
7009 " aaaa,\n"
7010 " aaaa );\n"
7011 "aaa(aaaa, aaaa, aaaa);", // inconclusive
7012 Style));
7013 EXPECT_EQ("aaa(aaaa, aaaa,\n"
7014 " aaaa);\n"
7015 "aaa(aaaa, aaaa,\n"
7016 " aaaa);",
7017 format("aaa(aaaa, aaaa,\n" // bin-packed
7018 " aaaa );\n"
7019 "aaa(aaaa, aaaa, aaaa);", // inconclusive
7020 Style));
7021 }
7022
TEST_F(FormatTest,FormatsBuilderPattern)7023 TEST_F(FormatTest, FormatsBuilderPattern) {
7024 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7025 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7026 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7027 " .StartsWith(\".init\", ORDER_INIT)\n"
7028 " .StartsWith(\".fini\", ORDER_FINI)\n"
7029 " .StartsWith(\".hash\", ORDER_HASH)\n"
7030 " .Default(ORDER_TEXT);\n");
7031
7032 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7033 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7034 verifyFormat("aaaaaaa->aaaaaaa\n"
7035 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7037 " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7038 verifyFormat(
7039 "aaaaaaa->aaaaaaa\n"
7040 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7041 " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7042 verifyFormat(
7043 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7044 " aaaaaaaaaaaaaa);");
7045 verifyFormat(
7046 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7047 " aaaaaa->aaaaaaaaaaaa()\n"
7048 " ->aaaaaaaaaaaaaaaa(\n"
7049 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7050 " ->aaaaaaaaaaaaaaaaa();");
7051 verifyGoogleFormat(
7052 "void f() {\n"
7053 " someo->Add((new util::filetools::Handler(dir))\n"
7054 " ->OnEvent1(NewPermanentCallback(\n"
7055 " this, &HandlerHolderClass::EventHandlerCBA))\n"
7056 " ->OnEvent2(NewPermanentCallback(\n"
7057 " this, &HandlerHolderClass::EventHandlerCBB))\n"
7058 " ->OnEvent3(NewPermanentCallback(\n"
7059 " this, &HandlerHolderClass::EventHandlerCBC))\n"
7060 " ->OnEvent5(NewPermanentCallback(\n"
7061 " this, &HandlerHolderClass::EventHandlerCBD))\n"
7062 " ->OnEvent6(NewPermanentCallback(\n"
7063 " this, &HandlerHolderClass::EventHandlerCBE)));\n"
7064 "}");
7065
7066 verifyFormat(
7067 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7068 verifyFormat("aaaaaaaaaaaaaaa()\n"
7069 " .aaaaaaaaaaaaaaa()\n"
7070 " .aaaaaaaaaaaaaaa()\n"
7071 " .aaaaaaaaaaaaaaa()\n"
7072 " .aaaaaaaaaaaaaaa();");
7073 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7074 " .aaaaaaaaaaaaaaa()\n"
7075 " .aaaaaaaaaaaaaaa()\n"
7076 " .aaaaaaaaaaaaaaa();");
7077 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7078 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7079 " .aaaaaaaaaaaaaaa();");
7080 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7081 " ->aaaaaaaaaaaaaae(0)\n"
7082 " ->aaaaaaaaaaaaaaa();");
7083
7084 // Don't linewrap after very short segments.
7085 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7086 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7087 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7088 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7089 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7090 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7091 verifyFormat("aaa()\n"
7092 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7093 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7094 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7095
7096 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7097 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7098 " .has<bbbbbbbbbbbbbbbbbbbbb>();");
7099 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7100 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7101 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7102
7103 // Prefer not to break after empty parentheses.
7104 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7105 " First->LastNewlineOffset);");
7106
7107 // Prefer not to create "hanging" indents.
7108 verifyFormat(
7109 "return !soooooooooooooome_map\n"
7110 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7111 " .second;");
7112 verifyFormat(
7113 "return aaaaaaaaaaaaaaaa\n"
7114 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7115 " .aaaa(aaaaaaaaaaaaaa);");
7116 // No hanging indent here.
7117 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7119 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7121 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7122 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7123 getLLVMStyleWithColumns(60));
7124 verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7125 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7126 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7127 getLLVMStyleWithColumns(59));
7128 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7129 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7130 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7131
7132 // Dont break if only closing statements before member call
7133 verifyFormat("test() {\n"
7134 " ([]() -> {\n"
7135 " int b = 32;\n"
7136 " return 3;\n"
7137 " }).foo();\n"
7138 "}");
7139 verifyFormat("test() {\n"
7140 " (\n"
7141 " []() -> {\n"
7142 " int b = 32;\n"
7143 " return 3;\n"
7144 " },\n"
7145 " foo, bar)\n"
7146 " .foo();\n"
7147 "}");
7148 verifyFormat("test() {\n"
7149 " ([]() -> {\n"
7150 " int b = 32;\n"
7151 " return 3;\n"
7152 " })\n"
7153 " .foo()\n"
7154 " .bar();\n"
7155 "}");
7156 verifyFormat("test() {\n"
7157 " ([]() -> {\n"
7158 " int b = 32;\n"
7159 " return 3;\n"
7160 " })\n"
7161 " .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7162 " \"bbbb\");\n"
7163 "}",
7164 getLLVMStyleWithColumns(30));
7165 }
7166
TEST_F(FormatTest,BreaksAccordingToOperatorPrecedence)7167 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7168 verifyFormat(
7169 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7170 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7171 verifyFormat(
7172 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7173 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7174
7175 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7176 " ccccccccccccccccccccccccc) {\n}");
7177 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7178 " ccccccccccccccccccccccccc) {\n}");
7179
7180 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7181 " ccccccccccccccccccccccccc) {\n}");
7182 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7183 " ccccccccccccccccccccccccc) {\n}");
7184
7185 verifyFormat(
7186 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7187 " ccccccccccccccccccccccccc) {\n}");
7188 verifyFormat(
7189 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7190 " ccccccccccccccccccccccccc) {\n}");
7191
7192 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7193 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7194 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7195 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7196 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7197 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7198 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7199 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7200
7201 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7202 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7203 " aaaaaaaaaaaaaaa != aa) {\n}");
7204 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7205 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7206 " aaaaaaaaaaaaaaa != aa) {\n}");
7207 }
7208
TEST_F(FormatTest,BreaksAfterAssignments)7209 TEST_F(FormatTest, BreaksAfterAssignments) {
7210 verifyFormat(
7211 "unsigned Cost =\n"
7212 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7213 " SI->getPointerAddressSpaceee());\n");
7214 verifyFormat(
7215 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7216 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7217
7218 verifyFormat(
7219 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7220 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7221 verifyFormat("unsigned OriginalStartColumn =\n"
7222 " SourceMgr.getSpellingColumnNumber(\n"
7223 " Current.FormatTok.getStartOfNonWhitespace()) -\n"
7224 " 1;");
7225 }
7226
TEST_F(FormatTest,ConfigurableBreakAssignmentPenalty)7227 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7228 FormatStyle Style = getLLVMStyle();
7229 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7230 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7231 Style);
7232
7233 Style.PenaltyBreakAssignment = 20;
7234 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7235 " cccccccccccccccccccccccccc;",
7236 Style);
7237 }
7238
TEST_F(FormatTest,AlignsAfterAssignments)7239 TEST_F(FormatTest, AlignsAfterAssignments) {
7240 verifyFormat(
7241 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7242 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
7243 verifyFormat(
7244 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7245 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
7246 verifyFormat(
7247 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7248 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
7249 verifyFormat(
7250 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7251 " aaaaaaaaaaaaaaaaaaaaaaaaa);");
7252 verifyFormat(
7253 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7254 " aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7255 " aaaaaaaaaaaaaaaaaaaaaaaa;");
7256 }
7257
TEST_F(FormatTest,AlignsAfterReturn)7258 TEST_F(FormatTest, AlignsAfterReturn) {
7259 verifyFormat(
7260 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7261 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
7262 verifyFormat(
7263 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7264 " aaaaaaaaaaaaaaaaaaaaaaaaa);");
7265 verifyFormat(
7266 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7267 " aaaaaaaaaaaaaaaaaaaaaa();");
7268 verifyFormat(
7269 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7270 " aaaaaaaaaaaaaaaaaaaaaa());");
7271 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7272 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7273 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7274 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7275 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7276 verifyFormat("return\n"
7277 " // true if code is one of a or b.\n"
7278 " code == a || code == b;");
7279 }
7280
TEST_F(FormatTest,AlignsAfterOpenBracket)7281 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7282 verifyFormat(
7283 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7284 " aaaaaaaaa aaaaaaa) {}");
7285 verifyFormat(
7286 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7287 " aaaaaaaaaaa aaaaaaaaa);");
7288 verifyFormat(
7289 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7290 " aaaaaaaaaaaaaaaaaaaaa));");
7291 FormatStyle Style = getLLVMStyle();
7292 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7293 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7294 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7295 Style);
7296 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7297 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7298 Style);
7299 verifyFormat("SomeLongVariableName->someFunction(\n"
7300 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7301 Style);
7302 verifyFormat(
7303 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7304 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7305 Style);
7306 verifyFormat(
7307 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7308 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7309 Style);
7310 verifyFormat(
7311 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7312 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7313 Style);
7314
7315 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7316 " ccccccc(aaaaaaaaaaaaaaaaa, //\n"
7317 " b));",
7318 Style);
7319
7320 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7321 Style.BinPackArguments = false;
7322 Style.BinPackParameters = false;
7323 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7324 " aaaaaaaaaaa aaaaaaaa,\n"
7325 " aaaaaaaaa aaaaaaa,\n"
7326 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7327 Style);
7328 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7329 " aaaaaaaaaaa aaaaaaaaa,\n"
7330 " aaaaaaaaaaa aaaaaaaaa,\n"
7331 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7332 Style);
7333 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7334 " aaaaaaaaaaaaaaa,\n"
7335 " aaaaaaaaaaaaaaaaaaaaa,\n"
7336 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7337 Style);
7338 verifyFormat(
7339 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7340 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7341 Style);
7342 verifyFormat(
7343 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7344 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7345 Style);
7346 verifyFormat(
7347 "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7348 " aaaaaaaaaaaaaaaaaaaaa(\n"
7349 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7350 " aaaaaaaaaaaaaaaa);",
7351 Style);
7352 verifyFormat(
7353 "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7354 " aaaaaaaaaaaaaaaaaaaaa(\n"
7355 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7356 " aaaaaaaaaaaaaaaa);",
7357 Style);
7358 }
7359
TEST_F(FormatTest,ParenthesesAndOperandAlignment)7360 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7361 FormatStyle Style = getLLVMStyleWithColumns(40);
7362 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7363 " bbbbbbbbbbbbbbbbbbbbbb);",
7364 Style);
7365 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7366 Style.AlignOperands = FormatStyle::OAS_DontAlign;
7367 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7368 " bbbbbbbbbbbbbbbbbbbbbb);",
7369 Style);
7370 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7371 Style.AlignOperands = FormatStyle::OAS_Align;
7372 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7373 " bbbbbbbbbbbbbbbbbbbbbb);",
7374 Style);
7375 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7376 Style.AlignOperands = FormatStyle::OAS_DontAlign;
7377 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7378 " bbbbbbbbbbbbbbbbbbbbbb);",
7379 Style);
7380 }
7381
TEST_F(FormatTest,BreaksConditionalExpressions)7382 TEST_F(FormatTest, BreaksConditionalExpressions) {
7383 verifyFormat(
7384 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7385 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7386 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7387 verifyFormat(
7388 "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7389 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7390 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7391 verifyFormat(
7392 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7393 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7394 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7395 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7396 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7397 verifyFormat(
7398 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7399 " : aaaaaaaaaaaaa);");
7400 verifyFormat(
7401 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7402 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7403 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7404 " aaaaaaaaaaaaa);");
7405 verifyFormat(
7406 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7407 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7408 " aaaaaaaaaaaaa);");
7409 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7410 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7411 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7412 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7413 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7414 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7415 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7416 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7418 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7419 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7420 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7421 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7423 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7425 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7426 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7427 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7428 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7429 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7430 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7431 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7432 " : aaaaaaaaaaaaaaaa;");
7433 verifyFormat(
7434 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7435 " ? aaaaaaaaaaaaaaa\n"
7436 " : aaaaaaaaaaaaaaa;");
7437 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7438 " aaaaaaaaa\n"
7439 " ? b\n"
7440 " : c);");
7441 verifyFormat("return aaaa == bbbb\n"
7442 " // comment\n"
7443 " ? aaaa\n"
7444 " : bbbb;");
7445 verifyFormat("unsigned Indent =\n"
7446 " format(TheLine.First,\n"
7447 " IndentForLevel[TheLine.Level] >= 0\n"
7448 " ? IndentForLevel[TheLine.Level]\n"
7449 " : TheLine * 2,\n"
7450 " TheLine.InPPDirective, PreviousEndOfLineColumn);",
7451 getLLVMStyleWithColumns(60));
7452 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7453 " ? aaaaaaaaaaaaaaa\n"
7454 " : bbbbbbbbbbbbbbb //\n"
7455 " ? ccccccccccccccc\n"
7456 " : ddddddddddddddd;");
7457 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7458 " ? aaaaaaaaaaaaaaa\n"
7459 " : (bbbbbbbbbbbbbbb //\n"
7460 " ? ccccccccccccccc\n"
7461 " : ddddddddddddddd);");
7462 verifyFormat(
7463 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7464 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7465 " aaaaaaaaaaaaaaaaaaaaa +\n"
7466 " aaaaaaaaaaaaaaaaaaaaa\n"
7467 " : aaaaaaaaaa;");
7468 verifyFormat(
7469 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7470 " : aaaaaaaaaaaaaaaaaaaaaa\n"
7471 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7472
7473 FormatStyle NoBinPacking = getLLVMStyle();
7474 NoBinPacking.BinPackArguments = false;
7475 verifyFormat(
7476 "void f() {\n"
7477 " g(aaa,\n"
7478 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7480 " ? aaaaaaaaaaaaaaa\n"
7481 " : aaaaaaaaaaaaaaa);\n"
7482 "}",
7483 NoBinPacking);
7484 verifyFormat(
7485 "void f() {\n"
7486 " g(aaa,\n"
7487 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7488 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7489 " ?: aaaaaaaaaaaaaaa);\n"
7490 "}",
7491 NoBinPacking);
7492
7493 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7494 " // comment.\n"
7495 " ccccccccccccccccccccccccccccccccccccccc\n"
7496 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7497 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7498
7499 // Assignments in conditional expressions. Apparently not uncommon :-(.
7500 verifyFormat("return a != b\n"
7501 " // comment\n"
7502 " ? a = b\n"
7503 " : a = b;");
7504 verifyFormat("return a != b\n"
7505 " // comment\n"
7506 " ? a = a != b\n"
7507 " // comment\n"
7508 " ? a = b\n"
7509 " : a\n"
7510 " : a;\n");
7511 verifyFormat("return a != b\n"
7512 " // comment\n"
7513 " ? a\n"
7514 " : a = a != b\n"
7515 " // comment\n"
7516 " ? a = b\n"
7517 " : a;");
7518
7519 // Chained conditionals
7520 FormatStyle Style = getLLVMStyle();
7521 Style.ColumnLimit = 70;
7522 Style.AlignOperands = FormatStyle::OAS_Align;
7523 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7524 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7525 " : 3333333333333333;",
7526 Style);
7527 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7528 " : bbbbbbbbbb ? 2222222222222222\n"
7529 " : 3333333333333333;",
7530 Style);
7531 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n"
7532 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7533 " : 3333333333333333;",
7534 Style);
7535 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7536 " : bbbbbbbbbbbbbb ? 222222\n"
7537 " : 333333;",
7538 Style);
7539 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7540 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7541 " : cccccccccccccc ? 3333333333333333\n"
7542 " : 4444444444444444;",
7543 Style);
7544 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7545 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7546 " : 3333333333333333;",
7547 Style);
7548 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7549 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7550 " : (aaa ? bbb : ccc);",
7551 Style);
7552 verifyFormat(
7553 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7554 " : cccccccccccccccccc)\n"
7555 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7556 " : 3333333333333333;",
7557 Style);
7558 verifyFormat(
7559 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7560 " : cccccccccccccccccc)\n"
7561 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7562 " : 3333333333333333;",
7563 Style);
7564 verifyFormat(
7565 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7566 " : dddddddddddddddddd)\n"
7567 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7568 " : 3333333333333333;",
7569 Style);
7570 verifyFormat(
7571 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7572 " : dddddddddddddddddd)\n"
7573 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7574 " : 3333333333333333;",
7575 Style);
7576 verifyFormat(
7577 "return aaaaaaaaa ? 1111111111111111\n"
7578 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7579 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7580 " : dddddddddddddddddd)\n",
7581 Style);
7582 verifyFormat(
7583 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7584 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7585 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7586 " : cccccccccccccccccc);",
7587 Style);
7588 verifyFormat(
7589 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7590 " : ccccccccccccccc ? dddddddddddddddddd\n"
7591 " : eeeeeeeeeeeeeeeeee)\n"
7592 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7593 " : 3333333333333333;",
7594 Style);
7595 verifyFormat(
7596 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7597 " : ccccccccccccccc ? dddddddddddddddddd\n"
7598 " : eeeeeeeeeeeeeeeeee)\n"
7599 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7600 " : 3333333333333333;",
7601 Style);
7602 verifyFormat(
7603 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7604 " : cccccccccccc ? dddddddddddddddddd\n"
7605 " : eeeeeeeeeeeeeeeeee)\n"
7606 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7607 " : 3333333333333333;",
7608 Style);
7609 verifyFormat(
7610 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7611 " : cccccccccccccccccc\n"
7612 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7613 " : 3333333333333333;",
7614 Style);
7615 verifyFormat(
7616 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7617 " : cccccccccccccccc ? dddddddddddddddddd\n"
7618 " : eeeeeeeeeeeeeeeeee\n"
7619 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
7620 " : 3333333333333333;",
7621 Style);
7622 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7623 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7624 " : cccccccccccccccccc ? dddddddddddddddddd\n"
7625 " : eeeeeeeeeeeeeeeeee)\n"
7626 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7627 " : 3333333333333333;",
7628 Style);
7629 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7630 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7631 " : cccccccccccccccc ? dddddddddddddddddd\n"
7632 " : eeeeeeeeeeeeeeeeee\n"
7633 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7634 " : 3333333333333333;",
7635 Style);
7636
7637 Style.AlignOperands = FormatStyle::OAS_DontAlign;
7638 Style.BreakBeforeTernaryOperators = false;
7639 // FIXME: Aligning the question marks is weird given DontAlign.
7640 // Consider disabling this alignment in this case. Also check whether this
7641 // will render the adjustment from https://reviews.llvm.org/D82199
7642 // unnecessary.
7643 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
7644 " bbbb ? cccccccccccccccccc :\n"
7645 " ddddd;\n",
7646 Style);
7647
7648 EXPECT_EQ(
7649 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7650 " /*\n"
7651 " */\n"
7652 " function() {\n"
7653 " try {\n"
7654 " return JJJJJJJJJJJJJJ(\n"
7655 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7656 " }\n"
7657 " } :\n"
7658 " function() {};",
7659 format(
7660 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7661 " /*\n"
7662 " */\n"
7663 " function() {\n"
7664 " try {\n"
7665 " return JJJJJJJJJJJJJJ(\n"
7666 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7667 " }\n"
7668 " } :\n"
7669 " function() {};",
7670 getGoogleStyle(FormatStyle::LK_JavaScript)));
7671 }
7672
TEST_F(FormatTest,BreaksConditionalExpressionsAfterOperator)7673 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
7674 FormatStyle Style = getLLVMStyle();
7675 Style.BreakBeforeTernaryOperators = false;
7676 Style.ColumnLimit = 70;
7677 verifyFormat(
7678 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7679 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7680 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7681 Style);
7682 verifyFormat(
7683 "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7684 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7685 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7686 Style);
7687 verifyFormat(
7688 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7689 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7690 Style);
7691 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
7692 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7693 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7694 Style);
7695 verifyFormat(
7696 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
7697 " aaaaaaaaaaaaa);",
7698 Style);
7699 verifyFormat(
7700 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7701 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7702 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7703 " aaaaaaaaaaaaa);",
7704 Style);
7705 verifyFormat(
7706 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7707 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7708 " aaaaaaaaaaaaa);",
7709 Style);
7710 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7711 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7712 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7713 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7714 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7715 Style);
7716 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7717 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7718 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7719 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7720 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7721 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7722 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7723 Style);
7724 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7725 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
7726 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7727 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7728 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7729 Style);
7730 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7731 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7732 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7733 Style);
7734 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7735 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7736 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7737 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7738 Style);
7739 verifyFormat(
7740 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7741 " aaaaaaaaaaaaaaa :\n"
7742 " aaaaaaaaaaaaaaa;",
7743 Style);
7744 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7745 " aaaaaaaaa ?\n"
7746 " b :\n"
7747 " c);",
7748 Style);
7749 verifyFormat("unsigned Indent =\n"
7750 " format(TheLine.First,\n"
7751 " IndentForLevel[TheLine.Level] >= 0 ?\n"
7752 " IndentForLevel[TheLine.Level] :\n"
7753 " TheLine * 2,\n"
7754 " TheLine.InPPDirective, PreviousEndOfLineColumn);",
7755 Style);
7756 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7757 " aaaaaaaaaaaaaaa :\n"
7758 " bbbbbbbbbbbbbbb ? //\n"
7759 " ccccccccccccccc :\n"
7760 " ddddddddddddddd;",
7761 Style);
7762 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7763 " aaaaaaaaaaaaaaa :\n"
7764 " (bbbbbbbbbbbbbbb ? //\n"
7765 " ccccccccccccccc :\n"
7766 " ddddddddddddddd);",
7767 Style);
7768 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7769 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
7770 " ccccccccccccccccccccccccccc;",
7771 Style);
7772 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7773 " aaaaa :\n"
7774 " bbbbbbbbbbbbbbb + cccccccccccccccc;",
7775 Style);
7776
7777 // Chained conditionals
7778 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7779 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7780 " 3333333333333333;",
7781 Style);
7782 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7783 " bbbbbbbbbb ? 2222222222222222 :\n"
7784 " 3333333333333333;",
7785 Style);
7786 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n"
7787 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7788 " 3333333333333333;",
7789 Style);
7790 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7791 " bbbbbbbbbbbbbbbb ? 222222 :\n"
7792 " 333333;",
7793 Style);
7794 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7795 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7796 " cccccccccccccccc ? 3333333333333333 :\n"
7797 " 4444444444444444;",
7798 Style);
7799 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
7800 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7801 " 3333333333333333;",
7802 Style);
7803 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7804 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7805 " (aaa ? bbb : ccc);",
7806 Style);
7807 verifyFormat(
7808 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7809 " cccccccccccccccccc) :\n"
7810 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7811 " 3333333333333333;",
7812 Style);
7813 verifyFormat(
7814 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7815 " cccccccccccccccccc) :\n"
7816 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7817 " 3333333333333333;",
7818 Style);
7819 verifyFormat(
7820 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7821 " dddddddddddddddddd) :\n"
7822 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7823 " 3333333333333333;",
7824 Style);
7825 verifyFormat(
7826 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7827 " dddddddddddddddddd) :\n"
7828 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7829 " 3333333333333333;",
7830 Style);
7831 verifyFormat(
7832 "return aaaaaaaaa ? 1111111111111111 :\n"
7833 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7834 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7835 " dddddddddddddddddd)\n",
7836 Style);
7837 verifyFormat(
7838 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7839 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7840 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7841 " cccccccccccccccccc);",
7842 Style);
7843 verifyFormat(
7844 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7845 " ccccccccccccccccc ? dddddddddddddddddd :\n"
7846 " eeeeeeeeeeeeeeeeee) :\n"
7847 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7848 " 3333333333333333;",
7849 Style);
7850 verifyFormat(
7851 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7852 " ccccccccccccc ? dddddddddddddddddd :\n"
7853 " eeeeeeeeeeeeeeeeee) :\n"
7854 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7855 " 3333333333333333;",
7856 Style);
7857 verifyFormat(
7858 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7859 " ccccccccccccccccc ? dddddddddddddddddd :\n"
7860 " eeeeeeeeeeeeeeeeee) :\n"
7861 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7862 " 3333333333333333;",
7863 Style);
7864 verifyFormat(
7865 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7866 " cccccccccccccccccc :\n"
7867 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7868 " 3333333333333333;",
7869 Style);
7870 verifyFormat(
7871 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7872 " cccccccccccccccccc ? dddddddddddddddddd :\n"
7873 " eeeeeeeeeeeeeeeeee :\n"
7874 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7875 " 3333333333333333;",
7876 Style);
7877 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7878 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7879 " cccccccccccccccccc ? dddddddddddddddddd :\n"
7880 " eeeeeeeeeeeeeeeeee) :\n"
7881 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7882 " 3333333333333333;",
7883 Style);
7884 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7885 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7886 " cccccccccccccccccccc ? dddddddddddddddddd :\n"
7887 " eeeeeeeeeeeeeeeeee :\n"
7888 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7889 " 3333333333333333;",
7890 Style);
7891 }
7892
TEST_F(FormatTest,DeclarationsOfMultipleVariables)7893 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
7894 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
7895 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
7896 verifyFormat("bool a = true, b = false;");
7897
7898 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
7900 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
7901 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
7902 verifyFormat(
7903 "bool aaaaaaaaaaaaaaaaaaaaa =\n"
7904 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
7905 " d = e && f;");
7906 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
7907 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
7908 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7909 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
7910 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
7911 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
7912
7913 FormatStyle Style = getGoogleStyle();
7914 Style.PointerAlignment = FormatStyle::PAS_Left;
7915 Style.DerivePointerAlignment = false;
7916 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7917 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
7918 " *b = bbbbbbbbbbbbbbbbbbb;",
7919 Style);
7920 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7921 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
7922 Style);
7923 verifyFormat("vector<int*> a, b;", Style);
7924 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
7925 }
7926
TEST_F(FormatTest,ConditionalExpressionsInBrackets)7927 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
7928 verifyFormat("arr[foo ? bar : baz];");
7929 verifyFormat("f()[foo ? bar : baz];");
7930 verifyFormat("(a + b)[foo ? bar : baz];");
7931 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
7932 }
7933
TEST_F(FormatTest,AlignsStringLiterals)7934 TEST_F(FormatTest, AlignsStringLiterals) {
7935 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
7936 " \"short literal\");");
7937 verifyFormat(
7938 "looooooooooooooooooooooooongFunction(\n"
7939 " \"short literal\"\n"
7940 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
7941 verifyFormat("someFunction(\"Always break between multi-line\"\n"
7942 " \" string literals\",\n"
7943 " and, other, parameters);");
7944 EXPECT_EQ("fun + \"1243\" /* comment */\n"
7945 " \"5678\";",
7946 format("fun + \"1243\" /* comment */\n"
7947 " \"5678\";",
7948 getLLVMStyleWithColumns(28)));
7949 EXPECT_EQ(
7950 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7951 " \"aaaaaaaaaaaaaaaaaaaaa\"\n"
7952 " \"aaaaaaaaaaaaaaaa\";",
7953 format("aaaaaa ="
7954 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
7955 "aaaaaaaaaaaaaaaaaaaaa\" "
7956 "\"aaaaaaaaaaaaaaaa\";"));
7957 verifyFormat("a = a + \"a\"\n"
7958 " \"a\"\n"
7959 " \"a\";");
7960 verifyFormat("f(\"a\", \"b\"\n"
7961 " \"c\");");
7962
7963 verifyFormat(
7964 "#define LL_FORMAT \"ll\"\n"
7965 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
7966 " \"d, ddddddddd: %\" LL_FORMAT \"d\");");
7967
7968 verifyFormat("#define A(X) \\\n"
7969 " \"aaaaa\" #X \"bbbbbb\" \\\n"
7970 " \"ccccc\"",
7971 getLLVMStyleWithColumns(23));
7972 verifyFormat("#define A \"def\"\n"
7973 "f(\"abc\" A \"ghi\"\n"
7974 " \"jkl\");");
7975
7976 verifyFormat("f(L\"a\"\n"
7977 " L\"b\");");
7978 verifyFormat("#define A(X) \\\n"
7979 " L\"aaaaa\" #X L\"bbbbbb\" \\\n"
7980 " L\"ccccc\"",
7981 getLLVMStyleWithColumns(25));
7982
7983 verifyFormat("f(@\"a\"\n"
7984 " @\"b\");");
7985 verifyFormat("NSString s = @\"a\"\n"
7986 " @\"b\"\n"
7987 " @\"c\";");
7988 verifyFormat("NSString s = @\"a\"\n"
7989 " \"b\"\n"
7990 " \"c\";");
7991 }
7992
TEST_F(FormatTest,ReturnTypeBreakingStyle)7993 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
7994 FormatStyle Style = getLLVMStyle();
7995 // No declarations or definitions should be moved to own line.
7996 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
7997 verifyFormat("class A {\n"
7998 " int f() { return 1; }\n"
7999 " int g();\n"
8000 "};\n"
8001 "int f() { return 1; }\n"
8002 "int g();\n",
8003 Style);
8004
8005 // All declarations and definitions should have the return type moved to its
8006 // own line.
8007 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8008 Style.TypenameMacros = {"LIST"};
8009 verifyFormat("SomeType\n"
8010 "funcdecl(LIST(uint64_t));",
8011 Style);
8012 verifyFormat("class E {\n"
8013 " int\n"
8014 " f() {\n"
8015 " return 1;\n"
8016 " }\n"
8017 " int\n"
8018 " g();\n"
8019 "};\n"
8020 "int\n"
8021 "f() {\n"
8022 " return 1;\n"
8023 "}\n"
8024 "int\n"
8025 "g();\n",
8026 Style);
8027
8028 // Top-level definitions, and no kinds of declarations should have the
8029 // return type moved to its own line.
8030 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8031 verifyFormat("class B {\n"
8032 " int f() { return 1; }\n"
8033 " int g();\n"
8034 "};\n"
8035 "int\n"
8036 "f() {\n"
8037 " return 1;\n"
8038 "}\n"
8039 "int g();\n",
8040 Style);
8041
8042 // Top-level definitions and declarations should have the return type moved
8043 // to its own line.
8044 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8045 verifyFormat("class C {\n"
8046 " int f() { return 1; }\n"
8047 " int g();\n"
8048 "};\n"
8049 "int\n"
8050 "f() {\n"
8051 " return 1;\n"
8052 "}\n"
8053 "int\n"
8054 "g();\n",
8055 Style);
8056
8057 // All definitions should have the return type moved to its own line, but no
8058 // kinds of declarations.
8059 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8060 verifyFormat("class D {\n"
8061 " int\n"
8062 " f() {\n"
8063 " return 1;\n"
8064 " }\n"
8065 " int g();\n"
8066 "};\n"
8067 "int\n"
8068 "f() {\n"
8069 " return 1;\n"
8070 "}\n"
8071 "int g();\n",
8072 Style);
8073 verifyFormat("const char *\n"
8074 "f(void) {\n" // Break here.
8075 " return \"\";\n"
8076 "}\n"
8077 "const char *bar(void);\n", // No break here.
8078 Style);
8079 verifyFormat("template <class T>\n"
8080 "T *\n"
8081 "f(T &c) {\n" // Break here.
8082 " return NULL;\n"
8083 "}\n"
8084 "template <class T> T *f(T &c);\n", // No break here.
8085 Style);
8086 verifyFormat("class C {\n"
8087 " int\n"
8088 " operator+() {\n"
8089 " return 1;\n"
8090 " }\n"
8091 " int\n"
8092 " operator()() {\n"
8093 " return 1;\n"
8094 " }\n"
8095 "};\n",
8096 Style);
8097 verifyFormat("void\n"
8098 "A::operator()() {}\n"
8099 "void\n"
8100 "A::operator>>() {}\n"
8101 "void\n"
8102 "A::operator+() {}\n"
8103 "void\n"
8104 "A::operator*() {}\n"
8105 "void\n"
8106 "A::operator->() {}\n"
8107 "void\n"
8108 "A::operator void *() {}\n"
8109 "void\n"
8110 "A::operator void &() {}\n"
8111 "void\n"
8112 "A::operator void &&() {}\n"
8113 "void\n"
8114 "A::operator char *() {}\n"
8115 "void\n"
8116 "A::operator[]() {}\n"
8117 "void\n"
8118 "A::operator!() {}\n"
8119 "void\n"
8120 "A::operator**() {}\n"
8121 "void\n"
8122 "A::operator<Foo> *() {}\n"
8123 "void\n"
8124 "A::operator<Foo> **() {}\n"
8125 "void\n"
8126 "A::operator<Foo> &() {}\n"
8127 "void\n"
8128 "A::operator void **() {}\n",
8129 Style);
8130 verifyFormat("constexpr auto\n"
8131 "operator()() const -> reference {}\n"
8132 "constexpr auto\n"
8133 "operator>>() const -> reference {}\n"
8134 "constexpr auto\n"
8135 "operator+() const -> reference {}\n"
8136 "constexpr auto\n"
8137 "operator*() const -> reference {}\n"
8138 "constexpr auto\n"
8139 "operator->() const -> reference {}\n"
8140 "constexpr auto\n"
8141 "operator++() const -> reference {}\n"
8142 "constexpr auto\n"
8143 "operator void *() const -> reference {}\n"
8144 "constexpr auto\n"
8145 "operator void **() const -> reference {}\n"
8146 "constexpr auto\n"
8147 "operator void *() const -> reference {}\n"
8148 "constexpr auto\n"
8149 "operator void &() const -> reference {}\n"
8150 "constexpr auto\n"
8151 "operator void &&() const -> reference {}\n"
8152 "constexpr auto\n"
8153 "operator char *() const -> reference {}\n"
8154 "constexpr auto\n"
8155 "operator!() const -> reference {}\n"
8156 "constexpr auto\n"
8157 "operator[]() const -> reference {}\n",
8158 Style);
8159 verifyFormat("void *operator new(std::size_t s);", // No break here.
8160 Style);
8161 verifyFormat("void *\n"
8162 "operator new(std::size_t s) {}",
8163 Style);
8164 verifyFormat("void *\n"
8165 "operator delete[](void *ptr) {}",
8166 Style);
8167 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8168 verifyFormat("const char *\n"
8169 "f(void)\n" // Break here.
8170 "{\n"
8171 " return \"\";\n"
8172 "}\n"
8173 "const char *bar(void);\n", // No break here.
8174 Style);
8175 verifyFormat("template <class T>\n"
8176 "T *\n" // Problem here: no line break
8177 "f(T &c)\n" // Break here.
8178 "{\n"
8179 " return NULL;\n"
8180 "}\n"
8181 "template <class T> T *f(T &c);\n", // No break here.
8182 Style);
8183 verifyFormat("int\n"
8184 "foo(A<bool> a)\n"
8185 "{\n"
8186 " return a;\n"
8187 "}\n",
8188 Style);
8189 verifyFormat("int\n"
8190 "foo(A<8> a)\n"
8191 "{\n"
8192 " return a;\n"
8193 "}\n",
8194 Style);
8195 verifyFormat("int\n"
8196 "foo(A<B<bool>, 8> a)\n"
8197 "{\n"
8198 " return a;\n"
8199 "}\n",
8200 Style);
8201 verifyFormat("int\n"
8202 "foo(A<B<8>, bool> a)\n"
8203 "{\n"
8204 " return a;\n"
8205 "}\n",
8206 Style);
8207 verifyFormat("int\n"
8208 "foo(A<B<bool>, bool> a)\n"
8209 "{\n"
8210 " return a;\n"
8211 "}\n",
8212 Style);
8213 verifyFormat("int\n"
8214 "foo(A<B<8>, 8> a)\n"
8215 "{\n"
8216 " return a;\n"
8217 "}\n",
8218 Style);
8219
8220 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8221 Style.BraceWrapping.AfterFunction = true;
8222 verifyFormat("int f(i);\n" // No break here.
8223 "int\n" // Break here.
8224 "f(i)\n"
8225 "{\n"
8226 " return i + 1;\n"
8227 "}\n"
8228 "int\n" // Break here.
8229 "f(i)\n"
8230 "{\n"
8231 " return i + 1;\n"
8232 "};",
8233 Style);
8234 verifyFormat("int f(a, b, c);\n" // No break here.
8235 "int\n" // Break here.
8236 "f(a, b, c)\n" // Break here.
8237 "short a, b;\n"
8238 "float c;\n"
8239 "{\n"
8240 " return a + b < c;\n"
8241 "}\n"
8242 "int\n" // Break here.
8243 "f(a, b, c)\n" // Break here.
8244 "short a, b;\n"
8245 "float c;\n"
8246 "{\n"
8247 " return a + b < c;\n"
8248 "};",
8249 Style);
8250 verifyFormat("byte *\n" // Break here.
8251 "f(a)\n" // Break here.
8252 "byte a[];\n"
8253 "{\n"
8254 " return a;\n"
8255 "}",
8256 Style);
8257 verifyFormat("bool f(int a, int) override;\n"
8258 "Bar g(int a, Bar) final;\n"
8259 "Bar h(a, Bar) final;",
8260 Style);
8261 verifyFormat("int\n"
8262 "f(a)",
8263 Style);
8264 verifyFormat("bool\n"
8265 "f(size_t = 0, bool b = false)\n"
8266 "{\n"
8267 " return !b;\n"
8268 "}",
8269 Style);
8270
8271 // The return breaking style doesn't affect:
8272 // * function and object definitions with attribute-like macros
8273 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8274 " ABSL_GUARDED_BY(mutex) = {};",
8275 getGoogleStyleWithColumns(40));
8276 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8277 " ABSL_GUARDED_BY(mutex); // comment",
8278 getGoogleStyleWithColumns(40));
8279 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8280 " ABSL_GUARDED_BY(mutex1)\n"
8281 " ABSL_GUARDED_BY(mutex2);",
8282 getGoogleStyleWithColumns(40));
8283 verifyFormat("Tttttt f(int a, int b)\n"
8284 " ABSL_GUARDED_BY(mutex1)\n"
8285 " ABSL_GUARDED_BY(mutex2);",
8286 getGoogleStyleWithColumns(40));
8287 // * typedefs
8288 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8289
8290 Style = getGNUStyle();
8291
8292 // Test for comments at the end of function declarations.
8293 verifyFormat("void\n"
8294 "foo (int a, /*abc*/ int b) // def\n"
8295 "{\n"
8296 "}\n",
8297 Style);
8298
8299 verifyFormat("void\n"
8300 "foo (int a, /* abc */ int b) /* def */\n"
8301 "{\n"
8302 "}\n",
8303 Style);
8304
8305 // Definitions that should not break after return type
8306 verifyFormat("void foo (int a, int b); // def\n", Style);
8307 verifyFormat("void foo (int a, int b); /* def */\n", Style);
8308 verifyFormat("void foo (int a, int b);\n", Style);
8309 }
8310
TEST_F(FormatTest,AlwaysBreakBeforeMultilineStrings)8311 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8312 FormatStyle NoBreak = getLLVMStyle();
8313 NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8314 FormatStyle Break = getLLVMStyle();
8315 Break.AlwaysBreakBeforeMultilineStrings = true;
8316 verifyFormat("aaaa = \"bbbb\"\n"
8317 " \"cccc\";",
8318 NoBreak);
8319 verifyFormat("aaaa =\n"
8320 " \"bbbb\"\n"
8321 " \"cccc\";",
8322 Break);
8323 verifyFormat("aaaa(\"bbbb\"\n"
8324 " \"cccc\");",
8325 NoBreak);
8326 verifyFormat("aaaa(\n"
8327 " \"bbbb\"\n"
8328 " \"cccc\");",
8329 Break);
8330 verifyFormat("aaaa(qqq, \"bbbb\"\n"
8331 " \"cccc\");",
8332 NoBreak);
8333 verifyFormat("aaaa(qqq,\n"
8334 " \"bbbb\"\n"
8335 " \"cccc\");",
8336 Break);
8337 verifyFormat("aaaa(qqq,\n"
8338 " L\"bbbb\"\n"
8339 " L\"cccc\");",
8340 Break);
8341 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8342 " \"bbbb\"));",
8343 Break);
8344 verifyFormat("string s = someFunction(\n"
8345 " \"abc\"\n"
8346 " \"abc\");",
8347 Break);
8348
8349 // As we break before unary operators, breaking right after them is bad.
8350 verifyFormat("string foo = abc ? \"x\"\n"
8351 " \"blah blah blah blah blah blah\"\n"
8352 " : \"y\";",
8353 Break);
8354
8355 // Don't break if there is no column gain.
8356 verifyFormat("f(\"aaaa\"\n"
8357 " \"bbbb\");",
8358 Break);
8359
8360 // Treat literals with escaped newlines like multi-line string literals.
8361 EXPECT_EQ("x = \"a\\\n"
8362 "b\\\n"
8363 "c\";",
8364 format("x = \"a\\\n"
8365 "b\\\n"
8366 "c\";",
8367 NoBreak));
8368 EXPECT_EQ("xxxx =\n"
8369 " \"a\\\n"
8370 "b\\\n"
8371 "c\";",
8372 format("xxxx = \"a\\\n"
8373 "b\\\n"
8374 "c\";",
8375 Break));
8376
8377 EXPECT_EQ("NSString *const kString =\n"
8378 " @\"aaaa\"\n"
8379 " @\"bbbb\";",
8380 format("NSString *const kString = @\"aaaa\"\n"
8381 "@\"bbbb\";",
8382 Break));
8383
8384 Break.ColumnLimit = 0;
8385 verifyFormat("const char *hello = \"hello llvm\";", Break);
8386 }
8387
TEST_F(FormatTest,AlignsPipes)8388 TEST_F(FormatTest, AlignsPipes) {
8389 verifyFormat(
8390 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8391 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8392 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8393 verifyFormat(
8394 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8395 " << aaaaaaaaaaaaaaaaaaaa;");
8396 verifyFormat(
8397 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8398 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8399 verifyFormat(
8400 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8401 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8402 verifyFormat(
8403 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8404 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8405 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8406 verifyFormat(
8407 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8408 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8409 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8410 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8411 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8412 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8413 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8414 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8415 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8416 verifyFormat(
8417 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8418 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8419 verifyFormat(
8420 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8421 " aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8422
8423 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8424 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8425 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8426 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8427 " aaaaaaaaaaaaaaaaaaaaa)\n"
8428 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8429 verifyFormat("LOG_IF(aaa == //\n"
8430 " bbb)\n"
8431 " << a << b;");
8432
8433 // But sometimes, breaking before the first "<<" is desirable.
8434 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8435 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8436 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8437 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8438 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8439 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8440 " << BEF << IsTemplate << Description << E->getType();");
8441 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8442 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8443 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8444 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8445 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8446 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8447 " << aaa;");
8448
8449 verifyFormat(
8450 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8451 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8452
8453 // Incomplete string literal.
8454 EXPECT_EQ("llvm::errs() << \"\n"
8455 " << a;",
8456 format("llvm::errs() << \"\n<<a;"));
8457
8458 verifyFormat("void f() {\n"
8459 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8460 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8461 "}");
8462
8463 // Handle 'endl'.
8464 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8465 " << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8466 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8467
8468 // Handle '\n'.
8469 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8470 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8471 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8472 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8473 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8474 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8475 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8476 }
8477
TEST_F(FormatTest,KeepStringLabelValuePairsOnALine)8478 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8479 verifyFormat("return out << \"somepacket = {\\n\"\n"
8480 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8481 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8482 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8483 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8484 " << \"}\";");
8485
8486 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8487 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8488 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8489 verifyFormat(
8490 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8491 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8492 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8493 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8494 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8495 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8496 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8497 verifyFormat(
8498 "void f() {\n"
8499 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8500 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8501 "}");
8502
8503 // Breaking before the first "<<" is generally not desirable.
8504 verifyFormat(
8505 "llvm::errs()\n"
8506 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8507 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8508 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8509 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8510 getLLVMStyleWithColumns(70));
8511 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8512 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8513 " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8514 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8515 " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8516 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8517 getLLVMStyleWithColumns(70));
8518
8519 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8520 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8521 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8522 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8523 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8524 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8525 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8526 " (aaaa + aaaa);",
8527 getLLVMStyleWithColumns(40));
8528 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8529 " (aaaaaaa + aaaaa));",
8530 getLLVMStyleWithColumns(40));
8531 verifyFormat(
8532 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8533 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8534 " bbbbbbbbbbbbbbbbbbbbbbb);");
8535 }
8536
TEST_F(FormatTest,UnderstandsEquals)8537 TEST_F(FormatTest, UnderstandsEquals) {
8538 verifyFormat(
8539 "aaaaaaaaaaaaaaaaa =\n"
8540 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8541 verifyFormat(
8542 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8543 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8544 verifyFormat(
8545 "if (a) {\n"
8546 " f();\n"
8547 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8548 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8549 "}");
8550
8551 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8552 " 100000000 + 10000000) {\n}");
8553 }
8554
TEST_F(FormatTest,WrapsAtFunctionCallsIfNecessary)8555 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8556 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8557 " .looooooooooooooooooooooooooooooooooooooongFunction();");
8558
8559 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8560 " ->looooooooooooooooooooooooooooooooooooooongFunction();");
8561
8562 verifyFormat(
8563 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8564 " Parameter2);");
8565
8566 verifyFormat(
8567 "ShortObject->shortFunction(\n"
8568 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8569 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8570
8571 verifyFormat("loooooooooooooongFunction(\n"
8572 " LoooooooooooooongObject->looooooooooooooooongFunction());");
8573
8574 verifyFormat(
8575 "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8576 " ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8577
8578 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8579 " .WillRepeatedly(Return(SomeValue));");
8580 verifyFormat("void f() {\n"
8581 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8582 " .Times(2)\n"
8583 " .WillRepeatedly(Return(SomeValue));\n"
8584 "}");
8585 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8586 " ccccccccccccccccccccccc);");
8587 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8588 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8589 " .aaaaa(aaaaa),\n"
8590 " aaaaaaaaaaaaaaaaaaaaa);");
8591 verifyFormat("void f() {\n"
8592 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8593 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8594 "}");
8595 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8596 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8597 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8598 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8599 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8600 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8601 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8602 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8603 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8604 "}");
8605
8606 // Here, it is not necessary to wrap at "." or "->".
8607 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8608 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8609 verifyFormat(
8610 "aaaaaaaaaaa->aaaaaaaaa(\n"
8611 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8612 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8613
8614 verifyFormat(
8615 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8616 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8617 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8618 " aaaaaaaaa()->aaaaaa()->aaaaa());");
8619 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8620 " aaaaaaaaa()->aaaaaa()->aaaaa());");
8621
8622 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8623 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8624 " .a();");
8625
8626 FormatStyle NoBinPacking = getLLVMStyle();
8627 NoBinPacking.BinPackParameters = false;
8628 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8629 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8630 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8631 " aaaaaaaaaaaaaaaaaaa,\n"
8632 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8633 NoBinPacking);
8634
8635 // If there is a subsequent call, change to hanging indentation.
8636 verifyFormat(
8637 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8638 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
8639 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8640 verifyFormat(
8641 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8642 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
8643 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8644 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8645 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8646 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8647 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8648 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8649 }
8650
TEST_F(FormatTest,WrapsTemplateDeclarations)8651 TEST_F(FormatTest, WrapsTemplateDeclarations) {
8652 verifyFormat("template <typename T>\n"
8653 "virtual void loooooooooooongFunction(int Param1, int Param2);");
8654 verifyFormat("template <typename T>\n"
8655 "// T should be one of {A, B}.\n"
8656 "virtual void loooooooooooongFunction(int Param1, int Param2);");
8657 verifyFormat(
8658 "template <typename T>\n"
8659 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
8660 verifyFormat("template <typename T>\n"
8661 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
8662 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
8663 verifyFormat(
8664 "template <typename T>\n"
8665 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
8666 " int Paaaaaaaaaaaaaaaaaaaaram2);");
8667 verifyFormat(
8668 "template <typename T>\n"
8669 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
8670 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
8671 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8672 verifyFormat("template <typename T>\n"
8673 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8674 " int aaaaaaaaaaaaaaaaaaaaaa);");
8675 verifyFormat(
8676 "template <typename T1, typename T2 = char, typename T3 = char,\n"
8677 " typename T4 = char>\n"
8678 "void f();");
8679 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
8680 " template <typename> class cccccccccccccccccccccc,\n"
8681 " typename ddddddddddddd>\n"
8682 "class C {};");
8683 verifyFormat(
8684 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
8685 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8686
8687 verifyFormat("void f() {\n"
8688 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
8689 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
8690 "}");
8691
8692 verifyFormat("template <typename T> class C {};");
8693 verifyFormat("template <typename T> void f();");
8694 verifyFormat("template <typename T> void f() {}");
8695 verifyFormat(
8696 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8697 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8698 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
8699 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8700 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8701 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
8702 " bbbbbbbbbbbbbbbbbbbbbbbb);",
8703 getLLVMStyleWithColumns(72));
8704 EXPECT_EQ("static_cast<A< //\n"
8705 " B> *>(\n"
8706 "\n"
8707 ");",
8708 format("static_cast<A<//\n"
8709 " B>*>(\n"
8710 "\n"
8711 " );"));
8712 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8713 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
8714
8715 FormatStyle AlwaysBreak = getLLVMStyle();
8716 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
8717 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
8718 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
8719 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
8720 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8721 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8722 " ccccccccccccccccccccccccccccccccccccccccccccccc);");
8723 verifyFormat("template <template <typename> class Fooooooo,\n"
8724 " template <typename> class Baaaaaaar>\n"
8725 "struct C {};",
8726 AlwaysBreak);
8727 verifyFormat("template <typename T> // T can be A, B or C.\n"
8728 "struct C {};",
8729 AlwaysBreak);
8730 verifyFormat("template <enum E> class A {\n"
8731 "public:\n"
8732 " E *f();\n"
8733 "};");
8734
8735 FormatStyle NeverBreak = getLLVMStyle();
8736 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
8737 verifyFormat("template <typename T> class C {};", NeverBreak);
8738 verifyFormat("template <typename T> void f();", NeverBreak);
8739 verifyFormat("template <typename T> void f() {}", NeverBreak);
8740 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8741 "bbbbbbbbbbbbbbbbbbbb) {}",
8742 NeverBreak);
8743 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8744 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8745 " ccccccccccccccccccccccccccccccccccccccccccccccc);",
8746 NeverBreak);
8747 verifyFormat("template <template <typename> class Fooooooo,\n"
8748 " template <typename> class Baaaaaaar>\n"
8749 "struct C {};",
8750 NeverBreak);
8751 verifyFormat("template <typename T> // T can be A, B or C.\n"
8752 "struct C {};",
8753 NeverBreak);
8754 verifyFormat("template <enum E> class A {\n"
8755 "public:\n"
8756 " E *f();\n"
8757 "};",
8758 NeverBreak);
8759 NeverBreak.PenaltyBreakTemplateDeclaration = 100;
8760 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8761 "bbbbbbbbbbbbbbbbbbbb) {}",
8762 NeverBreak);
8763 }
8764
TEST_F(FormatTest,WrapsTemplateDeclarationsWithComments)8765 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
8766 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
8767 Style.ColumnLimit = 60;
8768 EXPECT_EQ("// Baseline - no comments.\n"
8769 "template <\n"
8770 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8771 "void f() {}",
8772 format("// Baseline - no comments.\n"
8773 "template <\n"
8774 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8775 "void f() {}",
8776 Style));
8777
8778 EXPECT_EQ("template <\n"
8779 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8780 "void f() {}",
8781 format("template <\n"
8782 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8783 "void f() {}",
8784 Style));
8785
8786 EXPECT_EQ(
8787 "template <\n"
8788 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
8789 "void f() {}",
8790 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
8791 "void f() {}",
8792 Style));
8793
8794 EXPECT_EQ(
8795 "template <\n"
8796 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8797 " // multiline\n"
8798 "void f() {}",
8799 format("template <\n"
8800 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8801 " // multiline\n"
8802 "void f() {}",
8803 Style));
8804
8805 EXPECT_EQ(
8806 "template <typename aaaaaaaaaa<\n"
8807 " bbbbbbbbbbbb>::value> // trailing loooong\n"
8808 "void f() {}",
8809 format(
8810 "template <\n"
8811 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
8812 "void f() {}",
8813 Style));
8814 }
8815
TEST_F(FormatTest,WrapsTemplateParameters)8816 TEST_F(FormatTest, WrapsTemplateParameters) {
8817 FormatStyle Style = getLLVMStyle();
8818 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8819 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8820 verifyFormat(
8821 "template <typename... a> struct q {};\n"
8822 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8823 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8824 " y;",
8825 Style);
8826 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8827 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8828 verifyFormat(
8829 "template <typename... a> struct r {};\n"
8830 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8831 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8832 " y;",
8833 Style);
8834 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8835 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8836 verifyFormat("template <typename... a> struct s {};\n"
8837 "extern s<\n"
8838 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8839 "aaaaaaaaaaaaaaaaaaaaaa,\n"
8840 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8841 "aaaaaaaaaaaaaaaaaaaaaa>\n"
8842 " y;",
8843 Style);
8844 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8845 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8846 verifyFormat("template <typename... a> struct t {};\n"
8847 "extern t<\n"
8848 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8849 "aaaaaaaaaaaaaaaaaaaaaa,\n"
8850 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8851 "aaaaaaaaaaaaaaaaaaaaaa>\n"
8852 " y;",
8853 Style);
8854 }
8855
TEST_F(FormatTest,WrapsAtNestedNameSpecifiers)8856 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
8857 verifyFormat(
8858 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8859 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8860 verifyFormat(
8861 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8862 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8863 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8864
8865 // FIXME: Should we have the extra indent after the second break?
8866 verifyFormat(
8867 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8869 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8870
8871 verifyFormat(
8872 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
8873 " cccccccccccccccccccccccccccccccccccccccccccccc());");
8874
8875 // Breaking at nested name specifiers is generally not desirable.
8876 verifyFormat(
8877 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8878 " aaaaaaaaaaaaaaaaaaaaaaa);");
8879
8880 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
8881 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8882 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8883 " aaaaaaaaaaaaaaaaaaaaa);",
8884 getLLVMStyleWithColumns(74));
8885
8886 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8887 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8888 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8889 }
8890
TEST_F(FormatTest,UnderstandsTemplateParameters)8891 TEST_F(FormatTest, UnderstandsTemplateParameters) {
8892 verifyFormat("A<int> a;");
8893 verifyFormat("A<A<A<int>>> a;");
8894 verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
8895 verifyFormat("bool x = a < 1 || 2 > a;");
8896 verifyFormat("bool x = 5 < f<int>();");
8897 verifyFormat("bool x = f<int>() > 5;");
8898 verifyFormat("bool x = 5 < a<int>::x;");
8899 verifyFormat("bool x = a < 4 ? a > 2 : false;");
8900 verifyFormat("bool x = f() ? a < 2 : a > 2;");
8901
8902 verifyGoogleFormat("A<A<int>> a;");
8903 verifyGoogleFormat("A<A<A<int>>> a;");
8904 verifyGoogleFormat("A<A<A<A<int>>>> a;");
8905 verifyGoogleFormat("A<A<int> > a;");
8906 verifyGoogleFormat("A<A<A<int> > > a;");
8907 verifyGoogleFormat("A<A<A<A<int> > > > a;");
8908 verifyGoogleFormat("A<::A<int>> a;");
8909 verifyGoogleFormat("A<::A> a;");
8910 verifyGoogleFormat("A< ::A> a;");
8911 verifyGoogleFormat("A< ::A<int> > a;");
8912 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
8913 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
8914 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
8915 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
8916 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
8917 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
8918
8919 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
8920
8921 // template closer followed by a token that starts with > or =
8922 verifyFormat("bool b = a<1> > 1;");
8923 verifyFormat("bool b = a<1> >= 1;");
8924 verifyFormat("int i = a<1> >> 1;");
8925 FormatStyle Style = getLLVMStyle();
8926 Style.SpaceBeforeAssignmentOperators = false;
8927 verifyFormat("bool b= a<1> == 1;", Style);
8928 verifyFormat("a<int> = 1;", Style);
8929 verifyFormat("a<int> >>= 1;", Style);
8930
8931 verifyFormat("test < a | b >> c;");
8932 verifyFormat("test<test<a | b>> c;");
8933 verifyFormat("test >> a >> b;");
8934 verifyFormat("test << a >> b;");
8935
8936 verifyFormat("f<int>();");
8937 verifyFormat("template <typename T> void f() {}");
8938 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
8939 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
8940 "sizeof(char)>::type>;");
8941 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
8942 verifyFormat("f(a.operator()<A>());");
8943 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8944 " .template operator()<A>());",
8945 getLLVMStyleWithColumns(35));
8946
8947 // Not template parameters.
8948 verifyFormat("return a < b && c > d;");
8949 verifyFormat("void f() {\n"
8950 " while (a < b && c > d) {\n"
8951 " }\n"
8952 "}");
8953 verifyFormat("template <typename... Types>\n"
8954 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
8955
8956 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8957 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
8958 getLLVMStyleWithColumns(60));
8959 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
8960 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
8961 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
8962 verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
8963 }
8964
TEST_F(FormatTest,UnderstandsShiftOperators)8965 TEST_F(FormatTest, UnderstandsShiftOperators) {
8966 verifyFormat("if (i < x >> 1)");
8967 verifyFormat("while (i < x >> 1)");
8968 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
8969 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
8970 verifyFormat(
8971 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
8972 verifyFormat("Foo.call<Bar<Function>>()");
8973 verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
8974 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
8975 "++i, v = v >> 1)");
8976 verifyFormat("if (w<u<v<x>>, 1>::t)");
8977 }
8978
TEST_F(FormatTest,BitshiftOperatorWidth)8979 TEST_F(FormatTest, BitshiftOperatorWidth) {
8980 EXPECT_EQ("int a = 1 << 2; /* foo\n"
8981 " bar */",
8982 format("int a=1<<2; /* foo\n"
8983 " bar */"));
8984
8985 EXPECT_EQ("int b = 256 >> 1; /* foo\n"
8986 " bar */",
8987 format("int b =256>>1 ; /* foo\n"
8988 " bar */"));
8989 }
8990
TEST_F(FormatTest,UnderstandsBinaryOperators)8991 TEST_F(FormatTest, UnderstandsBinaryOperators) {
8992 verifyFormat("COMPARE(a, ==, b);");
8993 verifyFormat("auto s = sizeof...(Ts) - 1;");
8994 }
8995
TEST_F(FormatTest,UnderstandsPointersToMembers)8996 TEST_F(FormatTest, UnderstandsPointersToMembers) {
8997 verifyFormat("int A::*x;");
8998 verifyFormat("int (S::*func)(void *);");
8999 verifyFormat("void f() { int (S::*func)(void *); }");
9000 verifyFormat("typedef bool *(Class::*Member)() const;");
9001 verifyFormat("void f() {\n"
9002 " (a->*f)();\n"
9003 " a->*x;\n"
9004 " (a.*f)();\n"
9005 " ((*a).*f)();\n"
9006 " a.*x;\n"
9007 "}");
9008 verifyFormat("void f() {\n"
9009 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9010 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9011 "}");
9012 verifyFormat(
9013 "(aaaaaaaaaa->*bbbbbbb)(\n"
9014 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9015 FormatStyle Style = getLLVMStyle();
9016 Style.PointerAlignment = FormatStyle::PAS_Left;
9017 verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9018 }
9019
TEST_F(FormatTest,UnderstandsUnaryOperators)9020 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9021 verifyFormat("int a = -2;");
9022 verifyFormat("f(-1, -2, -3);");
9023 verifyFormat("a[-1] = 5;");
9024 verifyFormat("int a = 5 + -2;");
9025 verifyFormat("if (i == -1) {\n}");
9026 verifyFormat("if (i != -1) {\n}");
9027 verifyFormat("if (i > -1) {\n}");
9028 verifyFormat("if (i < -1) {\n}");
9029 verifyFormat("++(a->f());");
9030 verifyFormat("--(a->f());");
9031 verifyFormat("(a->f())++;");
9032 verifyFormat("a[42]++;");
9033 verifyFormat("if (!(a->f())) {\n}");
9034 verifyFormat("if (!+i) {\n}");
9035 verifyFormat("~&a;");
9036
9037 verifyFormat("a-- > b;");
9038 verifyFormat("b ? -a : c;");
9039 verifyFormat("n * sizeof char16;");
9040 verifyFormat("n * alignof char16;", getGoogleStyle());
9041 verifyFormat("sizeof(char);");
9042 verifyFormat("alignof(char);", getGoogleStyle());
9043
9044 verifyFormat("return -1;");
9045 verifyFormat("throw -1;");
9046 verifyFormat("switch (a) {\n"
9047 "case -1:\n"
9048 " break;\n"
9049 "}");
9050 verifyFormat("#define X -1");
9051 verifyFormat("#define X -kConstant");
9052
9053 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9054 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9055
9056 verifyFormat("int a = /* confusing comment */ -1;");
9057 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9058 verifyFormat("int a = i /* confusing comment */++;");
9059
9060 verifyFormat("co_yield -1;");
9061 verifyFormat("co_return -1;");
9062
9063 // Check that * is not treated as a binary operator when we set
9064 // PointerAlignment as PAS_Left after a keyword and not a declaration.
9065 FormatStyle PASLeftStyle = getLLVMStyle();
9066 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9067 verifyFormat("co_return *a;", PASLeftStyle);
9068 verifyFormat("co_await *a;", PASLeftStyle);
9069 verifyFormat("co_yield *a", PASLeftStyle);
9070 verifyFormat("return *a;", PASLeftStyle);
9071 }
9072
TEST_F(FormatTest,DoesNotIndentRelativeToUnaryOperators)9073 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9074 verifyFormat("if (!aaaaaaaaaa( // break\n"
9075 " aaaaa)) {\n"
9076 "}");
9077 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9078 " aaaaa));");
9079 verifyFormat("*aaa = aaaaaaa( // break\n"
9080 " bbbbbb);");
9081 }
9082
TEST_F(FormatTest,UnderstandsOverloadedOperators)9083 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9084 verifyFormat("bool operator<();");
9085 verifyFormat("bool operator>();");
9086 verifyFormat("bool operator=();");
9087 verifyFormat("bool operator==();");
9088 verifyFormat("bool operator!=();");
9089 verifyFormat("int operator+();");
9090 verifyFormat("int operator++();");
9091 verifyFormat("int operator++(int) volatile noexcept;");
9092 verifyFormat("bool operator,();");
9093 verifyFormat("bool operator();");
9094 verifyFormat("bool operator()();");
9095 verifyFormat("bool operator[]();");
9096 verifyFormat("operator bool();");
9097 verifyFormat("operator int();");
9098 verifyFormat("operator void *();");
9099 verifyFormat("operator SomeType<int>();");
9100 verifyFormat("operator SomeType<int, int>();");
9101 verifyFormat("operator SomeType<SomeType<int>>();");
9102 verifyFormat("void *operator new(std::size_t size);");
9103 verifyFormat("void *operator new[](std::size_t size);");
9104 verifyFormat("void operator delete(void *ptr);");
9105 verifyFormat("void operator delete[](void *ptr);");
9106 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9107 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9108 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9109 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9110
9111 verifyFormat(
9112 "ostream &operator<<(ostream &OutputStream,\n"
9113 " SomeReallyLongType WithSomeReallyLongValue);");
9114 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9115 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9116 " return left.group < right.group;\n"
9117 "}");
9118 verifyFormat("SomeType &operator=(const SomeType &S);");
9119 verifyFormat("f.template operator()<int>();");
9120
9121 verifyGoogleFormat("operator void*();");
9122 verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9123 verifyGoogleFormat("operator ::A();");
9124
9125 verifyFormat("using A::operator+;");
9126 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9127 "int i;");
9128
9129 // Calling an operator as a member function.
9130 verifyFormat("void f() { a.operator*(); }");
9131 verifyFormat("void f() { a.operator*(b & b); }");
9132 verifyFormat("void f() { a->operator&(a * b); }");
9133 verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9134 // TODO: Calling an operator as a non-member function is hard to distinguish.
9135 // https://llvm.org/PR50629
9136 // verifyFormat("void f() { operator*(a & a); }");
9137 // verifyFormat("void f() { operator&(a, b * b); }");
9138 }
9139
TEST_F(FormatTest,UnderstandsFunctionRefQualification)9140 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9141 verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9142 verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9143 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9144 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9145 verifyFormat("Deleted &operator=(const Deleted &) &;");
9146 verifyFormat("Deleted &operator=(const Deleted &) &&;");
9147 verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9148 verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9149 verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9150 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9151 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9152 verifyFormat("void Fn(T const &) const &;");
9153 verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9154 verifyFormat("template <typename T>\n"
9155 "void F(T) && = delete;",
9156 getGoogleStyle());
9157
9158 FormatStyle AlignLeft = getLLVMStyle();
9159 AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9160 verifyFormat("void A::b() && {}", AlignLeft);
9161 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9162 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9163 AlignLeft);
9164 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9165 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9166 verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9167 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9168 verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9169 verifyFormat("auto Function(T) & -> void;", AlignLeft);
9170 verifyFormat("void Fn(T const&) const&;", AlignLeft);
9171 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9172
9173 FormatStyle Spaces = getLLVMStyle();
9174 Spaces.SpacesInCStyleCastParentheses = true;
9175 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9176 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9177 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9178 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9179
9180 Spaces.SpacesInCStyleCastParentheses = false;
9181 Spaces.SpacesInParentheses = true;
9182 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9183 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9184 Spaces);
9185 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9186 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9187
9188 FormatStyle BreakTemplate = getLLVMStyle();
9189 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9190
9191 verifyFormat("struct f {\n"
9192 " template <class T>\n"
9193 " int &foo(const std::string &str) &noexcept {}\n"
9194 "};",
9195 BreakTemplate);
9196
9197 verifyFormat("struct f {\n"
9198 " template <class T>\n"
9199 " int &foo(const std::string &str) &&noexcept {}\n"
9200 "};",
9201 BreakTemplate);
9202
9203 verifyFormat("struct f {\n"
9204 " template <class T>\n"
9205 " int &foo(const std::string &str) const &noexcept {}\n"
9206 "};",
9207 BreakTemplate);
9208
9209 verifyFormat("struct f {\n"
9210 " template <class T>\n"
9211 " int &foo(const std::string &str) const &noexcept {}\n"
9212 "};",
9213 BreakTemplate);
9214
9215 verifyFormat("struct f {\n"
9216 " template <class T>\n"
9217 " auto foo(const std::string &str) &&noexcept -> int & {}\n"
9218 "};",
9219 BreakTemplate);
9220
9221 FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9222 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9223 FormatStyle::BTDS_Yes;
9224 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9225
9226 verifyFormat("struct f {\n"
9227 " template <class T>\n"
9228 " int& foo(const std::string& str) & noexcept {}\n"
9229 "};",
9230 AlignLeftBreakTemplate);
9231
9232 verifyFormat("struct f {\n"
9233 " template <class T>\n"
9234 " int& foo(const std::string& str) && noexcept {}\n"
9235 "};",
9236 AlignLeftBreakTemplate);
9237
9238 verifyFormat("struct f {\n"
9239 " template <class T>\n"
9240 " int& foo(const std::string& str) const& noexcept {}\n"
9241 "};",
9242 AlignLeftBreakTemplate);
9243
9244 verifyFormat("struct f {\n"
9245 " template <class T>\n"
9246 " int& foo(const std::string& str) const&& noexcept {}\n"
9247 "};",
9248 AlignLeftBreakTemplate);
9249
9250 verifyFormat("struct f {\n"
9251 " template <class T>\n"
9252 " auto foo(const std::string& str) && noexcept -> int& {}\n"
9253 "};",
9254 AlignLeftBreakTemplate);
9255
9256 // The `&` in `Type&` should not be confused with a trailing `&` of
9257 // DEPRECATED(reason) member function.
9258 verifyFormat("struct f {\n"
9259 " template <class T>\n"
9260 " DEPRECATED(reason)\n"
9261 " Type &foo(arguments) {}\n"
9262 "};",
9263 BreakTemplate);
9264
9265 verifyFormat("struct f {\n"
9266 " template <class T>\n"
9267 " DEPRECATED(reason)\n"
9268 " Type& foo(arguments) {}\n"
9269 "};",
9270 AlignLeftBreakTemplate);
9271
9272 verifyFormat("void (*foopt)(int) = &func;");
9273 }
9274
TEST_F(FormatTest,UnderstandsNewAndDelete)9275 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9276 verifyFormat("void f() {\n"
9277 " A *a = new A;\n"
9278 " A *a = new (placement) A;\n"
9279 " delete a;\n"
9280 " delete (A *)a;\n"
9281 "}");
9282 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9283 " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9284 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9285 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9286 " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9287 verifyFormat("delete[] h->p;");
9288 }
9289
TEST_F(FormatTest,UnderstandsUsesOfStarAndAmp)9290 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9291 verifyFormat("int *f(int *a) {}");
9292 verifyFormat("int main(int argc, char **argv) {}");
9293 verifyFormat("Test::Test(int b) : a(b * b) {}");
9294 verifyIndependentOfContext("f(a, *a);");
9295 verifyFormat("void g() { f(*a); }");
9296 verifyIndependentOfContext("int a = b * 10;");
9297 verifyIndependentOfContext("int a = 10 * b;");
9298 verifyIndependentOfContext("int a = b * c;");
9299 verifyIndependentOfContext("int a += b * c;");
9300 verifyIndependentOfContext("int a -= b * c;");
9301 verifyIndependentOfContext("int a *= b * c;");
9302 verifyIndependentOfContext("int a /= b * c;");
9303 verifyIndependentOfContext("int a = *b;");
9304 verifyIndependentOfContext("int a = *b * c;");
9305 verifyIndependentOfContext("int a = b * *c;");
9306 verifyIndependentOfContext("int a = b * (10);");
9307 verifyIndependentOfContext("S << b * (10);");
9308 verifyIndependentOfContext("return 10 * b;");
9309 verifyIndependentOfContext("return *b * *c;");
9310 verifyIndependentOfContext("return a & ~b;");
9311 verifyIndependentOfContext("f(b ? *c : *d);");
9312 verifyIndependentOfContext("int a = b ? *c : *d;");
9313 verifyIndependentOfContext("*b = a;");
9314 verifyIndependentOfContext("a * ~b;");
9315 verifyIndependentOfContext("a * !b;");
9316 verifyIndependentOfContext("a * +b;");
9317 verifyIndependentOfContext("a * -b;");
9318 verifyIndependentOfContext("a * ++b;");
9319 verifyIndependentOfContext("a * --b;");
9320 verifyIndependentOfContext("a[4] * b;");
9321 verifyIndependentOfContext("a[a * a] = 1;");
9322 verifyIndependentOfContext("f() * b;");
9323 verifyIndependentOfContext("a * [self dostuff];");
9324 verifyIndependentOfContext("int x = a * (a + b);");
9325 verifyIndependentOfContext("(a *)(a + b);");
9326 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9327 verifyIndependentOfContext("int *pa = (int *)&a;");
9328 verifyIndependentOfContext("return sizeof(int **);");
9329 verifyIndependentOfContext("return sizeof(int ******);");
9330 verifyIndependentOfContext("return (int **&)a;");
9331 verifyIndependentOfContext("f((*PointerToArray)[10]);");
9332 verifyFormat("void f(Type (*parameter)[10]) {}");
9333 verifyFormat("void f(Type (¶meter)[10]) {}");
9334 verifyGoogleFormat("return sizeof(int**);");
9335 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9336 verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9337 verifyFormat("auto a = [](int **&, int ***) {};");
9338 verifyFormat("auto PointerBinding = [](const char *S) {};");
9339 verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9340 verifyFormat("[](const decltype(*a) &value) {}");
9341 verifyFormat("[](const typeof(*a) &value) {}");
9342 verifyFormat("[](const _Atomic(a *) &value) {}");
9343 verifyFormat("[](const __underlying_type(a) &value) {}");
9344 verifyFormat("decltype(a * b) F();");
9345 verifyFormat("typeof(a * b) F();");
9346 verifyFormat("#define MACRO() [](A *a) { return 1; }");
9347 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9348 verifyIndependentOfContext("typedef void (*f)(int *a);");
9349 verifyIndependentOfContext("int i{a * b};");
9350 verifyIndependentOfContext("aaa && aaa->f();");
9351 verifyIndependentOfContext("int x = ~*p;");
9352 verifyFormat("Constructor() : a(a), area(width * height) {}");
9353 verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9354 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9355 verifyFormat("void f() { f(a, c * d); }");
9356 verifyFormat("void f() { f(new a(), c * d); }");
9357 verifyFormat("void f(const MyOverride &override);");
9358 verifyFormat("void f(const MyFinal &final);");
9359 verifyIndependentOfContext("bool a = f() && override.f();");
9360 verifyIndependentOfContext("bool a = f() && final.f();");
9361
9362 verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9363
9364 verifyIndependentOfContext("A<int *> a;");
9365 verifyIndependentOfContext("A<int **> a;");
9366 verifyIndependentOfContext("A<int *, int *> a;");
9367 verifyIndependentOfContext("A<int *[]> a;");
9368 verifyIndependentOfContext(
9369 "const char *const p = reinterpret_cast<const char *const>(q);");
9370 verifyIndependentOfContext("A<int **, int **> a;");
9371 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9372 verifyFormat("for (char **a = b; *a; ++a) {\n}");
9373 verifyFormat("for (; a && b;) {\n}");
9374 verifyFormat("bool foo = true && [] { return false; }();");
9375
9376 verifyFormat(
9377 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9378 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9379
9380 verifyGoogleFormat("int const* a = &b;");
9381 verifyGoogleFormat("**outparam = 1;");
9382 verifyGoogleFormat("*outparam = a * b;");
9383 verifyGoogleFormat("int main(int argc, char** argv) {}");
9384 verifyGoogleFormat("A<int*> a;");
9385 verifyGoogleFormat("A<int**> a;");
9386 verifyGoogleFormat("A<int*, int*> a;");
9387 verifyGoogleFormat("A<int**, int**> a;");
9388 verifyGoogleFormat("f(b ? *c : *d);");
9389 verifyGoogleFormat("int a = b ? *c : *d;");
9390 verifyGoogleFormat("Type* t = **x;");
9391 verifyGoogleFormat("Type* t = *++*x;");
9392 verifyGoogleFormat("*++*x;");
9393 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9394 verifyGoogleFormat("Type* t = x++ * y;");
9395 verifyGoogleFormat(
9396 "const char* const p = reinterpret_cast<const char* const>(q);");
9397 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9398 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9399 verifyGoogleFormat("template <typename T>\n"
9400 "void f(int i = 0, SomeType** temps = NULL);");
9401
9402 FormatStyle Left = getLLVMStyle();
9403 Left.PointerAlignment = FormatStyle::PAS_Left;
9404 verifyFormat("x = *a(x) = *a(y);", Left);
9405 verifyFormat("for (;; *a = b) {\n}", Left);
9406 verifyFormat("return *this += 1;", Left);
9407 verifyFormat("throw *x;", Left);
9408 verifyFormat("delete *x;", Left);
9409 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9410 verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9411 verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9412 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9413 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9414 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9415 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9416 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9417 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9418
9419 verifyIndependentOfContext("a = *(x + y);");
9420 verifyIndependentOfContext("a = &(x + y);");
9421 verifyIndependentOfContext("*(x + y).call();");
9422 verifyIndependentOfContext("&(x + y)->call();");
9423 verifyFormat("void f() { &(*I).first; }");
9424
9425 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9426 verifyFormat(
9427 "int *MyValues = {\n"
9428 " *A, // Operator detection might be confused by the '{'\n"
9429 " *BB // Operator detection might be confused by previous comment\n"
9430 "};");
9431
9432 verifyIndependentOfContext("if (int *a = &b)");
9433 verifyIndependentOfContext("if (int &a = *b)");
9434 verifyIndependentOfContext("if (a & b[i])");
9435 verifyIndependentOfContext("if constexpr (a & b[i])");
9436 verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9437 verifyIndependentOfContext("if (a * (b * c))");
9438 verifyIndependentOfContext("if constexpr (a * (b * c))");
9439 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9440 verifyIndependentOfContext("if (a::b::c::d & b[i])");
9441 verifyIndependentOfContext("if (*b[i])");
9442 verifyIndependentOfContext("if (int *a = (&b))");
9443 verifyIndependentOfContext("while (int *a = &b)");
9444 verifyIndependentOfContext("while (a * (b * c))");
9445 verifyIndependentOfContext("size = sizeof *a;");
9446 verifyIndependentOfContext("if (a && (b = c))");
9447 verifyFormat("void f() {\n"
9448 " for (const int &v : Values) {\n"
9449 " }\n"
9450 "}");
9451 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9452 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9453 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9454
9455 verifyFormat("#define A (!a * b)");
9456 verifyFormat("#define MACRO \\\n"
9457 " int *i = a * b; \\\n"
9458 " void f(a *b);",
9459 getLLVMStyleWithColumns(19));
9460
9461 verifyIndependentOfContext("A = new SomeType *[Length];");
9462 verifyIndependentOfContext("A = new SomeType *[Length]();");
9463 verifyIndependentOfContext("T **t = new T *;");
9464 verifyIndependentOfContext("T **t = new T *();");
9465 verifyGoogleFormat("A = new SomeType*[Length]();");
9466 verifyGoogleFormat("A = new SomeType*[Length];");
9467 verifyGoogleFormat("T** t = new T*;");
9468 verifyGoogleFormat("T** t = new T*();");
9469
9470 verifyFormat("STATIC_ASSERT((a & b) == 0);");
9471 verifyFormat("STATIC_ASSERT(0 == (a & b));");
9472 verifyFormat("template <bool a, bool b> "
9473 "typename t::if<x && y>::type f() {}");
9474 verifyFormat("template <int *y> f() {}");
9475 verifyFormat("vector<int *> v;");
9476 verifyFormat("vector<int *const> v;");
9477 verifyFormat("vector<int *const **const *> v;");
9478 verifyFormat("vector<int *volatile> v;");
9479 verifyFormat("vector<a *_Nonnull> v;");
9480 verifyFormat("vector<a *_Nullable> v;");
9481 verifyFormat("vector<a *_Null_unspecified> v;");
9482 verifyFormat("vector<a *__ptr32> v;");
9483 verifyFormat("vector<a *__ptr64> v;");
9484 verifyFormat("vector<a *__capability> v;");
9485 FormatStyle TypeMacros = getLLVMStyle();
9486 TypeMacros.TypenameMacros = {"LIST"};
9487 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9488 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9489 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9490 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9491 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9492
9493 FormatStyle CustomQualifier = getLLVMStyle();
9494 // Add identifiers that should not be parsed as a qualifier by default.
9495 CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9496 CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9497 CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9498 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9499 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9500 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9501 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9502 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9503 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9504 verifyFormat("vector<a * _NotAQualifier> v;");
9505 verifyFormat("vector<a * __not_a_qualifier> v;");
9506 verifyFormat("vector<a * b> v;");
9507 verifyFormat("foo<b && false>();");
9508 verifyFormat("foo<b & 1>();");
9509 verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9510 verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9511 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9512 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9513 verifyFormat(
9514 "template <class T, class = typename std::enable_if<\n"
9515 " std::is_integral<T>::value &&\n"
9516 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9517 "void F();",
9518 getLLVMStyleWithColumns(70));
9519 verifyFormat("template <class T,\n"
9520 " class = typename std::enable_if<\n"
9521 " std::is_integral<T>::value &&\n"
9522 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9523 " class U>\n"
9524 "void F();",
9525 getLLVMStyleWithColumns(70));
9526 verifyFormat(
9527 "template <class T,\n"
9528 " class = typename ::std::enable_if<\n"
9529 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9530 "void F();",
9531 getGoogleStyleWithColumns(68));
9532
9533 verifyIndependentOfContext("MACRO(int *i);");
9534 verifyIndependentOfContext("MACRO(auto *a);");
9535 verifyIndependentOfContext("MACRO(const A *a);");
9536 verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9537 verifyIndependentOfContext("MACRO(decltype(A) *a);");
9538 verifyIndependentOfContext("MACRO(typeof(A) *a);");
9539 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9540 verifyIndependentOfContext("MACRO(A *const a);");
9541 verifyIndependentOfContext("MACRO(A *restrict a);");
9542 verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9543 verifyIndependentOfContext("MACRO(A *__restrict a);");
9544 verifyIndependentOfContext("MACRO(A *volatile a);");
9545 verifyIndependentOfContext("MACRO(A *__volatile a);");
9546 verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9547 verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9548 verifyIndependentOfContext("MACRO(A *_Nullable a);");
9549 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9550 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9551 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9552 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9553 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9554 verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9555 verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9556 verifyIndependentOfContext("MACRO(A *__capability);");
9557 verifyIndependentOfContext("MACRO(A &__capability);");
9558 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration
9559 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9560 // If we add __my_qualifier to AttributeMacros it should always be parsed as
9561 // a type declaration:
9562 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9563 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9564 // Also check that TypenameMacros prevents parsing it as multiplication:
9565 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9566 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9567
9568 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9569 verifyFormat("void f() { f(float{1}, a * a); }");
9570 verifyFormat("void f() { f(float(1), a * a); }");
9571
9572 verifyFormat("f((void (*)(int))g);");
9573 verifyFormat("f((void (&)(int))g);");
9574 verifyFormat("f((void (^)(int))g);");
9575
9576 // FIXME: Is there a way to make this work?
9577 // verifyIndependentOfContext("MACRO(A *a);");
9578 verifyFormat("MACRO(A &B);");
9579 verifyFormat("MACRO(A *B);");
9580 verifyFormat("void f() { MACRO(A * B); }");
9581 verifyFormat("void f() { MACRO(A & B); }");
9582
9583 // This lambda was mis-formatted after D88956 (treating it as a binop):
9584 verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9585 verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9586 verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9587 verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9588
9589 verifyFormat("DatumHandle const *operator->() const { return input_; }");
9590 verifyFormat("return options != nullptr && operator==(*options);");
9591
9592 EXPECT_EQ("#define OP(x) \\\n"
9593 " ostream &operator<<(ostream &s, const A &a) { \\\n"
9594 " return s << a.DebugString(); \\\n"
9595 " }",
9596 format("#define OP(x) \\\n"
9597 " ostream &operator<<(ostream &s, const A &a) { \\\n"
9598 " return s << a.DebugString(); \\\n"
9599 " }",
9600 getLLVMStyleWithColumns(50)));
9601
9602 // FIXME: We cannot handle this case yet; we might be able to figure out that
9603 // foo<x> d > v; doesn't make sense.
9604 verifyFormat("foo<a<b && c> d> v;");
9605
9606 FormatStyle PointerMiddle = getLLVMStyle();
9607 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9608 verifyFormat("delete *x;", PointerMiddle);
9609 verifyFormat("int * x;", PointerMiddle);
9610 verifyFormat("int *[] x;", PointerMiddle);
9611 verifyFormat("template <int * y> f() {}", PointerMiddle);
9612 verifyFormat("int * f(int * a) {}", PointerMiddle);
9613 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9614 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
9615 verifyFormat("A<int *> a;", PointerMiddle);
9616 verifyFormat("A<int **> a;", PointerMiddle);
9617 verifyFormat("A<int *, int *> a;", PointerMiddle);
9618 verifyFormat("A<int *[]> a;", PointerMiddle);
9619 verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
9620 verifyFormat("A = new SomeType *[Length];", PointerMiddle);
9621 verifyFormat("T ** t = new T *;", PointerMiddle);
9622
9623 // Member function reference qualifiers aren't binary operators.
9624 verifyFormat("string // break\n"
9625 "operator()() & {}");
9626 verifyFormat("string // break\n"
9627 "operator()() && {}");
9628 verifyGoogleFormat("template <typename T>\n"
9629 "auto x() & -> int {}");
9630
9631 // Should be binary operators when used as an argument expression (overloaded
9632 // operator invoked as a member function).
9633 verifyFormat("void f() { a.operator()(a * a); }");
9634 verifyFormat("void f() { a->operator()(a & a); }");
9635 verifyFormat("void f() { a.operator()(*a & *a); }");
9636 verifyFormat("void f() { a->operator()(*a * *a); }");
9637 }
9638
TEST_F(FormatTest,UnderstandsAttributes)9639 TEST_F(FormatTest, UnderstandsAttributes) {
9640 verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
9641 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
9642 "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9643 FormatStyle AfterType = getLLVMStyle();
9644 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
9645 verifyFormat("__attribute__((nodebug)) void\n"
9646 "foo() {}\n",
9647 AfterType);
9648 verifyFormat("__unused void\n"
9649 "foo() {}",
9650 AfterType);
9651
9652 FormatStyle CustomAttrs = getLLVMStyle();
9653 CustomAttrs.AttributeMacros.push_back("__unused");
9654 CustomAttrs.AttributeMacros.push_back("__attr1");
9655 CustomAttrs.AttributeMacros.push_back("__attr2");
9656 CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
9657 verifyFormat("vector<SomeType *__attribute((foo))> v;");
9658 verifyFormat("vector<SomeType *__attribute__((foo))> v;");
9659 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
9660 // Check that it is parsed as a multiplication without AttributeMacros and
9661 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
9662 verifyFormat("vector<SomeType * __attr1> v;");
9663 verifyFormat("vector<SomeType __attr1 *> v;");
9664 verifyFormat("vector<SomeType __attr1 *const> v;");
9665 verifyFormat("vector<SomeType __attr1 * __attr2> v;");
9666 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
9667 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
9668 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
9669 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
9670 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
9671 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
9672 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
9673
9674 // Check that these are not parsed as function declarations:
9675 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9676 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
9677 verifyFormat("SomeType s(InitValue);", CustomAttrs);
9678 verifyFormat("SomeType s{InitValue};", CustomAttrs);
9679 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
9680 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
9681 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
9682 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
9683 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
9684 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
9685 }
9686
TEST_F(FormatTest,UnderstandsPointerQualifiersInCast)9687 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
9688 // Check that qualifiers on pointers don't break parsing of casts.
9689 verifyFormat("x = (foo *const)*v;");
9690 verifyFormat("x = (foo *volatile)*v;");
9691 verifyFormat("x = (foo *restrict)*v;");
9692 verifyFormat("x = (foo *__attribute__((foo)))*v;");
9693 verifyFormat("x = (foo *_Nonnull)*v;");
9694 verifyFormat("x = (foo *_Nullable)*v;");
9695 verifyFormat("x = (foo *_Null_unspecified)*v;");
9696 verifyFormat("x = (foo *_Nonnull)*v;");
9697 verifyFormat("x = (foo *[[clang::attr]])*v;");
9698 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
9699 verifyFormat("x = (foo *__ptr32)*v;");
9700 verifyFormat("x = (foo *__ptr64)*v;");
9701 verifyFormat("x = (foo *__capability)*v;");
9702
9703 // Check that we handle multiple trailing qualifiers and skip them all to
9704 // determine that the expression is a cast to a pointer type.
9705 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
9706 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
9707 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
9708 StringRef AllQualifiers =
9709 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
9710 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
9711 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
9712 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
9713
9714 // Also check that address-of is not parsed as a binary bitwise-and:
9715 verifyFormat("x = (foo *const)&v;");
9716 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
9717 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
9718
9719 // Check custom qualifiers:
9720 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
9721 CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9722 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
9723 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
9724 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
9725 CustomQualifier);
9726 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
9727 CustomQualifier);
9728
9729 // Check that unknown identifiers result in binary operator parsing:
9730 verifyFormat("x = (foo * __unknown_qualifier) * v;");
9731 verifyFormat("x = (foo * __unknown_qualifier) & v;");
9732 }
9733
TEST_F(FormatTest,UnderstandsSquareAttributes)9734 TEST_F(FormatTest, UnderstandsSquareAttributes) {
9735 verifyFormat("SomeType s [[unused]] (InitValue);");
9736 verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
9737 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
9738 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
9739 verifyFormat("void f() [[deprecated(\"so sorry\")]];");
9740 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9741 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9742 verifyFormat("[[nodiscard]] bool f() { return false; }");
9743 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}");
9744 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}");
9745 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}");
9746
9747 // Make sure we do not mistake attributes for array subscripts.
9748 verifyFormat("int a() {}\n"
9749 "[[unused]] int b() {}\n");
9750 verifyFormat("NSArray *arr;\n"
9751 "arr[[Foo() bar]];");
9752
9753 // On the other hand, we still need to correctly find array subscripts.
9754 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
9755
9756 // Make sure that we do not mistake Objective-C method inside array literals
9757 // as attributes, even if those method names are also keywords.
9758 verifyFormat("@[ [foo bar] ];");
9759 verifyFormat("@[ [NSArray class] ];");
9760 verifyFormat("@[ [foo enum] ];");
9761
9762 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
9763
9764 // Make sure we do not parse attributes as lambda introducers.
9765 FormatStyle MultiLineFunctions = getLLVMStyle();
9766 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9767 verifyFormat("[[unused]] int b() {\n"
9768 " return 42;\n"
9769 "}\n",
9770 MultiLineFunctions);
9771 }
9772
TEST_F(FormatTest,AttributeClass)9773 TEST_F(FormatTest, AttributeClass) {
9774 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
9775 verifyFormat("class S {\n"
9776 " S(S&&) = default;\n"
9777 "};",
9778 Style);
9779 verifyFormat("class [[nodiscard]] S {\n"
9780 " S(S&&) = default;\n"
9781 "};",
9782 Style);
9783 verifyFormat("class __attribute((maybeunused)) S {\n"
9784 " S(S&&) = default;\n"
9785 "};",
9786 Style);
9787 verifyFormat("struct S {\n"
9788 " S(S&&) = default;\n"
9789 "};",
9790 Style);
9791 verifyFormat("struct [[nodiscard]] S {\n"
9792 " S(S&&) = default;\n"
9793 "};",
9794 Style);
9795 }
9796
TEST_F(FormatTest,AttributesAfterMacro)9797 TEST_F(FormatTest, AttributesAfterMacro) {
9798 FormatStyle Style = getLLVMStyle();
9799 verifyFormat("MACRO;\n"
9800 "__attribute__((maybe_unused)) int foo() {\n"
9801 " //...\n"
9802 "}");
9803
9804 verifyFormat("MACRO;\n"
9805 "[[nodiscard]] int foo() {\n"
9806 " //...\n"
9807 "}");
9808
9809 EXPECT_EQ("MACRO\n\n"
9810 "__attribute__((maybe_unused)) int foo() {\n"
9811 " //...\n"
9812 "}",
9813 format("MACRO\n\n"
9814 "__attribute__((maybe_unused)) int foo() {\n"
9815 " //...\n"
9816 "}"));
9817
9818 EXPECT_EQ("MACRO\n\n"
9819 "[[nodiscard]] int foo() {\n"
9820 " //...\n"
9821 "}",
9822 format("MACRO\n\n"
9823 "[[nodiscard]] int foo() {\n"
9824 " //...\n"
9825 "}"));
9826 }
9827
TEST_F(FormatTest,AttributePenaltyBreaking)9828 TEST_F(FormatTest, AttributePenaltyBreaking) {
9829 FormatStyle Style = getLLVMStyle();
9830 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
9831 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
9832 Style);
9833 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
9834 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
9835 Style);
9836 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
9837 "shared_ptr<ALongTypeName> &C d) {\n}",
9838 Style);
9839 }
9840
TEST_F(FormatTest,UnderstandsEllipsis)9841 TEST_F(FormatTest, UnderstandsEllipsis) {
9842 FormatStyle Style = getLLVMStyle();
9843 verifyFormat("int printf(const char *fmt, ...);");
9844 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
9845 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
9846
9847 verifyFormat("template <int *...PP> a;", Style);
9848
9849 Style.PointerAlignment = FormatStyle::PAS_Left;
9850 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
9851
9852 verifyFormat("template <int*... PP> a;", Style);
9853
9854 Style.PointerAlignment = FormatStyle::PAS_Middle;
9855 verifyFormat("template <int *... PP> a;", Style);
9856 }
9857
TEST_F(FormatTest,AdaptivelyFormatsPointersAndReferences)9858 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
9859 EXPECT_EQ("int *a;\n"
9860 "int *a;\n"
9861 "int *a;",
9862 format("int *a;\n"
9863 "int* a;\n"
9864 "int *a;",
9865 getGoogleStyle()));
9866 EXPECT_EQ("int* a;\n"
9867 "int* a;\n"
9868 "int* a;",
9869 format("int* a;\n"
9870 "int* a;\n"
9871 "int *a;",
9872 getGoogleStyle()));
9873 EXPECT_EQ("int *a;\n"
9874 "int *a;\n"
9875 "int *a;",
9876 format("int *a;\n"
9877 "int * a;\n"
9878 "int * a;",
9879 getGoogleStyle()));
9880 EXPECT_EQ("auto x = [] {\n"
9881 " int *a;\n"
9882 " int *a;\n"
9883 " int *a;\n"
9884 "};",
9885 format("auto x=[]{int *a;\n"
9886 "int * a;\n"
9887 "int * a;};",
9888 getGoogleStyle()));
9889 }
9890
TEST_F(FormatTest,UnderstandsRvalueReferences)9891 TEST_F(FormatTest, UnderstandsRvalueReferences) {
9892 verifyFormat("int f(int &&a) {}");
9893 verifyFormat("int f(int a, char &&b) {}");
9894 verifyFormat("void f() { int &&a = b; }");
9895 verifyGoogleFormat("int f(int a, char&& b) {}");
9896 verifyGoogleFormat("void f() { int&& a = b; }");
9897
9898 verifyIndependentOfContext("A<int &&> a;");
9899 verifyIndependentOfContext("A<int &&, int &&> a;");
9900 verifyGoogleFormat("A<int&&> a;");
9901 verifyGoogleFormat("A<int&&, int&&> a;");
9902
9903 // Not rvalue references:
9904 verifyFormat("template <bool B, bool C> class A {\n"
9905 " static_assert(B && C, \"Something is wrong\");\n"
9906 "};");
9907 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
9908 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
9909 verifyFormat("#define A(a, b) (a && b)");
9910 }
9911
TEST_F(FormatTest,FormatsBinaryOperatorsPrecedingEquals)9912 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
9913 verifyFormat("void f() {\n"
9914 " x[aaaaaaaaa -\n"
9915 " b] = 23;\n"
9916 "}",
9917 getLLVMStyleWithColumns(15));
9918 }
9919
TEST_F(FormatTest,FormatsCasts)9920 TEST_F(FormatTest, FormatsCasts) {
9921 verifyFormat("Type *A = static_cast<Type *>(P);");
9922 verifyFormat("Type *A = (Type *)P;");
9923 verifyFormat("Type *A = (vector<Type *, int *>)P;");
9924 verifyFormat("int a = (int)(2.0f);");
9925 verifyFormat("int a = (int)2.0f;");
9926 verifyFormat("x[(int32)y];");
9927 verifyFormat("x = (int32)y;");
9928 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
9929 verifyFormat("int a = (int)*b;");
9930 verifyFormat("int a = (int)2.0f;");
9931 verifyFormat("int a = (int)~0;");
9932 verifyFormat("int a = (int)++a;");
9933 verifyFormat("int a = (int)sizeof(int);");
9934 verifyFormat("int a = (int)+2;");
9935 verifyFormat("my_int a = (my_int)2.0f;");
9936 verifyFormat("my_int a = (my_int)sizeof(int);");
9937 verifyFormat("return (my_int)aaa;");
9938 verifyFormat("#define x ((int)-1)");
9939 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
9940 verifyFormat("#define p(q) ((int *)&q)");
9941 verifyFormat("fn(a)(b) + 1;");
9942
9943 verifyFormat("void f() { my_int a = (my_int)*b; }");
9944 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
9945 verifyFormat("my_int a = (my_int)~0;");
9946 verifyFormat("my_int a = (my_int)++a;");
9947 verifyFormat("my_int a = (my_int)-2;");
9948 verifyFormat("my_int a = (my_int)1;");
9949 verifyFormat("my_int a = (my_int *)1;");
9950 verifyFormat("my_int a = (const my_int)-1;");
9951 verifyFormat("my_int a = (const my_int *)-1;");
9952 verifyFormat("my_int a = (my_int)(my_int)-1;");
9953 verifyFormat("my_int a = (ns::my_int)-2;");
9954 verifyFormat("case (my_int)ONE:");
9955 verifyFormat("auto x = (X)this;");
9956 // Casts in Obj-C style calls used to not be recognized as such.
9957 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
9958
9959 // FIXME: single value wrapped with paren will be treated as cast.
9960 verifyFormat("void f(int i = (kValue)*kMask) {}");
9961
9962 verifyFormat("{ (void)F; }");
9963
9964 // Don't break after a cast's
9965 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9966 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
9967 " bbbbbbbbbbbbbbbbbbbbbb);");
9968
9969 // These are not casts.
9970 verifyFormat("void f(int *) {}");
9971 verifyFormat("f(foo)->b;");
9972 verifyFormat("f(foo).b;");
9973 verifyFormat("f(foo)(b);");
9974 verifyFormat("f(foo)[b];");
9975 verifyFormat("[](foo) { return 4; }(bar);");
9976 verifyFormat("(*funptr)(foo)[4];");
9977 verifyFormat("funptrs[4](foo)[4];");
9978 verifyFormat("void f(int *);");
9979 verifyFormat("void f(int *) = 0;");
9980 verifyFormat("void f(SmallVector<int>) {}");
9981 verifyFormat("void f(SmallVector<int>);");
9982 verifyFormat("void f(SmallVector<int>) = 0;");
9983 verifyFormat("void f(int i = (kA * kB) & kMask) {}");
9984 verifyFormat("int a = sizeof(int) * b;");
9985 verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
9986 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
9987 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
9988 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
9989
9990 // These are not casts, but at some point were confused with casts.
9991 verifyFormat("virtual void foo(int *) override;");
9992 verifyFormat("virtual void foo(char &) const;");
9993 verifyFormat("virtual void foo(int *a, char *) const;");
9994 verifyFormat("int a = sizeof(int *) + b;");
9995 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
9996 verifyFormat("bool b = f(g<int>) && c;");
9997 verifyFormat("typedef void (*f)(int i) func;");
9998 verifyFormat("void operator++(int) noexcept;");
9999 verifyFormat("void operator++(int &) noexcept;");
10000 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10001 "&) noexcept;");
10002 verifyFormat(
10003 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10004 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10005 verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10006 verifyFormat("void operator delete(nothrow_t &) noexcept;");
10007 verifyFormat("void operator delete(foo &) noexcept;");
10008 verifyFormat("void operator delete(foo) noexcept;");
10009 verifyFormat("void operator delete(int) noexcept;");
10010 verifyFormat("void operator delete(int &) noexcept;");
10011 verifyFormat("void operator delete(int &) volatile noexcept;");
10012 verifyFormat("void operator delete(int &) const");
10013 verifyFormat("void operator delete(int &) = default");
10014 verifyFormat("void operator delete(int &) = delete");
10015 verifyFormat("void operator delete(int &) [[noreturn]]");
10016 verifyFormat("void operator delete(int &) throw();");
10017 verifyFormat("void operator delete(int &) throw(int);");
10018 verifyFormat("auto operator delete(int &) -> int;");
10019 verifyFormat("auto operator delete(int &) override");
10020 verifyFormat("auto operator delete(int &) final");
10021
10022 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10023 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10024 // FIXME: The indentation here is not ideal.
10025 verifyFormat(
10026 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10027 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10028 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10029 }
10030
TEST_F(FormatTest,FormatsFunctionTypes)10031 TEST_F(FormatTest, FormatsFunctionTypes) {
10032 verifyFormat("A<bool()> a;");
10033 verifyFormat("A<SomeType()> a;");
10034 verifyFormat("A<void (*)(int, std::string)> a;");
10035 verifyFormat("A<void *(int)>;");
10036 verifyFormat("void *(*a)(int *, SomeType *);");
10037 verifyFormat("int (*func)(void *);");
10038 verifyFormat("void f() { int (*func)(void *); }");
10039 verifyFormat("template <class CallbackClass>\n"
10040 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10041
10042 verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10043 verifyGoogleFormat("void* (*a)(int);");
10044 verifyGoogleFormat(
10045 "template <class CallbackClass>\n"
10046 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10047
10048 // Other constructs can look somewhat like function types:
10049 verifyFormat("A<sizeof(*x)> a;");
10050 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10051 verifyFormat("some_var = function(*some_pointer_var)[0];");
10052 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10053 verifyFormat("int x = f(&h)();");
10054 verifyFormat("returnsFunction(¶m1, ¶m2)(param);");
10055 verifyFormat("std::function<\n"
10056 " LooooooooooongTemplatedType<\n"
10057 " SomeType>*(\n"
10058 " LooooooooooooooooongType type)>\n"
10059 " function;",
10060 getGoogleStyleWithColumns(40));
10061 }
10062
TEST_F(FormatTest,FormatsPointersToArrayTypes)10063 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10064 verifyFormat("A (*foo_)[6];");
10065 verifyFormat("vector<int> (*foo_)[6];");
10066 }
10067
TEST_F(FormatTest,BreaksLongVariableDeclarations)10068 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10069 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10070 " LoooooooooooooooooooooooooooooooooooooooongVariable;");
10071 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10072 " LoooooooooooooooooooooooooooooooooooooooongVariable;");
10073 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10074 " *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10075
10076 // Different ways of ()-initializiation.
10077 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10078 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10079 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10080 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10081 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10082 " LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10083 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10084 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10085
10086 // Lambdas should not confuse the variable declaration heuristic.
10087 verifyFormat("LooooooooooooooooongType\n"
10088 " variable(nullptr, [](A *a) {});",
10089 getLLVMStyleWithColumns(40));
10090 }
10091
TEST_F(FormatTest,BreaksLongDeclarations)10092 TEST_F(FormatTest, BreaksLongDeclarations) {
10093 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10094 " AnotherNameForTheLongType;");
10095 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10096 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10097 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10098 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10099 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10100 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10101 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10102 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10103 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10104 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10105 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10106 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10107 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10108 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10109 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10110 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10111 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10112 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10113 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10114 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10115 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10116 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10117 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10118 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10119 FormatStyle Indented = getLLVMStyle();
10120 Indented.IndentWrappedFunctionNames = true;
10121 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10122 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10123 Indented);
10124 verifyFormat(
10125 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10126 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10127 Indented);
10128 verifyFormat(
10129 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10130 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10131 Indented);
10132 verifyFormat(
10133 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10134 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10135 Indented);
10136
10137 // FIXME: Without the comment, this breaks after "(".
10138 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n"
10139 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10140 getGoogleStyle());
10141
10142 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10143 " int LoooooooooooooooooooongParam2) {}");
10144 verifyFormat(
10145 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10146 " SourceLocation L, IdentifierIn *II,\n"
10147 " Type *T) {}");
10148 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10149 "ReallyReaaallyLongFunctionName(\n"
10150 " const std::string &SomeParameter,\n"
10151 " const SomeType<string, SomeOtherTemplateParameter>\n"
10152 " &ReallyReallyLongParameterName,\n"
10153 " const SomeType<string, SomeOtherTemplateParameter>\n"
10154 " &AnotherLongParameterName) {}");
10155 verifyFormat("template <typename A>\n"
10156 "SomeLoooooooooooooooooooooongType<\n"
10157 " typename some_namespace::SomeOtherType<A>::Type>\n"
10158 "Function() {}");
10159
10160 verifyGoogleFormat(
10161 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10162 " aaaaaaaaaaaaaaaaaaaaaaa;");
10163 verifyGoogleFormat(
10164 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10165 " SourceLocation L) {}");
10166 verifyGoogleFormat(
10167 "some_namespace::LongReturnType\n"
10168 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10169 " int first_long_parameter, int second_parameter) {}");
10170
10171 verifyGoogleFormat("template <typename T>\n"
10172 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10173 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10174 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10175 " int aaaaaaaaaaaaaaaaaaaaaaa);");
10176
10177 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10178 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10179 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10180 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10181 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10182 " aaaaaaaaaaaaaaaaaaaaaaaa);");
10183 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10184 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10185 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10187
10188 verifyFormat("template <typename T> // Templates on own line.\n"
10189 "static int // Some comment.\n"
10190 "MyFunction(int a);",
10191 getLLVMStyle());
10192 }
10193
TEST_F(FormatTest,FormatsAccessModifiers)10194 TEST_F(FormatTest, FormatsAccessModifiers) {
10195 FormatStyle Style = getLLVMStyle();
10196 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10197 FormatStyle::ELBAMS_LogicalBlock);
10198 verifyFormat("struct foo {\n"
10199 "private:\n"
10200 " void f() {}\n"
10201 "\n"
10202 "private:\n"
10203 " int i;\n"
10204 "\n"
10205 "protected:\n"
10206 " int j;\n"
10207 "};\n",
10208 Style);
10209 verifyFormat("struct foo {\n"
10210 "private:\n"
10211 " void f() {}\n"
10212 "\n"
10213 "private:\n"
10214 " int i;\n"
10215 "\n"
10216 "protected:\n"
10217 " int j;\n"
10218 "};\n",
10219 "struct foo {\n"
10220 "private:\n"
10221 " void f() {}\n"
10222 "private:\n"
10223 " int i;\n"
10224 "protected:\n"
10225 " int j;\n"
10226 "};\n",
10227 Style);
10228 verifyFormat("struct foo { /* comment */\n"
10229 "private:\n"
10230 " int i;\n"
10231 " // comment\n"
10232 "private:\n"
10233 " int j;\n"
10234 "};\n",
10235 Style);
10236 verifyFormat("struct foo {\n"
10237 "#ifdef FOO\n"
10238 "#endif\n"
10239 "private:\n"
10240 " int i;\n"
10241 "#ifdef FOO\n"
10242 "private:\n"
10243 "#endif\n"
10244 " int j;\n"
10245 "};\n",
10246 Style);
10247 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10248 verifyFormat("struct foo {\n"
10249 "private:\n"
10250 " void f() {}\n"
10251 "private:\n"
10252 " int i;\n"
10253 "protected:\n"
10254 " int j;\n"
10255 "};\n",
10256 Style);
10257 verifyFormat("struct foo {\n"
10258 "private:\n"
10259 " void f() {}\n"
10260 "private:\n"
10261 " int i;\n"
10262 "protected:\n"
10263 " int j;\n"
10264 "};\n",
10265 "struct foo {\n"
10266 "\n"
10267 "private:\n"
10268 " void f() {}\n"
10269 "\n"
10270 "private:\n"
10271 " int i;\n"
10272 "\n"
10273 "protected:\n"
10274 " int j;\n"
10275 "};\n",
10276 Style);
10277 verifyFormat("struct foo { /* comment */\n"
10278 "private:\n"
10279 " int i;\n"
10280 " // comment\n"
10281 "private:\n"
10282 " int j;\n"
10283 "};\n",
10284 "struct foo { /* comment */\n"
10285 "\n"
10286 "private:\n"
10287 " int i;\n"
10288 " // comment\n"
10289 "\n"
10290 "private:\n"
10291 " int j;\n"
10292 "};\n",
10293 Style);
10294 verifyFormat("struct foo {\n"
10295 "#ifdef FOO\n"
10296 "#endif\n"
10297 "private:\n"
10298 " int i;\n"
10299 "#ifdef FOO\n"
10300 "private:\n"
10301 "#endif\n"
10302 " int j;\n"
10303 "};\n",
10304 "struct foo {\n"
10305 "#ifdef FOO\n"
10306 "#endif\n"
10307 "\n"
10308 "private:\n"
10309 " int i;\n"
10310 "#ifdef FOO\n"
10311 "\n"
10312 "private:\n"
10313 "#endif\n"
10314 " int j;\n"
10315 "};\n",
10316 Style);
10317 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10318 verifyFormat("struct foo {\n"
10319 "private:\n"
10320 " void f() {}\n"
10321 "\n"
10322 "private:\n"
10323 " int i;\n"
10324 "\n"
10325 "protected:\n"
10326 " int j;\n"
10327 "};\n",
10328 Style);
10329 verifyFormat("struct foo {\n"
10330 "private:\n"
10331 " void f() {}\n"
10332 "\n"
10333 "private:\n"
10334 " int i;\n"
10335 "\n"
10336 "protected:\n"
10337 " int j;\n"
10338 "};\n",
10339 "struct foo {\n"
10340 "private:\n"
10341 " void f() {}\n"
10342 "private:\n"
10343 " int i;\n"
10344 "protected:\n"
10345 " int j;\n"
10346 "};\n",
10347 Style);
10348 verifyFormat("struct foo { /* comment */\n"
10349 "private:\n"
10350 " int i;\n"
10351 " // comment\n"
10352 "\n"
10353 "private:\n"
10354 " int j;\n"
10355 "};\n",
10356 "struct foo { /* comment */\n"
10357 "private:\n"
10358 " int i;\n"
10359 " // comment\n"
10360 "\n"
10361 "private:\n"
10362 " int j;\n"
10363 "};\n",
10364 Style);
10365 verifyFormat("struct foo {\n"
10366 "#ifdef FOO\n"
10367 "#endif\n"
10368 "\n"
10369 "private:\n"
10370 " int i;\n"
10371 "#ifdef FOO\n"
10372 "\n"
10373 "private:\n"
10374 "#endif\n"
10375 " int j;\n"
10376 "};\n",
10377 "struct foo {\n"
10378 "#ifdef FOO\n"
10379 "#endif\n"
10380 "private:\n"
10381 " int i;\n"
10382 "#ifdef FOO\n"
10383 "private:\n"
10384 "#endif\n"
10385 " int j;\n"
10386 "};\n",
10387 Style);
10388 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10389 EXPECT_EQ("struct foo {\n"
10390 "\n"
10391 "private:\n"
10392 " void f() {}\n"
10393 "\n"
10394 "private:\n"
10395 " int i;\n"
10396 "\n"
10397 "protected:\n"
10398 " int j;\n"
10399 "};\n",
10400 format("struct foo {\n"
10401 "\n"
10402 "private:\n"
10403 " void f() {}\n"
10404 "\n"
10405 "private:\n"
10406 " int i;\n"
10407 "\n"
10408 "protected:\n"
10409 " int j;\n"
10410 "};\n",
10411 Style));
10412 verifyFormat("struct foo {\n"
10413 "private:\n"
10414 " void f() {}\n"
10415 "private:\n"
10416 " int i;\n"
10417 "protected:\n"
10418 " int j;\n"
10419 "};\n",
10420 Style);
10421 EXPECT_EQ("struct foo { /* comment */\n"
10422 "\n"
10423 "private:\n"
10424 " int i;\n"
10425 " // comment\n"
10426 "\n"
10427 "private:\n"
10428 " int j;\n"
10429 "};\n",
10430 format("struct foo { /* comment */\n"
10431 "\n"
10432 "private:\n"
10433 " int i;\n"
10434 " // comment\n"
10435 "\n"
10436 "private:\n"
10437 " int j;\n"
10438 "};\n",
10439 Style));
10440 verifyFormat("struct foo { /* comment */\n"
10441 "private:\n"
10442 " int i;\n"
10443 " // comment\n"
10444 "private:\n"
10445 " int j;\n"
10446 "};\n",
10447 Style);
10448 EXPECT_EQ("struct foo {\n"
10449 "#ifdef FOO\n"
10450 "#endif\n"
10451 "\n"
10452 "private:\n"
10453 " int i;\n"
10454 "#ifdef FOO\n"
10455 "\n"
10456 "private:\n"
10457 "#endif\n"
10458 " int j;\n"
10459 "};\n",
10460 format("struct foo {\n"
10461 "#ifdef FOO\n"
10462 "#endif\n"
10463 "\n"
10464 "private:\n"
10465 " int i;\n"
10466 "#ifdef FOO\n"
10467 "\n"
10468 "private:\n"
10469 "#endif\n"
10470 " int j;\n"
10471 "};\n",
10472 Style));
10473 verifyFormat("struct foo {\n"
10474 "#ifdef FOO\n"
10475 "#endif\n"
10476 "private:\n"
10477 " int i;\n"
10478 "#ifdef FOO\n"
10479 "private:\n"
10480 "#endif\n"
10481 " int j;\n"
10482 "};\n",
10483 Style);
10484
10485 FormatStyle NoEmptyLines = getLLVMStyle();
10486 NoEmptyLines.MaxEmptyLinesToKeep = 0;
10487 verifyFormat("struct foo {\n"
10488 "private:\n"
10489 " void f() {}\n"
10490 "\n"
10491 "private:\n"
10492 " int i;\n"
10493 "\n"
10494 "public:\n"
10495 "protected:\n"
10496 " int j;\n"
10497 "};\n",
10498 NoEmptyLines);
10499
10500 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10501 verifyFormat("struct foo {\n"
10502 "private:\n"
10503 " void f() {}\n"
10504 "private:\n"
10505 " int i;\n"
10506 "public:\n"
10507 "protected:\n"
10508 " int j;\n"
10509 "};\n",
10510 NoEmptyLines);
10511
10512 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10513 verifyFormat("struct foo {\n"
10514 "private:\n"
10515 " void f() {}\n"
10516 "\n"
10517 "private:\n"
10518 " int i;\n"
10519 "\n"
10520 "public:\n"
10521 "\n"
10522 "protected:\n"
10523 " int j;\n"
10524 "};\n",
10525 NoEmptyLines);
10526 }
10527
TEST_F(FormatTest,FormatsAfterAccessModifiers)10528 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10529
10530 FormatStyle Style = getLLVMStyle();
10531 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10532 verifyFormat("struct foo {\n"
10533 "private:\n"
10534 " void f() {}\n"
10535 "\n"
10536 "private:\n"
10537 " int i;\n"
10538 "\n"
10539 "protected:\n"
10540 " int j;\n"
10541 "};\n",
10542 Style);
10543
10544 // Check if lines are removed.
10545 verifyFormat("struct foo {\n"
10546 "private:\n"
10547 " void f() {}\n"
10548 "\n"
10549 "private:\n"
10550 " int i;\n"
10551 "\n"
10552 "protected:\n"
10553 " int j;\n"
10554 "};\n",
10555 "struct foo {\n"
10556 "private:\n"
10557 "\n"
10558 " void f() {}\n"
10559 "\n"
10560 "private:\n"
10561 "\n"
10562 " int i;\n"
10563 "\n"
10564 "protected:\n"
10565 "\n"
10566 " int j;\n"
10567 "};\n",
10568 Style);
10569
10570 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10571 verifyFormat("struct foo {\n"
10572 "private:\n"
10573 "\n"
10574 " void f() {}\n"
10575 "\n"
10576 "private:\n"
10577 "\n"
10578 " int i;\n"
10579 "\n"
10580 "protected:\n"
10581 "\n"
10582 " int j;\n"
10583 "};\n",
10584 Style);
10585
10586 // Check if lines are added.
10587 verifyFormat("struct foo {\n"
10588 "private:\n"
10589 "\n"
10590 " void f() {}\n"
10591 "\n"
10592 "private:\n"
10593 "\n"
10594 " int i;\n"
10595 "\n"
10596 "protected:\n"
10597 "\n"
10598 " int j;\n"
10599 "};\n",
10600 "struct foo {\n"
10601 "private:\n"
10602 " void f() {}\n"
10603 "\n"
10604 "private:\n"
10605 " int i;\n"
10606 "\n"
10607 "protected:\n"
10608 " int j;\n"
10609 "};\n",
10610 Style);
10611
10612 // Leave tests rely on the code layout, test::messUp can not be used.
10613 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10614 Style.MaxEmptyLinesToKeep = 0u;
10615 verifyFormat("struct foo {\n"
10616 "private:\n"
10617 " void f() {}\n"
10618 "\n"
10619 "private:\n"
10620 " int i;\n"
10621 "\n"
10622 "protected:\n"
10623 " int j;\n"
10624 "};\n",
10625 Style);
10626
10627 // Check if MaxEmptyLinesToKeep is respected.
10628 EXPECT_EQ("struct foo {\n"
10629 "private:\n"
10630 " void f() {}\n"
10631 "\n"
10632 "private:\n"
10633 " int i;\n"
10634 "\n"
10635 "protected:\n"
10636 " int j;\n"
10637 "};\n",
10638 format("struct foo {\n"
10639 "private:\n"
10640 "\n\n\n"
10641 " void f() {}\n"
10642 "\n"
10643 "private:\n"
10644 "\n\n\n"
10645 " int i;\n"
10646 "\n"
10647 "protected:\n"
10648 "\n\n\n"
10649 " int j;\n"
10650 "};\n",
10651 Style));
10652
10653 Style.MaxEmptyLinesToKeep = 1u;
10654 EXPECT_EQ("struct foo {\n"
10655 "private:\n"
10656 "\n"
10657 " void f() {}\n"
10658 "\n"
10659 "private:\n"
10660 "\n"
10661 " int i;\n"
10662 "\n"
10663 "protected:\n"
10664 "\n"
10665 " int j;\n"
10666 "};\n",
10667 format("struct foo {\n"
10668 "private:\n"
10669 "\n"
10670 " void f() {}\n"
10671 "\n"
10672 "private:\n"
10673 "\n"
10674 " int i;\n"
10675 "\n"
10676 "protected:\n"
10677 "\n"
10678 " int j;\n"
10679 "};\n",
10680 Style));
10681 // Check if no lines are kept.
10682 EXPECT_EQ("struct foo {\n"
10683 "private:\n"
10684 " void f() {}\n"
10685 "\n"
10686 "private:\n"
10687 " int i;\n"
10688 "\n"
10689 "protected:\n"
10690 " int j;\n"
10691 "};\n",
10692 format("struct foo {\n"
10693 "private:\n"
10694 " void f() {}\n"
10695 "\n"
10696 "private:\n"
10697 " int i;\n"
10698 "\n"
10699 "protected:\n"
10700 " int j;\n"
10701 "};\n",
10702 Style));
10703 // Check if MaxEmptyLinesToKeep is respected.
10704 EXPECT_EQ("struct foo {\n"
10705 "private:\n"
10706 "\n"
10707 " void f() {}\n"
10708 "\n"
10709 "private:\n"
10710 "\n"
10711 " int i;\n"
10712 "\n"
10713 "protected:\n"
10714 "\n"
10715 " int j;\n"
10716 "};\n",
10717 format("struct foo {\n"
10718 "private:\n"
10719 "\n\n\n"
10720 " void f() {}\n"
10721 "\n"
10722 "private:\n"
10723 "\n\n\n"
10724 " int i;\n"
10725 "\n"
10726 "protected:\n"
10727 "\n\n\n"
10728 " int j;\n"
10729 "};\n",
10730 Style));
10731
10732 Style.MaxEmptyLinesToKeep = 10u;
10733 EXPECT_EQ("struct foo {\n"
10734 "private:\n"
10735 "\n\n\n"
10736 " void f() {}\n"
10737 "\n"
10738 "private:\n"
10739 "\n\n\n"
10740 " int i;\n"
10741 "\n"
10742 "protected:\n"
10743 "\n\n\n"
10744 " int j;\n"
10745 "};\n",
10746 format("struct foo {\n"
10747 "private:\n"
10748 "\n\n\n"
10749 " void f() {}\n"
10750 "\n"
10751 "private:\n"
10752 "\n\n\n"
10753 " int i;\n"
10754 "\n"
10755 "protected:\n"
10756 "\n\n\n"
10757 " int j;\n"
10758 "};\n",
10759 Style));
10760
10761 // Test with comments.
10762 Style = getLLVMStyle();
10763 verifyFormat("struct foo {\n"
10764 "private:\n"
10765 " // comment\n"
10766 " void f() {}\n"
10767 "\n"
10768 "private: /* comment */\n"
10769 " int i;\n"
10770 "};\n",
10771 Style);
10772 verifyFormat("struct foo {\n"
10773 "private:\n"
10774 " // comment\n"
10775 " void f() {}\n"
10776 "\n"
10777 "private: /* comment */\n"
10778 " int i;\n"
10779 "};\n",
10780 "struct foo {\n"
10781 "private:\n"
10782 "\n"
10783 " // comment\n"
10784 " void f() {}\n"
10785 "\n"
10786 "private: /* comment */\n"
10787 "\n"
10788 " int i;\n"
10789 "};\n",
10790 Style);
10791
10792 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10793 verifyFormat("struct foo {\n"
10794 "private:\n"
10795 "\n"
10796 " // comment\n"
10797 " void f() {}\n"
10798 "\n"
10799 "private: /* comment */\n"
10800 "\n"
10801 " int i;\n"
10802 "};\n",
10803 "struct foo {\n"
10804 "private:\n"
10805 " // comment\n"
10806 " void f() {}\n"
10807 "\n"
10808 "private: /* comment */\n"
10809 " int i;\n"
10810 "};\n",
10811 Style);
10812 verifyFormat("struct foo {\n"
10813 "private:\n"
10814 "\n"
10815 " // comment\n"
10816 " void f() {}\n"
10817 "\n"
10818 "private: /* comment */\n"
10819 "\n"
10820 " int i;\n"
10821 "};\n",
10822 Style);
10823
10824 // Test with preprocessor defines.
10825 Style = getLLVMStyle();
10826 verifyFormat("struct foo {\n"
10827 "private:\n"
10828 "#ifdef FOO\n"
10829 "#endif\n"
10830 " void f() {}\n"
10831 "};\n",
10832 Style);
10833 verifyFormat("struct foo {\n"
10834 "private:\n"
10835 "#ifdef FOO\n"
10836 "#endif\n"
10837 " void f() {}\n"
10838 "};\n",
10839 "struct foo {\n"
10840 "private:\n"
10841 "\n"
10842 "#ifdef FOO\n"
10843 "#endif\n"
10844 " void f() {}\n"
10845 "};\n",
10846 Style);
10847
10848 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10849 verifyFormat("struct foo {\n"
10850 "private:\n"
10851 "\n"
10852 "#ifdef FOO\n"
10853 "#endif\n"
10854 " void f() {}\n"
10855 "};\n",
10856 "struct foo {\n"
10857 "private:\n"
10858 "#ifdef FOO\n"
10859 "#endif\n"
10860 " void f() {}\n"
10861 "};\n",
10862 Style);
10863 verifyFormat("struct foo {\n"
10864 "private:\n"
10865 "\n"
10866 "#ifdef FOO\n"
10867 "#endif\n"
10868 " void f() {}\n"
10869 "};\n",
10870 Style);
10871 }
10872
TEST_F(FormatTest,FormatsAfterAndBeforeAccessModifiersInteraction)10873 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
10874 // Combined tests of EmptyLineAfterAccessModifier and
10875 // EmptyLineBeforeAccessModifier.
10876 FormatStyle Style = getLLVMStyle();
10877 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10878 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10879 verifyFormat("struct foo {\n"
10880 "private:\n"
10881 "\n"
10882 "protected:\n"
10883 "};\n",
10884 Style);
10885
10886 Style.MaxEmptyLinesToKeep = 10u;
10887 // Both remove all new lines.
10888 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10889 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10890 verifyFormat("struct foo {\n"
10891 "private:\n"
10892 "protected:\n"
10893 "};\n",
10894 "struct foo {\n"
10895 "private:\n"
10896 "\n\n\n"
10897 "protected:\n"
10898 "};\n",
10899 Style);
10900
10901 // Leave tests rely on the code layout, test::messUp can not be used.
10902 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10903 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10904 Style.MaxEmptyLinesToKeep = 10u;
10905 EXPECT_EQ("struct foo {\n"
10906 "private:\n"
10907 "\n\n\n"
10908 "protected:\n"
10909 "};\n",
10910 format("struct foo {\n"
10911 "private:\n"
10912 "\n\n\n"
10913 "protected:\n"
10914 "};\n",
10915 Style));
10916 Style.MaxEmptyLinesToKeep = 3u;
10917 EXPECT_EQ("struct foo {\n"
10918 "private:\n"
10919 "\n\n\n"
10920 "protected:\n"
10921 "};\n",
10922 format("struct foo {\n"
10923 "private:\n"
10924 "\n\n\n"
10925 "protected:\n"
10926 "};\n",
10927 Style));
10928 Style.MaxEmptyLinesToKeep = 1u;
10929 EXPECT_EQ("struct foo {\n"
10930 "private:\n"
10931 "\n\n\n"
10932 "protected:\n"
10933 "};\n",
10934 format("struct foo {\n"
10935 "private:\n"
10936 "\n\n\n"
10937 "protected:\n"
10938 "};\n",
10939 Style)); // Based on new lines in original document and not
10940 // on the setting.
10941
10942 Style.MaxEmptyLinesToKeep = 10u;
10943 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10944 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10945 // Newlines are kept if they are greater than zero,
10946 // test::messUp removes all new lines which changes the logic
10947 EXPECT_EQ("struct foo {\n"
10948 "private:\n"
10949 "\n\n\n"
10950 "protected:\n"
10951 "};\n",
10952 format("struct foo {\n"
10953 "private:\n"
10954 "\n\n\n"
10955 "protected:\n"
10956 "};\n",
10957 Style));
10958
10959 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10960 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10961 // test::messUp removes all new lines which changes the logic
10962 EXPECT_EQ("struct foo {\n"
10963 "private:\n"
10964 "\n\n\n"
10965 "protected:\n"
10966 "};\n",
10967 format("struct foo {\n"
10968 "private:\n"
10969 "\n\n\n"
10970 "protected:\n"
10971 "};\n",
10972 Style));
10973
10974 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10975 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10976 EXPECT_EQ("struct foo {\n"
10977 "private:\n"
10978 "\n\n\n"
10979 "protected:\n"
10980 "};\n",
10981 format("struct foo {\n"
10982 "private:\n"
10983 "\n\n\n"
10984 "protected:\n"
10985 "};\n",
10986 Style)); // test::messUp removes all new lines which changes
10987 // the logic.
10988
10989 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10990 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10991 verifyFormat("struct foo {\n"
10992 "private:\n"
10993 "protected:\n"
10994 "};\n",
10995 "struct foo {\n"
10996 "private:\n"
10997 "\n\n\n"
10998 "protected:\n"
10999 "};\n",
11000 Style);
11001
11002 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11003 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11004 EXPECT_EQ("struct foo {\n"
11005 "private:\n"
11006 "\n\n\n"
11007 "protected:\n"
11008 "};\n",
11009 format("struct foo {\n"
11010 "private:\n"
11011 "\n\n\n"
11012 "protected:\n"
11013 "};\n",
11014 Style)); // test::messUp removes all new lines which changes
11015 // the logic.
11016
11017 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11018 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11019 verifyFormat("struct foo {\n"
11020 "private:\n"
11021 "protected:\n"
11022 "};\n",
11023 "struct foo {\n"
11024 "private:\n"
11025 "\n\n\n"
11026 "protected:\n"
11027 "};\n",
11028 Style);
11029
11030 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11031 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11032 verifyFormat("struct foo {\n"
11033 "private:\n"
11034 "protected:\n"
11035 "};\n",
11036 "struct foo {\n"
11037 "private:\n"
11038 "\n\n\n"
11039 "protected:\n"
11040 "};\n",
11041 Style);
11042
11043 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11044 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11045 verifyFormat("struct foo {\n"
11046 "private:\n"
11047 "protected:\n"
11048 "};\n",
11049 "struct foo {\n"
11050 "private:\n"
11051 "\n\n\n"
11052 "protected:\n"
11053 "};\n",
11054 Style);
11055
11056 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11057 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11058 verifyFormat("struct foo {\n"
11059 "private:\n"
11060 "protected:\n"
11061 "};\n",
11062 "struct foo {\n"
11063 "private:\n"
11064 "\n\n\n"
11065 "protected:\n"
11066 "};\n",
11067 Style);
11068 }
11069
TEST_F(FormatTest,FormatsArrays)11070 TEST_F(FormatTest, FormatsArrays) {
11071 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11072 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11073 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11074 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11075 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11076 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11077 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11078 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11079 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11080 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11081 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11082 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11083 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11084 verifyFormat(
11085 "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11086 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11087 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11088 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11089 " .aaaaaaaaaaaaaaaaaaaaaa();");
11090
11091 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11092 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11093 verifyFormat(
11094 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11095 " .aaaaaaa[0]\n"
11096 " .aaaaaaaaaaaaaaaaaaaaaa();");
11097 verifyFormat("a[::b::c];");
11098
11099 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11100
11101 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11102 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11103 }
11104
TEST_F(FormatTest,LineStartsWithSpecialCharacter)11105 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11106 verifyFormat("(a)->b();");
11107 verifyFormat("--a;");
11108 }
11109
TEST_F(FormatTest,HandlesIncludeDirectives)11110 TEST_F(FormatTest, HandlesIncludeDirectives) {
11111 verifyFormat("#include <string>\n"
11112 "#include <a/b/c.h>\n"
11113 "#include \"a/b/string\"\n"
11114 "#include \"string.h\"\n"
11115 "#include \"string.h\"\n"
11116 "#include <a-a>\n"
11117 "#include < path with space >\n"
11118 "#include_next <test.h>"
11119 "#include \"abc.h\" // this is included for ABC\n"
11120 "#include \"some long include\" // with a comment\n"
11121 "#include \"some very long include path\"\n"
11122 "#include <some/very/long/include/path>\n",
11123 getLLVMStyleWithColumns(35));
11124 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\""));
11125 EXPECT_EQ("#include <a>", format("#include<a>"));
11126
11127 verifyFormat("#import <string>");
11128 verifyFormat("#import <a/b/c.h>");
11129 verifyFormat("#import \"a/b/string\"");
11130 verifyFormat("#import \"string.h\"");
11131 verifyFormat("#import \"string.h\"");
11132 verifyFormat("#if __has_include(<strstream>)\n"
11133 "#include <strstream>\n"
11134 "#endif");
11135
11136 verifyFormat("#define MY_IMPORT <a/b>");
11137
11138 verifyFormat("#if __has_include(<a/b>)");
11139 verifyFormat("#if __has_include_next(<a/b>)");
11140 verifyFormat("#define F __has_include(<a/b>)");
11141 verifyFormat("#define F __has_include_next(<a/b>)");
11142
11143 // Protocol buffer definition or missing "#".
11144 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11145 getLLVMStyleWithColumns(30));
11146
11147 FormatStyle Style = getLLVMStyle();
11148 Style.AlwaysBreakBeforeMultilineStrings = true;
11149 Style.ColumnLimit = 0;
11150 verifyFormat("#import \"abc.h\"", Style);
11151
11152 // But 'import' might also be a regular C++ namespace.
11153 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11154 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11155 }
11156
11157 //===----------------------------------------------------------------------===//
11158 // Error recovery tests.
11159 //===----------------------------------------------------------------------===//
11160
TEST_F(FormatTest,IncompleteParameterLists)11161 TEST_F(FormatTest, IncompleteParameterLists) {
11162 FormatStyle NoBinPacking = getLLVMStyle();
11163 NoBinPacking.BinPackParameters = false;
11164 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11165 " double *min_x,\n"
11166 " double *max_x,\n"
11167 " double *min_y,\n"
11168 " double *max_y,\n"
11169 " double *min_z,\n"
11170 " double *max_z, ) {}",
11171 NoBinPacking);
11172 }
11173
TEST_F(FormatTest,IncorrectCodeTrailingStuff)11174 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11175 verifyFormat("void f() { return; }\n42");
11176 verifyFormat("void f() {\n"
11177 " if (0)\n"
11178 " return;\n"
11179 "}\n"
11180 "42");
11181 verifyFormat("void f() { return }\n42");
11182 verifyFormat("void f() {\n"
11183 " if (0)\n"
11184 " return\n"
11185 "}\n"
11186 "42");
11187 }
11188
TEST_F(FormatTest,IncorrectCodeMissingSemicolon)11189 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11190 EXPECT_EQ("void f() { return }", format("void f ( ) { return }"));
11191 EXPECT_EQ("void f() {\n"
11192 " if (a)\n"
11193 " return\n"
11194 "}",
11195 format("void f ( ) { if ( a ) return }"));
11196 EXPECT_EQ("namespace N {\n"
11197 "void f()\n"
11198 "}",
11199 format("namespace N { void f() }"));
11200 EXPECT_EQ("namespace N {\n"
11201 "void f() {}\n"
11202 "void g()\n"
11203 "} // namespace N",
11204 format("namespace N { void f( ) { } void g( ) }"));
11205 }
11206
TEST_F(FormatTest,IndentationWithinColumnLimitNotPossible)11207 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11208 verifyFormat("int aaaaaaaa =\n"
11209 " // Overlylongcomment\n"
11210 " b;",
11211 getLLVMStyleWithColumns(20));
11212 verifyFormat("function(\n"
11213 " ShortArgument,\n"
11214 " LoooooooooooongArgument);\n",
11215 getLLVMStyleWithColumns(20));
11216 }
11217
TEST_F(FormatTest,IncorrectAccessSpecifier)11218 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11219 verifyFormat("public:");
11220 verifyFormat("class A {\n"
11221 "public\n"
11222 " void f() {}\n"
11223 "};");
11224 verifyFormat("public\n"
11225 "int qwerty;");
11226 verifyFormat("public\n"
11227 "B {}");
11228 verifyFormat("public\n"
11229 "{}");
11230 verifyFormat("public\n"
11231 "B { int x; }");
11232 }
11233
TEST_F(FormatTest,IncorrectCodeUnbalancedBraces)11234 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11235 verifyFormat("{");
11236 verifyFormat("#})");
11237 verifyNoCrash("(/**/[:!] ?[).");
11238 }
11239
TEST_F(FormatTest,IncorrectUnbalancedBracesInMacrosWithUnicode)11240 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11241 // Found by oss-fuzz:
11242 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11243 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11244 Style.ColumnLimit = 60;
11245 verifyNoCrash(
11246 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11247 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11248 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11249 Style);
11250 }
11251
TEST_F(FormatTest,IncorrectCodeDoNoWhile)11252 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11253 verifyFormat("do {\n}");
11254 verifyFormat("do {\n}\n"
11255 "f();");
11256 verifyFormat("do {\n}\n"
11257 "wheeee(fun);");
11258 verifyFormat("do {\n"
11259 " f();\n"
11260 "}");
11261 }
11262
TEST_F(FormatTest,IncorrectCodeMissingParens)11263 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11264 verifyFormat("if {\n foo;\n foo();\n}");
11265 verifyFormat("switch {\n foo;\n foo();\n}");
11266 verifyIncompleteFormat("for {\n foo;\n foo();\n}");
11267 verifyFormat("while {\n foo;\n foo();\n}");
11268 verifyFormat("do {\n foo;\n foo();\n} while;");
11269 }
11270
TEST_F(FormatTest,DoesNotTouchUnwrappedLinesWithErrors)11271 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11272 verifyIncompleteFormat("namespace {\n"
11273 "class Foo { Foo (\n"
11274 "};\n"
11275 "} // namespace");
11276 }
11277
TEST_F(FormatTest,IncorrectCodeErrorDetection)11278 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11279 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n"));
11280 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n"));
11281 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n"));
11282 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n"));
11283
11284 EXPECT_EQ("{\n"
11285 " {\n"
11286 " breakme(\n"
11287 " qwe);\n"
11288 " }\n",
11289 format("{\n"
11290 " {\n"
11291 " breakme(qwe);\n"
11292 "}\n",
11293 getLLVMStyleWithColumns(10)));
11294 }
11295
TEST_F(FormatTest,LayoutCallsInsideBraceInitializers)11296 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11297 verifyFormat("int x = {\n"
11298 " avariable,\n"
11299 " b(alongervariable)};",
11300 getLLVMStyleWithColumns(25));
11301 }
11302
TEST_F(FormatTest,LayoutBraceInitializersInReturnStatement)11303 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11304 verifyFormat("return (a)(b){1, 2, 3};");
11305 }
11306
TEST_F(FormatTest,LayoutCxx11BraceInitializers)11307 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11308 verifyFormat("vector<int> x{1, 2, 3, 4};");
11309 verifyFormat("vector<int> x{\n"
11310 " 1,\n"
11311 " 2,\n"
11312 " 3,\n"
11313 " 4,\n"
11314 "};");
11315 verifyFormat("vector<T> x{{}, {}, {}, {}};");
11316 verifyFormat("f({1, 2});");
11317 verifyFormat("auto v = Foo{-1};");
11318 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11319 verifyFormat("Class::Class : member{1, 2, 3} {}");
11320 verifyFormat("new vector<int>{1, 2, 3};");
11321 verifyFormat("new int[3]{1, 2, 3};");
11322 verifyFormat("new int{1};");
11323 verifyFormat("return {arg1, arg2};");
11324 verifyFormat("return {arg1, SomeType{parameter}};");
11325 verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11326 verifyFormat("new T{arg1, arg2};");
11327 verifyFormat("f(MyMap[{composite, key}]);");
11328 verifyFormat("class Class {\n"
11329 " T member = {arg1, arg2};\n"
11330 "};");
11331 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11332 verifyFormat("const struct A a = {.a = 1, .b = 2};");
11333 verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11334 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11335 verifyFormat("int a = std::is_integral<int>{} + 0;");
11336
11337 verifyFormat("int foo(int i) { return fo1{}(i); }");
11338 verifyFormat("int foo(int i) { return fo1{}(i); }");
11339 verifyFormat("auto i = decltype(x){};");
11340 verifyFormat("auto i = typeof(x){};");
11341 verifyFormat("auto i = _Atomic(x){};");
11342 verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11343 verifyFormat("Node n{1, Node{1000}, //\n"
11344 " 2};");
11345 verifyFormat("Aaaa aaaaaaa{\n"
11346 " {\n"
11347 " aaaa,\n"
11348 " },\n"
11349 "};");
11350 verifyFormat("class C : public D {\n"
11351 " SomeClass SC{2};\n"
11352 "};");
11353 verifyFormat("class C : public A {\n"
11354 " class D : public B {\n"
11355 " void f() { int i{2}; }\n"
11356 " };\n"
11357 "};");
11358 verifyFormat("#define A {a, a},");
11359
11360 // Avoid breaking between equal sign and opening brace
11361 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11362 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11363 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11364 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11365 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11366 " {\"ccccccccccccccccccccc\", 2}};",
11367 AvoidBreakingFirstArgument);
11368
11369 // Binpacking only if there is no trailing comma
11370 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11371 " cccccccccc, dddddddddd};",
11372 getLLVMStyleWithColumns(50));
11373 verifyFormat("const Aaaaaa aaaaa = {\n"
11374 " aaaaaaaaaaa,\n"
11375 " bbbbbbbbbbb,\n"
11376 " ccccccccccc,\n"
11377 " ddddddddddd,\n"
11378 "};",
11379 getLLVMStyleWithColumns(50));
11380
11381 // Cases where distinguising braced lists and blocks is hard.
11382 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11383 verifyFormat("void f() {\n"
11384 " return; // comment\n"
11385 "}\n"
11386 "SomeType t;");
11387 verifyFormat("void f() {\n"
11388 " if (a) {\n"
11389 " f();\n"
11390 " }\n"
11391 "}\n"
11392 "SomeType t;");
11393
11394 // In combination with BinPackArguments = false.
11395 FormatStyle NoBinPacking = getLLVMStyle();
11396 NoBinPacking.BinPackArguments = false;
11397 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11398 " bbbbb,\n"
11399 " ccccc,\n"
11400 " ddddd,\n"
11401 " eeeee,\n"
11402 " ffffff,\n"
11403 " ggggg,\n"
11404 " hhhhhh,\n"
11405 " iiiiii,\n"
11406 " jjjjjj,\n"
11407 " kkkkkk};",
11408 NoBinPacking);
11409 verifyFormat("const Aaaaaa aaaaa = {\n"
11410 " aaaaa,\n"
11411 " bbbbb,\n"
11412 " ccccc,\n"
11413 " ddddd,\n"
11414 " eeeee,\n"
11415 " ffffff,\n"
11416 " ggggg,\n"
11417 " hhhhhh,\n"
11418 " iiiiii,\n"
11419 " jjjjjj,\n"
11420 " kkkkkk,\n"
11421 "};",
11422 NoBinPacking);
11423 verifyFormat(
11424 "const Aaaaaa aaaaa = {\n"
11425 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n"
11426 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n"
11427 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11428 "};",
11429 NoBinPacking);
11430
11431 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11432 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11433 " CDDDP83848_BMCR_REGISTER,\n"
11434 " CDDDP83848_BMSR_REGISTER,\n"
11435 " CDDDP83848_RBR_REGISTER};",
11436 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11437 " CDDDP83848_BMSR_REGISTER,\n"
11438 " CDDDP83848_RBR_REGISTER};",
11439 NoBinPacking));
11440
11441 // FIXME: The alignment of these trailing comments might be bad. Then again,
11442 // this might be utterly useless in real code.
11443 verifyFormat("Constructor::Constructor()\n"
11444 " : some_value{ //\n"
11445 " aaaaaaa, //\n"
11446 " bbbbbbb} {}");
11447
11448 // In braced lists, the first comment is always assumed to belong to the
11449 // first element. Thus, it can be moved to the next or previous line as
11450 // appropriate.
11451 EXPECT_EQ("function({// First element:\n"
11452 " 1,\n"
11453 " // Second element:\n"
11454 " 2});",
11455 format("function({\n"
11456 " // First element:\n"
11457 " 1,\n"
11458 " // Second element:\n"
11459 " 2});"));
11460 EXPECT_EQ("std::vector<int> MyNumbers{\n"
11461 " // First element:\n"
11462 " 1,\n"
11463 " // Second element:\n"
11464 " 2};",
11465 format("std::vector<int> MyNumbers{// First element:\n"
11466 " 1,\n"
11467 " // Second element:\n"
11468 " 2};",
11469 getLLVMStyleWithColumns(30)));
11470 // A trailing comma should still lead to an enforced line break and no
11471 // binpacking.
11472 EXPECT_EQ("vector<int> SomeVector = {\n"
11473 " // aaa\n"
11474 " 1,\n"
11475 " 2,\n"
11476 "};",
11477 format("vector<int> SomeVector = { // aaa\n"
11478 " 1, 2, };"));
11479
11480 // C++11 brace initializer list l-braces should not be treated any differently
11481 // when breaking before lambda bodies is enabled
11482 FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11483 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11484 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11485 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11486 verifyFormat(
11487 "std::runtime_error{\n"
11488 " \"Long string which will force a break onto the next line...\"};",
11489 BreakBeforeLambdaBody);
11490
11491 FormatStyle ExtraSpaces = getLLVMStyle();
11492 ExtraSpaces.Cpp11BracedListStyle = false;
11493 ExtraSpaces.ColumnLimit = 75;
11494 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11495 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11496 verifyFormat("f({ 1, 2 });", ExtraSpaces);
11497 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11498 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11499 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11500 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11501 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11502 verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11503 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11504 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11505 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11506 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11507 verifyFormat("class Class {\n"
11508 " T member = { arg1, arg2 };\n"
11509 "};",
11510 ExtraSpaces);
11511 verifyFormat(
11512 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11513 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11514 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11515 " bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11516 ExtraSpaces);
11517 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11518 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11519 ExtraSpaces);
11520 verifyFormat(
11521 "someFunction(OtherParam,\n"
11522 " BracedList{ // comment 1 (Forcing interesting break)\n"
11523 " param1, param2,\n"
11524 " // comment 2\n"
11525 " param3, param4 });",
11526 ExtraSpaces);
11527 verifyFormat(
11528 "std::this_thread::sleep_for(\n"
11529 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11530 ExtraSpaces);
11531 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11532 " aaaaaaa,\n"
11533 " aaaaaaaaaa,\n"
11534 " aaaaa,\n"
11535 " aaaaaaaaaaaaaaa,\n"
11536 " aaa,\n"
11537 " aaaaaaaaaa,\n"
11538 " a,\n"
11539 " aaaaaaaaaaaaaaaaaaaaa,\n"
11540 " aaaaaaaaaaaa,\n"
11541 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11542 " aaaaaaa,\n"
11543 " a};");
11544 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11545 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11546 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11547
11548 // Avoid breaking between initializer/equal sign and opening brace
11549 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11550 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11551 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11552 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11553 " { \"ccccccccccccccccccccc\", 2 }\n"
11554 "};",
11555 ExtraSpaces);
11556 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11557 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11558 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11559 " { \"ccccccccccccccccccccc\", 2 }\n"
11560 "};",
11561 ExtraSpaces);
11562
11563 FormatStyle SpaceBeforeBrace = getLLVMStyle();
11564 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11565 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11566 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11567
11568 FormatStyle SpaceBetweenBraces = getLLVMStyle();
11569 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11570 SpaceBetweenBraces.SpacesInParentheses = true;
11571 SpaceBetweenBraces.SpacesInSquareBrackets = true;
11572 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11573 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11574 verifyFormat("vector< int > x{ // comment 1\n"
11575 " 1, 2, 3, 4 };",
11576 SpaceBetweenBraces);
11577 SpaceBetweenBraces.ColumnLimit = 20;
11578 EXPECT_EQ("vector< int > x{\n"
11579 " 1, 2, 3, 4 };",
11580 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11581 SpaceBetweenBraces.ColumnLimit = 24;
11582 EXPECT_EQ("vector< int > x{ 1, 2,\n"
11583 " 3, 4 };",
11584 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11585 EXPECT_EQ("vector< int > x{\n"
11586 " 1,\n"
11587 " 2,\n"
11588 " 3,\n"
11589 " 4,\n"
11590 "};",
11591 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
11592 verifyFormat("vector< int > x{};", SpaceBetweenBraces);
11593 SpaceBetweenBraces.SpaceInEmptyParentheses = true;
11594 verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
11595 }
11596
TEST_F(FormatTest,FormatsBracedListsInColumnLayout)11597 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
11598 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11599 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11600 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11601 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11602 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11603 " 1, 22, 333, 4444, 55555, 666666, 7777777};");
11604 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
11605 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11606 " 1, 22, 333, 4444, 55555, //\n"
11607 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11608 " 1, 22, 333, 4444, 55555, 666666, 7777777};");
11609 verifyFormat(
11610 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11611 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11612 " 1, 22, 333, 4444, 55555, 666666, // comment\n"
11613 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
11614 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
11615 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
11616 " 7777777};");
11617 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11618 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11619 " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11620 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11621 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11622 " // Separating comment.\n"
11623 " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11624 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11625 " // Leading comment\n"
11626 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11627 " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11628 verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11629 " 1, 1, 1, 1};",
11630 getLLVMStyleWithColumns(39));
11631 verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11632 " 1, 1, 1, 1};",
11633 getLLVMStyleWithColumns(38));
11634 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
11635 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
11636 getLLVMStyleWithColumns(43));
11637 verifyFormat(
11638 "static unsigned SomeValues[10][3] = {\n"
11639 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n"
11640 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
11641 verifyFormat("static auto fields = new vector<string>{\n"
11642 " \"aaaaaaaaaaaaa\",\n"
11643 " \"aaaaaaaaaaaaa\",\n"
11644 " \"aaaaaaaaaaaa\",\n"
11645 " \"aaaaaaaaaaaaaa\",\n"
11646 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11647 " \"aaaaaaaaaaaa\",\n"
11648 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11649 "};");
11650 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
11651 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
11652 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
11653 " 3, cccccccccccccccccccccc};",
11654 getLLVMStyleWithColumns(60));
11655
11656 // Trailing commas.
11657 verifyFormat("vector<int> x = {\n"
11658 " 1, 1, 1, 1, 1, 1, 1, 1,\n"
11659 "};",
11660 getLLVMStyleWithColumns(39));
11661 verifyFormat("vector<int> x = {\n"
11662 " 1, 1, 1, 1, 1, 1, 1, 1, //\n"
11663 "};",
11664 getLLVMStyleWithColumns(39));
11665 verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11666 " 1, 1, 1, 1,\n"
11667 " /**/ /**/};",
11668 getLLVMStyleWithColumns(39));
11669
11670 // Trailing comment in the first line.
11671 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n"
11672 " 1111111111, 2222222222, 33333333333, 4444444444, //\n"
11673 " 111111111, 222222222, 3333333333, 444444444, //\n"
11674 " 11111111, 22222222, 333333333, 44444444};");
11675 // Trailing comment in the last line.
11676 verifyFormat("int aaaaa[] = {\n"
11677 " 1, 2, 3, // comment\n"
11678 " 4, 5, 6 // comment\n"
11679 "};");
11680
11681 // With nested lists, we should either format one item per line or all nested
11682 // lists one on line.
11683 // FIXME: For some nested lists, we can do better.
11684 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
11685 " {aaaaaaaaaaaaaaaaaaa},\n"
11686 " {aaaaaaaaaaaaaaaaaaaaa},\n"
11687 " {aaaaaaaaaaaaaaaaa}};",
11688 getLLVMStyleWithColumns(60));
11689 verifyFormat(
11690 "SomeStruct my_struct_array = {\n"
11691 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
11692 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
11693 " {aaa, aaa},\n"
11694 " {aaa, aaa},\n"
11695 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
11696 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
11697 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
11698
11699 // No column layout should be used here.
11700 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
11701 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
11702
11703 verifyNoCrash("a<,");
11704
11705 // No braced initializer here.
11706 verifyFormat("void f() {\n"
11707 " struct Dummy {};\n"
11708 " f(v);\n"
11709 "}");
11710
11711 // Long lists should be formatted in columns even if they are nested.
11712 verifyFormat(
11713 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11714 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11715 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11716 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11717 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11718 " 1, 22, 333, 4444, 55555, 666666, 7777777});");
11719
11720 // Allow "single-column" layout even if that violates the column limit. There
11721 // isn't going to be a better way.
11722 verifyFormat("std::vector<int> a = {\n"
11723 " aaaaaaaa,\n"
11724 " aaaaaaaa,\n"
11725 " aaaaaaaa,\n"
11726 " aaaaaaaa,\n"
11727 " aaaaaaaaaa,\n"
11728 " aaaaaaaa,\n"
11729 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
11730 getLLVMStyleWithColumns(30));
11731 verifyFormat("vector<int> aaaa = {\n"
11732 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11733 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11734 " aaaaaa.aaaaaaa,\n"
11735 " aaaaaa.aaaaaaa,\n"
11736 " aaaaaa.aaaaaaa,\n"
11737 " aaaaaa.aaaaaaa,\n"
11738 "};");
11739
11740 // Don't create hanging lists.
11741 verifyFormat("someFunction(Param, {List1, List2,\n"
11742 " List3});",
11743 getLLVMStyleWithColumns(35));
11744 verifyFormat("someFunction(Param, Param,\n"
11745 " {List1, List2,\n"
11746 " List3});",
11747 getLLVMStyleWithColumns(35));
11748 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
11749 " aaaaaaaaaaaaaaaaaaaaaaa);");
11750 }
11751
TEST_F(FormatTest,PullTrivialFunctionDefinitionsIntoSingleLine)11752 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
11753 FormatStyle DoNotMerge = getLLVMStyle();
11754 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11755
11756 verifyFormat("void f() { return 42; }");
11757 verifyFormat("void f() {\n"
11758 " return 42;\n"
11759 "}",
11760 DoNotMerge);
11761 verifyFormat("void f() {\n"
11762 " // Comment\n"
11763 "}");
11764 verifyFormat("{\n"
11765 "#error {\n"
11766 " int a;\n"
11767 "}");
11768 verifyFormat("{\n"
11769 " int a;\n"
11770 "#error {\n"
11771 "}");
11772 verifyFormat("void f() {} // comment");
11773 verifyFormat("void f() { int a; } // comment");
11774 verifyFormat("void f() {\n"
11775 "} // comment",
11776 DoNotMerge);
11777 verifyFormat("void f() {\n"
11778 " int a;\n"
11779 "} // comment",
11780 DoNotMerge);
11781 verifyFormat("void f() {\n"
11782 "} // comment",
11783 getLLVMStyleWithColumns(15));
11784
11785 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
11786 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22));
11787
11788 verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
11789 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
11790 verifyFormat("class C {\n"
11791 " C()\n"
11792 " : iiiiiiii(nullptr),\n"
11793 " kkkkkkk(nullptr),\n"
11794 " mmmmmmm(nullptr),\n"
11795 " nnnnnnn(nullptr) {}\n"
11796 "};",
11797 getGoogleStyle());
11798
11799 FormatStyle NoColumnLimit = getLLVMStyle();
11800 NoColumnLimit.ColumnLimit = 0;
11801 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
11802 EXPECT_EQ("class C {\n"
11803 " A() : b(0) {}\n"
11804 "};",
11805 format("class C{A():b(0){}};", NoColumnLimit));
11806 EXPECT_EQ("A()\n"
11807 " : b(0) {\n"
11808 "}",
11809 format("A()\n:b(0)\n{\n}", NoColumnLimit));
11810
11811 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
11812 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
11813 FormatStyle::SFS_None;
11814 EXPECT_EQ("A()\n"
11815 " : b(0) {\n"
11816 "}",
11817 format("A():b(0){}", DoNotMergeNoColumnLimit));
11818 EXPECT_EQ("A()\n"
11819 " : b(0) {\n"
11820 "}",
11821 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
11822
11823 verifyFormat("#define A \\\n"
11824 " void f() { \\\n"
11825 " int i; \\\n"
11826 " }",
11827 getLLVMStyleWithColumns(20));
11828 verifyFormat("#define A \\\n"
11829 " void f() { int i; }",
11830 getLLVMStyleWithColumns(21));
11831 verifyFormat("#define A \\\n"
11832 " void f() { \\\n"
11833 " int i; \\\n"
11834 " } \\\n"
11835 " int j;",
11836 getLLVMStyleWithColumns(22));
11837 verifyFormat("#define A \\\n"
11838 " void f() { int i; } \\\n"
11839 " int j;",
11840 getLLVMStyleWithColumns(23));
11841 }
11842
TEST_F(FormatTest,PullEmptyFunctionDefinitionsIntoSingleLine)11843 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
11844 FormatStyle MergeEmptyOnly = getLLVMStyle();
11845 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
11846 verifyFormat("class C {\n"
11847 " int f() {}\n"
11848 "};",
11849 MergeEmptyOnly);
11850 verifyFormat("class C {\n"
11851 " int f() {\n"
11852 " return 42;\n"
11853 " }\n"
11854 "};",
11855 MergeEmptyOnly);
11856 verifyFormat("int f() {}", MergeEmptyOnly);
11857 verifyFormat("int f() {\n"
11858 " return 42;\n"
11859 "}",
11860 MergeEmptyOnly);
11861
11862 // Also verify behavior when BraceWrapping.AfterFunction = true
11863 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11864 MergeEmptyOnly.BraceWrapping.AfterFunction = true;
11865 verifyFormat("int f() {}", MergeEmptyOnly);
11866 verifyFormat("class C {\n"
11867 " int f() {}\n"
11868 "};",
11869 MergeEmptyOnly);
11870 }
11871
TEST_F(FormatTest,PullInlineFunctionDefinitionsIntoSingleLine)11872 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
11873 FormatStyle MergeInlineOnly = getLLVMStyle();
11874 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
11875 verifyFormat("class C {\n"
11876 " int f() { return 42; }\n"
11877 "};",
11878 MergeInlineOnly);
11879 verifyFormat("int f() {\n"
11880 " return 42;\n"
11881 "}",
11882 MergeInlineOnly);
11883
11884 // SFS_Inline implies SFS_Empty
11885 verifyFormat("class C {\n"
11886 " int f() {}\n"
11887 "};",
11888 MergeInlineOnly);
11889 verifyFormat("int f() {}", MergeInlineOnly);
11890
11891 // Also verify behavior when BraceWrapping.AfterFunction = true
11892 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11893 MergeInlineOnly.BraceWrapping.AfterFunction = true;
11894 verifyFormat("class C {\n"
11895 " int f() { return 42; }\n"
11896 "};",
11897 MergeInlineOnly);
11898 verifyFormat("int f()\n"
11899 "{\n"
11900 " return 42;\n"
11901 "}",
11902 MergeInlineOnly);
11903
11904 // SFS_Inline implies SFS_Empty
11905 verifyFormat("int f() {}", MergeInlineOnly);
11906 verifyFormat("class C {\n"
11907 " int f() {}\n"
11908 "};",
11909 MergeInlineOnly);
11910 }
11911
TEST_F(FormatTest,PullInlineOnlyFunctionDefinitionsIntoSingleLine)11912 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
11913 FormatStyle MergeInlineOnly = getLLVMStyle();
11914 MergeInlineOnly.AllowShortFunctionsOnASingleLine =
11915 FormatStyle::SFS_InlineOnly;
11916 verifyFormat("class C {\n"
11917 " int f() { return 42; }\n"
11918 "};",
11919 MergeInlineOnly);
11920 verifyFormat("int f() {\n"
11921 " return 42;\n"
11922 "}",
11923 MergeInlineOnly);
11924
11925 // SFS_InlineOnly does not imply SFS_Empty
11926 verifyFormat("class C {\n"
11927 " int f() {}\n"
11928 "};",
11929 MergeInlineOnly);
11930 verifyFormat("int f() {\n"
11931 "}",
11932 MergeInlineOnly);
11933
11934 // Also verify behavior when BraceWrapping.AfterFunction = true
11935 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11936 MergeInlineOnly.BraceWrapping.AfterFunction = true;
11937 verifyFormat("class C {\n"
11938 " int f() { return 42; }\n"
11939 "};",
11940 MergeInlineOnly);
11941 verifyFormat("int f()\n"
11942 "{\n"
11943 " return 42;\n"
11944 "}",
11945 MergeInlineOnly);
11946
11947 // SFS_InlineOnly does not imply SFS_Empty
11948 verifyFormat("int f()\n"
11949 "{\n"
11950 "}",
11951 MergeInlineOnly);
11952 verifyFormat("class C {\n"
11953 " int f() {}\n"
11954 "};",
11955 MergeInlineOnly);
11956 }
11957
TEST_F(FormatTest,SplitEmptyFunction)11958 TEST_F(FormatTest, SplitEmptyFunction) {
11959 FormatStyle Style = getLLVMStyle();
11960 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11961 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11962 Style.BraceWrapping.AfterFunction = true;
11963 Style.BraceWrapping.SplitEmptyFunction = false;
11964 Style.ColumnLimit = 40;
11965
11966 verifyFormat("int f()\n"
11967 "{}",
11968 Style);
11969 verifyFormat("int f()\n"
11970 "{\n"
11971 " return 42;\n"
11972 "}",
11973 Style);
11974 verifyFormat("int f()\n"
11975 "{\n"
11976 " // some comment\n"
11977 "}",
11978 Style);
11979
11980 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
11981 verifyFormat("int f() {}", Style);
11982 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11983 "{}",
11984 Style);
11985 verifyFormat("int f()\n"
11986 "{\n"
11987 " return 0;\n"
11988 "}",
11989 Style);
11990
11991 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
11992 verifyFormat("class Foo {\n"
11993 " int f() {}\n"
11994 "};\n",
11995 Style);
11996 verifyFormat("class Foo {\n"
11997 " int f() { return 0; }\n"
11998 "};\n",
11999 Style);
12000 verifyFormat("class Foo {\n"
12001 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12002 " {}\n"
12003 "};\n",
12004 Style);
12005 verifyFormat("class Foo {\n"
12006 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12007 " {\n"
12008 " return 0;\n"
12009 " }\n"
12010 "};\n",
12011 Style);
12012
12013 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12014 verifyFormat("int f() {}", Style);
12015 verifyFormat("int f() { return 0; }", Style);
12016 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12017 "{}",
12018 Style);
12019 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12020 "{\n"
12021 " return 0;\n"
12022 "}",
12023 Style);
12024 }
TEST_F(FormatTest,KeepShortFunctionAfterPPElse)12025 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12026 FormatStyle Style = getLLVMStyle();
12027 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12028 verifyFormat("#ifdef A\n"
12029 "int f() {}\n"
12030 "#else\n"
12031 "int g() {}\n"
12032 "#endif",
12033 Style);
12034 }
12035
TEST_F(FormatTest,SplitEmptyClass)12036 TEST_F(FormatTest, SplitEmptyClass) {
12037 FormatStyle Style = getLLVMStyle();
12038 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12039 Style.BraceWrapping.AfterClass = true;
12040 Style.BraceWrapping.SplitEmptyRecord = false;
12041
12042 verifyFormat("class Foo\n"
12043 "{};",
12044 Style);
12045 verifyFormat("/* something */ class Foo\n"
12046 "{};",
12047 Style);
12048 verifyFormat("template <typename X> class Foo\n"
12049 "{};",
12050 Style);
12051 verifyFormat("class Foo\n"
12052 "{\n"
12053 " Foo();\n"
12054 "};",
12055 Style);
12056 verifyFormat("typedef class Foo\n"
12057 "{\n"
12058 "} Foo_t;",
12059 Style);
12060
12061 Style.BraceWrapping.SplitEmptyRecord = true;
12062 Style.BraceWrapping.AfterStruct = true;
12063 verifyFormat("class rep\n"
12064 "{\n"
12065 "};",
12066 Style);
12067 verifyFormat("struct rep\n"
12068 "{\n"
12069 "};",
12070 Style);
12071 verifyFormat("template <typename T> class rep\n"
12072 "{\n"
12073 "};",
12074 Style);
12075 verifyFormat("template <typename T> struct rep\n"
12076 "{\n"
12077 "};",
12078 Style);
12079 verifyFormat("class rep\n"
12080 "{\n"
12081 " int x;\n"
12082 "};",
12083 Style);
12084 verifyFormat("struct rep\n"
12085 "{\n"
12086 " int x;\n"
12087 "};",
12088 Style);
12089 verifyFormat("template <typename T> class rep\n"
12090 "{\n"
12091 " int x;\n"
12092 "};",
12093 Style);
12094 verifyFormat("template <typename T> struct rep\n"
12095 "{\n"
12096 " int x;\n"
12097 "};",
12098 Style);
12099 verifyFormat("template <typename T> class rep // Foo\n"
12100 "{\n"
12101 " int x;\n"
12102 "};",
12103 Style);
12104 verifyFormat("template <typename T> struct rep // Bar\n"
12105 "{\n"
12106 " int x;\n"
12107 "};",
12108 Style);
12109
12110 verifyFormat("template <typename T> class rep<T>\n"
12111 "{\n"
12112 " int x;\n"
12113 "};",
12114 Style);
12115
12116 verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12117 "{\n"
12118 " int x;\n"
12119 "};",
12120 Style);
12121 verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12122 "{\n"
12123 "};",
12124 Style);
12125
12126 verifyFormat("#include \"stdint.h\"\n"
12127 "namespace rep {}",
12128 Style);
12129 verifyFormat("#include <stdint.h>\n"
12130 "namespace rep {}",
12131 Style);
12132 verifyFormat("#include <stdint.h>\n"
12133 "namespace rep {}",
12134 "#include <stdint.h>\n"
12135 "namespace rep {\n"
12136 "\n"
12137 "\n"
12138 "}",
12139 Style);
12140 }
12141
TEST_F(FormatTest,SplitEmptyStruct)12142 TEST_F(FormatTest, SplitEmptyStruct) {
12143 FormatStyle Style = getLLVMStyle();
12144 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12145 Style.BraceWrapping.AfterStruct = true;
12146 Style.BraceWrapping.SplitEmptyRecord = false;
12147
12148 verifyFormat("struct Foo\n"
12149 "{};",
12150 Style);
12151 verifyFormat("/* something */ struct Foo\n"
12152 "{};",
12153 Style);
12154 verifyFormat("template <typename X> struct Foo\n"
12155 "{};",
12156 Style);
12157 verifyFormat("struct Foo\n"
12158 "{\n"
12159 " Foo();\n"
12160 "};",
12161 Style);
12162 verifyFormat("typedef struct Foo\n"
12163 "{\n"
12164 "} Foo_t;",
12165 Style);
12166 // typedef struct Bar {} Bar_t;
12167 }
12168
TEST_F(FormatTest,SplitEmptyUnion)12169 TEST_F(FormatTest, SplitEmptyUnion) {
12170 FormatStyle Style = getLLVMStyle();
12171 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12172 Style.BraceWrapping.AfterUnion = true;
12173 Style.BraceWrapping.SplitEmptyRecord = false;
12174
12175 verifyFormat("union Foo\n"
12176 "{};",
12177 Style);
12178 verifyFormat("/* something */ union Foo\n"
12179 "{};",
12180 Style);
12181 verifyFormat("union Foo\n"
12182 "{\n"
12183 " A,\n"
12184 "};",
12185 Style);
12186 verifyFormat("typedef union Foo\n"
12187 "{\n"
12188 "} Foo_t;",
12189 Style);
12190 }
12191
TEST_F(FormatTest,SplitEmptyNamespace)12192 TEST_F(FormatTest, SplitEmptyNamespace) {
12193 FormatStyle Style = getLLVMStyle();
12194 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12195 Style.BraceWrapping.AfterNamespace = true;
12196 Style.BraceWrapping.SplitEmptyNamespace = false;
12197
12198 verifyFormat("namespace Foo\n"
12199 "{};",
12200 Style);
12201 verifyFormat("/* something */ namespace Foo\n"
12202 "{};",
12203 Style);
12204 verifyFormat("inline namespace Foo\n"
12205 "{};",
12206 Style);
12207 verifyFormat("/* something */ inline namespace Foo\n"
12208 "{};",
12209 Style);
12210 verifyFormat("export namespace Foo\n"
12211 "{};",
12212 Style);
12213 verifyFormat("namespace Foo\n"
12214 "{\n"
12215 "void Bar();\n"
12216 "};",
12217 Style);
12218 }
12219
TEST_F(FormatTest,NeverMergeShortRecords)12220 TEST_F(FormatTest, NeverMergeShortRecords) {
12221 FormatStyle Style = getLLVMStyle();
12222
12223 verifyFormat("class Foo {\n"
12224 " Foo();\n"
12225 "};",
12226 Style);
12227 verifyFormat("typedef class Foo {\n"
12228 " Foo();\n"
12229 "} Foo_t;",
12230 Style);
12231 verifyFormat("struct Foo {\n"
12232 " Foo();\n"
12233 "};",
12234 Style);
12235 verifyFormat("typedef struct Foo {\n"
12236 " Foo();\n"
12237 "} Foo_t;",
12238 Style);
12239 verifyFormat("union Foo {\n"
12240 " A,\n"
12241 "};",
12242 Style);
12243 verifyFormat("typedef union Foo {\n"
12244 " A,\n"
12245 "} Foo_t;",
12246 Style);
12247 verifyFormat("namespace Foo {\n"
12248 "void Bar();\n"
12249 "};",
12250 Style);
12251
12252 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12253 Style.BraceWrapping.AfterClass = true;
12254 Style.BraceWrapping.AfterStruct = true;
12255 Style.BraceWrapping.AfterUnion = true;
12256 Style.BraceWrapping.AfterNamespace = true;
12257 verifyFormat("class Foo\n"
12258 "{\n"
12259 " Foo();\n"
12260 "};",
12261 Style);
12262 verifyFormat("typedef class Foo\n"
12263 "{\n"
12264 " Foo();\n"
12265 "} Foo_t;",
12266 Style);
12267 verifyFormat("struct Foo\n"
12268 "{\n"
12269 " Foo();\n"
12270 "};",
12271 Style);
12272 verifyFormat("typedef struct Foo\n"
12273 "{\n"
12274 " Foo();\n"
12275 "} Foo_t;",
12276 Style);
12277 verifyFormat("union Foo\n"
12278 "{\n"
12279 " A,\n"
12280 "};",
12281 Style);
12282 verifyFormat("typedef union Foo\n"
12283 "{\n"
12284 " A,\n"
12285 "} Foo_t;",
12286 Style);
12287 verifyFormat("namespace Foo\n"
12288 "{\n"
12289 "void Bar();\n"
12290 "};",
12291 Style);
12292 }
12293
TEST_F(FormatTest,UnderstandContextOfRecordTypeKeywords)12294 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12295 // Elaborate type variable declarations.
12296 verifyFormat("struct foo a = {bar};\nint n;");
12297 verifyFormat("class foo a = {bar};\nint n;");
12298 verifyFormat("union foo a = {bar};\nint n;");
12299
12300 // Elaborate types inside function definitions.
12301 verifyFormat("struct foo f() {}\nint n;");
12302 verifyFormat("class foo f() {}\nint n;");
12303 verifyFormat("union foo f() {}\nint n;");
12304
12305 // Templates.
12306 verifyFormat("template <class X> void f() {}\nint n;");
12307 verifyFormat("template <struct X> void f() {}\nint n;");
12308 verifyFormat("template <union X> void f() {}\nint n;");
12309
12310 // Actual definitions...
12311 verifyFormat("struct {\n} n;");
12312 verifyFormat(
12313 "template <template <class T, class Y>, class Z> class X {\n} n;");
12314 verifyFormat("union Z {\n int n;\n} x;");
12315 verifyFormat("class MACRO Z {\n} n;");
12316 verifyFormat("class MACRO(X) Z {\n} n;");
12317 verifyFormat("class __attribute__(X) Z {\n} n;");
12318 verifyFormat("class __declspec(X) Z {\n} n;");
12319 verifyFormat("class A##B##C {\n} n;");
12320 verifyFormat("class alignas(16) Z {\n} n;");
12321 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12322 verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12323
12324 // Redefinition from nested context:
12325 verifyFormat("class A::B::C {\n} n;");
12326
12327 // Template definitions.
12328 verifyFormat(
12329 "template <typename F>\n"
12330 "Matcher(const Matcher<F> &Other,\n"
12331 " typename enable_if_c<is_base_of<F, T>::value &&\n"
12332 " !is_same<F, T>::value>::type * = 0)\n"
12333 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12334
12335 // FIXME: This is still incorrectly handled at the formatter side.
12336 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12337 verifyFormat("int i = SomeFunction(a<b, a> b);");
12338
12339 // FIXME:
12340 // This now gets parsed incorrectly as class definition.
12341 // verifyFormat("class A<int> f() {\n}\nint n;");
12342
12343 // Elaborate types where incorrectly parsing the structural element would
12344 // break the indent.
12345 verifyFormat("if (true)\n"
12346 " class X x;\n"
12347 "else\n"
12348 " f();\n");
12349
12350 // This is simply incomplete. Formatting is not important, but must not crash.
12351 verifyFormat("class A:");
12352 }
12353
TEST_F(FormatTest,DoNotInterfereWithErrorAndWarning)12354 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12355 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n",
12356 format("#error Leave all white!!!!! space* alone!\n"));
12357 EXPECT_EQ(
12358 "#warning Leave all white!!!!! space* alone!\n",
12359 format("#warning Leave all white!!!!! space* alone!\n"));
12360 EXPECT_EQ("#error 1", format(" # error 1"));
12361 EXPECT_EQ("#warning 1", format(" # warning 1"));
12362 }
12363
TEST_F(FormatTest,FormatHashIfExpressions)12364 TEST_F(FormatTest, FormatHashIfExpressions) {
12365 verifyFormat("#if AAAA && BBBB");
12366 verifyFormat("#if (AAAA && BBBB)");
12367 verifyFormat("#elif (AAAA && BBBB)");
12368 // FIXME: Come up with a better indentation for #elif.
12369 verifyFormat(
12370 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n"
12371 " defined(BBBBBBBB)\n"
12372 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n"
12373 " defined(BBBBBBBB)\n"
12374 "#endif",
12375 getLLVMStyleWithColumns(65));
12376 }
12377
TEST_F(FormatTest,MergeHandlingInTheFaceOfPreprocessorDirectives)12378 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12379 FormatStyle AllowsMergedIf = getGoogleStyle();
12380 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12381 FormatStyle::SIS_WithoutElse;
12382 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12383 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12384 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf);
12385 EXPECT_EQ("if (true) return 42;",
12386 format("if (true)\nreturn 42;", AllowsMergedIf));
12387 FormatStyle ShortMergedIf = AllowsMergedIf;
12388 ShortMergedIf.ColumnLimit = 25;
12389 verifyFormat("#define A \\\n"
12390 " if (true) return 42;",
12391 ShortMergedIf);
12392 verifyFormat("#define A \\\n"
12393 " f(); \\\n"
12394 " if (true)\n"
12395 "#define B",
12396 ShortMergedIf);
12397 verifyFormat("#define A \\\n"
12398 " f(); \\\n"
12399 " if (true)\n"
12400 "g();",
12401 ShortMergedIf);
12402 verifyFormat("{\n"
12403 "#ifdef A\n"
12404 " // Comment\n"
12405 " if (true) continue;\n"
12406 "#endif\n"
12407 " // Comment\n"
12408 " if (true) continue;\n"
12409 "}",
12410 ShortMergedIf);
12411 ShortMergedIf.ColumnLimit = 33;
12412 verifyFormat("#define A \\\n"
12413 " if constexpr (true) return 42;",
12414 ShortMergedIf);
12415 verifyFormat("#define A \\\n"
12416 " if CONSTEXPR (true) return 42;",
12417 ShortMergedIf);
12418 ShortMergedIf.ColumnLimit = 29;
12419 verifyFormat("#define A \\\n"
12420 " if (aaaaaaaaaa) return 1; \\\n"
12421 " return 2;",
12422 ShortMergedIf);
12423 ShortMergedIf.ColumnLimit = 28;
12424 verifyFormat("#define A \\\n"
12425 " if (aaaaaaaaaa) \\\n"
12426 " return 1; \\\n"
12427 " return 2;",
12428 ShortMergedIf);
12429 verifyFormat("#define A \\\n"
12430 " if constexpr (aaaaaaa) \\\n"
12431 " return 1; \\\n"
12432 " return 2;",
12433 ShortMergedIf);
12434 verifyFormat("#define A \\\n"
12435 " if CONSTEXPR (aaaaaaa) \\\n"
12436 " return 1; \\\n"
12437 " return 2;",
12438 ShortMergedIf);
12439 }
12440
TEST_F(FormatTest,FormatStarDependingOnContext)12441 TEST_F(FormatTest, FormatStarDependingOnContext) {
12442 verifyFormat("void f(int *a);");
12443 verifyFormat("void f() { f(fint * b); }");
12444 verifyFormat("class A {\n void f(int *a);\n};");
12445 verifyFormat("class A {\n int *a;\n};");
12446 verifyFormat("namespace a {\n"
12447 "namespace b {\n"
12448 "class A {\n"
12449 " void f() {}\n"
12450 " int *a;\n"
12451 "};\n"
12452 "} // namespace b\n"
12453 "} // namespace a");
12454 }
12455
TEST_F(FormatTest,SpecialTokensAtEndOfLine)12456 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12457 verifyFormat("while");
12458 verifyFormat("operator");
12459 }
12460
TEST_F(FormatTest,SkipsDeeplyNestedLines)12461 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12462 // This code would be painfully slow to format if we didn't skip it.
12463 std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x
12464 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12465 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12466 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12467 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12468 "A(1, 1)\n"
12469 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12470 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12471 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12472 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12473 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12474 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12475 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12476 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12477 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12478 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12479 // Deeply nested part is untouched, rest is formatted.
12480 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12481 format(std::string("int i;\n") + Code + "int j;\n",
12482 getLLVMStyle(), SC_ExpectIncomplete));
12483 }
12484
12485 //===----------------------------------------------------------------------===//
12486 // Objective-C tests.
12487 //===----------------------------------------------------------------------===//
12488
TEST_F(FormatTest,FormatForObjectiveCMethodDecls)12489 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12490 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12491 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12492 format("-(NSUInteger)indexOfObject:(id)anObject;"));
12493 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12494 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12495 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12496 format("-(NSInteger)Method3:(id)anObject;"));
12497 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12498 format("-(NSInteger)Method4:(id)anObject;"));
12499 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12500 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12501 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12502 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12503 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12504 "forAllCells:(BOOL)flag;",
12505 format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12506 "forAllCells:(BOOL)flag;"));
12507
12508 // Very long objectiveC method declaration.
12509 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12510 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12511 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12512 " inRange:(NSRange)range\n"
12513 " outRange:(NSRange)out_range\n"
12514 " outRange1:(NSRange)out_range1\n"
12515 " outRange2:(NSRange)out_range2\n"
12516 " outRange3:(NSRange)out_range3\n"
12517 " outRange4:(NSRange)out_range4\n"
12518 " outRange5:(NSRange)out_range5\n"
12519 " outRange6:(NSRange)out_range6\n"
12520 " outRange7:(NSRange)out_range7\n"
12521 " outRange8:(NSRange)out_range8\n"
12522 " outRange9:(NSRange)out_range9;");
12523
12524 // When the function name has to be wrapped.
12525 FormatStyle Style = getLLVMStyle();
12526 // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12527 // and always indents instead.
12528 Style.IndentWrappedFunctionNames = false;
12529 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12530 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12531 " anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12532 "}",
12533 Style);
12534 Style.IndentWrappedFunctionNames = true;
12535 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12536 " veryLooooooooooongName:(NSString)cccccccccccccc\n"
12537 " anotherName:(NSString)dddddddddddddd {\n"
12538 "}",
12539 Style);
12540
12541 verifyFormat("- (int)sum:(vector<int>)numbers;");
12542 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12543 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12544 // protocol lists (but not for template classes):
12545 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12546
12547 verifyFormat("- (int (*)())foo:(int (*)())f;");
12548 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12549
12550 // If there's no return type (very rare in practice!), LLVM and Google style
12551 // agree.
12552 verifyFormat("- foo;");
12553 verifyFormat("- foo:(int)f;");
12554 verifyGoogleFormat("- foo:(int)foo;");
12555 }
12556
TEST_F(FormatTest,BreaksStringLiterals)12557 TEST_F(FormatTest, BreaksStringLiterals) {
12558 EXPECT_EQ("\"some text \"\n"
12559 "\"other\";",
12560 format("\"some text other\";", getLLVMStyleWithColumns(12)));
12561 EXPECT_EQ("\"some text \"\n"
12562 "\"other\";",
12563 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
12564 EXPECT_EQ(
12565 "#define A \\\n"
12566 " \"some \" \\\n"
12567 " \"text \" \\\n"
12568 " \"other\";",
12569 format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
12570 EXPECT_EQ(
12571 "#define A \\\n"
12572 " \"so \" \\\n"
12573 " \"text \" \\\n"
12574 " \"other\";",
12575 format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
12576
12577 EXPECT_EQ("\"some text\"",
12578 format("\"some text\"", getLLVMStyleWithColumns(1)));
12579 EXPECT_EQ("\"some text\"",
12580 format("\"some text\"", getLLVMStyleWithColumns(11)));
12581 EXPECT_EQ("\"some \"\n"
12582 "\"text\"",
12583 format("\"some text\"", getLLVMStyleWithColumns(10)));
12584 EXPECT_EQ("\"some \"\n"
12585 "\"text\"",
12586 format("\"some text\"", getLLVMStyleWithColumns(7)));
12587 EXPECT_EQ("\"some\"\n"
12588 "\" tex\"\n"
12589 "\"t\"",
12590 format("\"some text\"", getLLVMStyleWithColumns(6)));
12591 EXPECT_EQ("\"some\"\n"
12592 "\" tex\"\n"
12593 "\" and\"",
12594 format("\"some tex and\"", getLLVMStyleWithColumns(6)));
12595 EXPECT_EQ("\"some\"\n"
12596 "\"/tex\"\n"
12597 "\"/and\"",
12598 format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
12599
12600 EXPECT_EQ("variable =\n"
12601 " \"long string \"\n"
12602 " \"literal\";",
12603 format("variable = \"long string literal\";",
12604 getLLVMStyleWithColumns(20)));
12605
12606 EXPECT_EQ("variable = f(\n"
12607 " \"long string \"\n"
12608 " \"literal\",\n"
12609 " short,\n"
12610 " loooooooooooooooooooong);",
12611 format("variable = f(\"long string literal\", short, "
12612 "loooooooooooooooooooong);",
12613 getLLVMStyleWithColumns(20)));
12614
12615 EXPECT_EQ(
12616 "f(g(\"long string \"\n"
12617 " \"literal\"),\n"
12618 " b);",
12619 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
12620 EXPECT_EQ("f(g(\"long string \"\n"
12621 " \"literal\",\n"
12622 " a),\n"
12623 " b);",
12624 format("f(g(\"long string literal\", a), b);",
12625 getLLVMStyleWithColumns(20)));
12626 EXPECT_EQ(
12627 "f(\"one two\".split(\n"
12628 " variable));",
12629 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
12630 EXPECT_EQ("f(\"one two three four five six \"\n"
12631 " \"seven\".split(\n"
12632 " really_looooong_variable));",
12633 format("f(\"one two three four five six seven\"."
12634 "split(really_looooong_variable));",
12635 getLLVMStyleWithColumns(33)));
12636
12637 EXPECT_EQ("f(\"some \"\n"
12638 " \"text\",\n"
12639 " other);",
12640 format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
12641
12642 // Only break as a last resort.
12643 verifyFormat(
12644 "aaaaaaaaaaaaaaaaaaaa(\n"
12645 " aaaaaaaaaaaaaaaaaaaa,\n"
12646 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
12647
12648 EXPECT_EQ("\"splitmea\"\n"
12649 "\"trandomp\"\n"
12650 "\"oint\"",
12651 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
12652
12653 EXPECT_EQ("\"split/\"\n"
12654 "\"pathat/\"\n"
12655 "\"slashes\"",
12656 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12657
12658 EXPECT_EQ("\"split/\"\n"
12659 "\"pathat/\"\n"
12660 "\"slashes\"",
12661 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12662 EXPECT_EQ("\"split at \"\n"
12663 "\"spaces/at/\"\n"
12664 "\"slashes.at.any$\"\n"
12665 "\"non-alphanumeric%\"\n"
12666 "\"1111111111characte\"\n"
12667 "\"rs\"",
12668 format("\"split at "
12669 "spaces/at/"
12670 "slashes.at."
12671 "any$non-"
12672 "alphanumeric%"
12673 "1111111111characte"
12674 "rs\"",
12675 getLLVMStyleWithColumns(20)));
12676
12677 // Verify that splitting the strings understands
12678 // Style::AlwaysBreakBeforeMultilineStrings.
12679 EXPECT_EQ("aaaaaaaaaaaa(\n"
12680 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
12681 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
12682 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
12683 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12684 "aaaaaaaaaaaaaaaaaaaaaa\");",
12685 getGoogleStyle()));
12686 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12687 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
12688 format("return \"aaaaaaaaaaaaaaaaaaaaaa "
12689 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12690 "aaaaaaaaaaaaaaaaaaaaaa\";",
12691 getGoogleStyle()));
12692 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12693 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12694 format("llvm::outs() << "
12695 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
12696 "aaaaaaaaaaaaaaaaaaa\";"));
12697 EXPECT_EQ("ffff(\n"
12698 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12699 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12700 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
12701 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12702 getGoogleStyle()));
12703
12704 FormatStyle Style = getLLVMStyleWithColumns(12);
12705 Style.BreakStringLiterals = false;
12706 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
12707
12708 FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
12709 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12710 EXPECT_EQ("#define A \\\n"
12711 " \"some \" \\\n"
12712 " \"text \" \\\n"
12713 " \"other\";",
12714 format("#define A \"some text other\";", AlignLeft));
12715 }
12716
TEST_F(FormatTest,BreaksStringLiteralsAtColumnLimit)12717 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
12718 EXPECT_EQ("C a = \"some more \"\n"
12719 " \"text\";",
12720 format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
12721 }
12722
TEST_F(FormatTest,FullyRemoveEmptyLines)12723 TEST_F(FormatTest, FullyRemoveEmptyLines) {
12724 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
12725 NoEmptyLines.MaxEmptyLinesToKeep = 0;
12726 EXPECT_EQ("int i = a(b());",
12727 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
12728 }
12729
TEST_F(FormatTest,BreaksStringLiteralsWithTabs)12730 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
12731 EXPECT_EQ(
12732 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12733 "(\n"
12734 " \"x\t\");",
12735 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12736 "aaaaaaa("
12737 "\"x\t\");"));
12738 }
12739
TEST_F(FormatTest,BreaksWideAndNSStringLiterals)12740 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
12741 EXPECT_EQ(
12742 "u8\"utf8 string \"\n"
12743 "u8\"literal\";",
12744 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
12745 EXPECT_EQ(
12746 "u\"utf16 string \"\n"
12747 "u\"literal\";",
12748 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
12749 EXPECT_EQ(
12750 "U\"utf32 string \"\n"
12751 "U\"literal\";",
12752 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
12753 EXPECT_EQ("L\"wide string \"\n"
12754 "L\"literal\";",
12755 format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
12756 EXPECT_EQ("@\"NSString \"\n"
12757 "@\"literal\";",
12758 format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
12759 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
12760
12761 // This input makes clang-format try to split the incomplete unicode escape
12762 // sequence, which used to lead to a crasher.
12763 verifyNoCrash(
12764 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
12765 getLLVMStyleWithColumns(60));
12766 }
12767
TEST_F(FormatTest,DoesNotBreakRawStringLiterals)12768 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
12769 FormatStyle Style = getGoogleStyleWithColumns(15);
12770 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
12771 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
12772 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
12773 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
12774 EXPECT_EQ("u8R\"x(raw literal)x\";",
12775 format("u8R\"x(raw literal)x\";", Style));
12776 }
12777
TEST_F(FormatTest,BreaksStringLiteralsWithin_TMacro)12778 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
12779 FormatStyle Style = getLLVMStyleWithColumns(20);
12780 EXPECT_EQ(
12781 "_T(\"aaaaaaaaaaaaaa\")\n"
12782 "_T(\"aaaaaaaaaaaaaa\")\n"
12783 "_T(\"aaaaaaaaaaaa\")",
12784 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
12785 EXPECT_EQ("f(x,\n"
12786 " _T(\"aaaaaaaaaaaa\")\n"
12787 " _T(\"aaa\"),\n"
12788 " z);",
12789 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
12790
12791 // FIXME: Handle embedded spaces in one iteration.
12792 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
12793 // "_T(\"aaaaaaaaaaaaa\")\n"
12794 // "_T(\"aaaaaaaaaaaaa\")\n"
12795 // "_T(\"a\")",
12796 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
12797 // getLLVMStyleWithColumns(20)));
12798 EXPECT_EQ(
12799 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
12800 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
12801 EXPECT_EQ("f(\n"
12802 "#if !TEST\n"
12803 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
12804 "#endif\n"
12805 ");",
12806 format("f(\n"
12807 "#if !TEST\n"
12808 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
12809 "#endif\n"
12810 ");"));
12811 EXPECT_EQ("f(\n"
12812 "\n"
12813 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
12814 format("f(\n"
12815 "\n"
12816 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
12817 }
12818
TEST_F(FormatTest,BreaksStringLiteralOperands)12819 TEST_F(FormatTest, BreaksStringLiteralOperands) {
12820 // In a function call with two operands, the second can be broken with no line
12821 // break before it.
12822 EXPECT_EQ(
12823 "func(a, \"long long \"\n"
12824 " \"long long\");",
12825 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
12826 // In a function call with three operands, the second must be broken with a
12827 // line break before it.
12828 EXPECT_EQ("func(a,\n"
12829 " \"long long long \"\n"
12830 " \"long\",\n"
12831 " c);",
12832 format("func(a, \"long long long long\", c);",
12833 getLLVMStyleWithColumns(24)));
12834 // In a function call with three operands, the third must be broken with a
12835 // line break before it.
12836 EXPECT_EQ("func(a, b,\n"
12837 " \"long long long \"\n"
12838 " \"long\");",
12839 format("func(a, b, \"long long long long\");",
12840 getLLVMStyleWithColumns(24)));
12841 // In a function call with three operands, both the second and the third must
12842 // be broken with a line break before them.
12843 EXPECT_EQ("func(a,\n"
12844 " \"long long long \"\n"
12845 " \"long\",\n"
12846 " \"long long long \"\n"
12847 " \"long\");",
12848 format("func(a, \"long long long long\", \"long long long long\");",
12849 getLLVMStyleWithColumns(24)));
12850 // In a chain of << with two operands, the second can be broken with no line
12851 // break before it.
12852 EXPECT_EQ("a << \"line line \"\n"
12853 " \"line\";",
12854 format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
12855 // In a chain of << with three operands, the second can be broken with no line
12856 // break before it.
12857 EXPECT_EQ(
12858 "abcde << \"line \"\n"
12859 " \"line line\"\n"
12860 " << c;",
12861 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
12862 // In a chain of << with three operands, the third must be broken with a line
12863 // break before it.
12864 EXPECT_EQ(
12865 "a << b\n"
12866 " << \"line line \"\n"
12867 " \"line\";",
12868 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
12869 // In a chain of << with three operands, the second can be broken with no line
12870 // break before it and the third must be broken with a line break before it.
12871 EXPECT_EQ("abcd << \"line line \"\n"
12872 " \"line\"\n"
12873 " << \"line line \"\n"
12874 " \"line\";",
12875 format("abcd << \"line line line\" << \"line line line\";",
12876 getLLVMStyleWithColumns(20)));
12877 // In a chain of binary operators with two operands, the second can be broken
12878 // with no line break before it.
12879 EXPECT_EQ(
12880 "abcd + \"line line \"\n"
12881 " \"line line\";",
12882 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
12883 // In a chain of binary operators with three operands, the second must be
12884 // broken with a line break before it.
12885 EXPECT_EQ("abcd +\n"
12886 " \"line line \"\n"
12887 " \"line line\" +\n"
12888 " e;",
12889 format("abcd + \"line line line line\" + e;",
12890 getLLVMStyleWithColumns(20)));
12891 // In a function call with two operands, with AlignAfterOpenBracket enabled,
12892 // the first must be broken with a line break before it.
12893 FormatStyle Style = getLLVMStyleWithColumns(25);
12894 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12895 EXPECT_EQ("someFunction(\n"
12896 " \"long long long \"\n"
12897 " \"long\",\n"
12898 " a);",
12899 format("someFunction(\"long long long long\", a);", Style));
12900 }
12901
TEST_F(FormatTest,DontSplitStringLiteralsWithEscapedNewlines)12902 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
12903 EXPECT_EQ(
12904 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12905 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12906 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12907 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12908 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
12910 }
12911
TEST_F(FormatTest,CountsCharactersInMultilineRawStringLiterals)12912 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
12913 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
12914 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle()));
12915 EXPECT_EQ("fffffffffff(g(R\"x(\n"
12916 "multiline raw string literal xxxxxxxxxxxxxx\n"
12917 ")x\",\n"
12918 " a),\n"
12919 " b);",
12920 format("fffffffffff(g(R\"x(\n"
12921 "multiline raw string literal xxxxxxxxxxxxxx\n"
12922 ")x\", a), b);",
12923 getGoogleStyleWithColumns(20)));
12924 EXPECT_EQ("fffffffffff(\n"
12925 " g(R\"x(qqq\n"
12926 "multiline raw string literal xxxxxxxxxxxxxx\n"
12927 ")x\",\n"
12928 " a),\n"
12929 " b);",
12930 format("fffffffffff(g(R\"x(qqq\n"
12931 "multiline raw string literal xxxxxxxxxxxxxx\n"
12932 ")x\", a), b);",
12933 getGoogleStyleWithColumns(20)));
12934
12935 EXPECT_EQ("fffffffffff(R\"x(\n"
12936 "multiline raw string literal xxxxxxxxxxxxxx\n"
12937 ")x\");",
12938 format("fffffffffff(R\"x(\n"
12939 "multiline raw string literal xxxxxxxxxxxxxx\n"
12940 ")x\");",
12941 getGoogleStyleWithColumns(20)));
12942 EXPECT_EQ("fffffffffff(R\"x(\n"
12943 "multiline raw string literal xxxxxxxxxxxxxx\n"
12944 ")x\" + bbbbbb);",
12945 format("fffffffffff(R\"x(\n"
12946 "multiline raw string literal xxxxxxxxxxxxxx\n"
12947 ")x\" + bbbbbb);",
12948 getGoogleStyleWithColumns(20)));
12949 EXPECT_EQ("fffffffffff(\n"
12950 " R\"x(\n"
12951 "multiline raw string literal xxxxxxxxxxxxxx\n"
12952 ")x\" +\n"
12953 " bbbbbb);",
12954 format("fffffffffff(\n"
12955 " R\"x(\n"
12956 "multiline raw string literal xxxxxxxxxxxxxx\n"
12957 ")x\" + bbbbbb);",
12958 getGoogleStyleWithColumns(20)));
12959 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
12960 format("fffffffffff(\n"
12961 " R\"(single line raw string)\" + bbbbbb);"));
12962 }
12963
TEST_F(FormatTest,SkipsUnknownStringLiterals)12964 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
12965 verifyFormat("string a = \"unterminated;");
12966 EXPECT_EQ("function(\"unterminated,\n"
12967 " OtherParameter);",
12968 format("function( \"unterminated,\n"
12969 " OtherParameter);"));
12970 }
12971
TEST_F(FormatTest,DoesNotTryToParseUDLiteralsInPreCpp11Code)12972 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
12973 FormatStyle Style = getLLVMStyle();
12974 Style.Standard = FormatStyle::LS_Cpp03;
12975 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
12976 format("#define x(_a) printf(\"foo\"_a);", Style));
12977 }
12978
TEST_F(FormatTest,CppLexVersion)12979 TEST_F(FormatTest, CppLexVersion) {
12980 FormatStyle Style = getLLVMStyle();
12981 // Formatting of x * y differs if x is a type.
12982 verifyFormat("void foo() { MACRO(a * b); }", Style);
12983 verifyFormat("void foo() { MACRO(int *b); }", Style);
12984
12985 // LLVM style uses latest lexer.
12986 verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
12987 Style.Standard = FormatStyle::LS_Cpp17;
12988 // But in c++17, char8_t isn't a keyword.
12989 verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
12990 }
12991
TEST_F(FormatTest,UnderstandsCpp1y)12992 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
12993
TEST_F(FormatTest,BreakStringLiteralsBeforeUnbreakableTokenSequence)12994 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
12995 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
12996 " \"ddeeefff\");",
12997 format("someFunction(\"aaabbbcccdddeeefff\");",
12998 getLLVMStyleWithColumns(25)));
12999 EXPECT_EQ("someFunction1234567890(\n"
13000 " \"aaabbbcccdddeeefff\");",
13001 format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13002 getLLVMStyleWithColumns(26)));
13003 EXPECT_EQ("someFunction1234567890(\n"
13004 " \"aaabbbcccdddeeeff\"\n"
13005 " \"f\");",
13006 format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13007 getLLVMStyleWithColumns(25)));
13008 EXPECT_EQ("someFunction1234567890(\n"
13009 " \"aaabbbcccdddeeeff\"\n"
13010 " \"f\");",
13011 format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13012 getLLVMStyleWithColumns(24)));
13013 EXPECT_EQ("someFunction(\n"
13014 " \"aaabbbcc ddde \"\n"
13015 " \"efff\");",
13016 format("someFunction(\"aaabbbcc ddde efff\");",
13017 getLLVMStyleWithColumns(25)));
13018 EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13019 " \"ddeeefff\");",
13020 format("someFunction(\"aaabbbccc ddeeefff\");",
13021 getLLVMStyleWithColumns(25)));
13022 EXPECT_EQ("someFunction1234567890(\n"
13023 " \"aaabb \"\n"
13024 " \"cccdddeeefff\");",
13025 format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13026 getLLVMStyleWithColumns(25)));
13027 EXPECT_EQ("#define A \\\n"
13028 " string s = \\\n"
13029 " \"123456789\" \\\n"
13030 " \"0\"; \\\n"
13031 " int i;",
13032 format("#define A string s = \"1234567890\"; int i;",
13033 getLLVMStyleWithColumns(20)));
13034 EXPECT_EQ("someFunction(\n"
13035 " \"aaabbbcc \"\n"
13036 " \"dddeeefff\");",
13037 format("someFunction(\"aaabbbcc dddeeefff\");",
13038 getLLVMStyleWithColumns(25)));
13039 }
13040
TEST_F(FormatTest,DoNotBreakStringLiteralsInEscapeSequence)13041 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13042 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13043 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13044 EXPECT_EQ("\"test\"\n"
13045 "\"\\n\"",
13046 format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13047 EXPECT_EQ("\"tes\\\\\"\n"
13048 "\"n\"",
13049 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13050 EXPECT_EQ("\"\\\\\\\\\"\n"
13051 "\"\\n\"",
13052 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13053 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13054 EXPECT_EQ("\"\\uff01\"\n"
13055 "\"test\"",
13056 format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13057 EXPECT_EQ("\"\\Uff01ff02\"",
13058 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13059 EXPECT_EQ("\"\\x000000000001\"\n"
13060 "\"next\"",
13061 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13062 EXPECT_EQ("\"\\x000000000001next\"",
13063 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13064 EXPECT_EQ("\"\\x000000000001\"",
13065 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13066 EXPECT_EQ("\"test\"\n"
13067 "\"\\000000\"\n"
13068 "\"000001\"",
13069 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13070 EXPECT_EQ("\"test\\000\"\n"
13071 "\"00000000\"\n"
13072 "\"1\"",
13073 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13074 }
13075
TEST_F(FormatTest,DoNotCreateUnreasonableUnwrappedLines)13076 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13077 verifyFormat("void f() {\n"
13078 " return g() {}\n"
13079 " void h() {}");
13080 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13081 "g();\n"
13082 "}");
13083 }
13084
TEST_F(FormatTest,DoNotPrematurelyEndUnwrappedLineForReturnStatements)13085 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13086 verifyFormat(
13087 "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13088 }
13089
TEST_F(FormatTest,FormatsClosingBracesInEmptyNestedBlocks)13090 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13091 verifyFormat("class X {\n"
13092 " void f() {\n"
13093 " }\n"
13094 "};",
13095 getLLVMStyleWithColumns(12));
13096 }
13097
TEST_F(FormatTest,ConfigurableIndentWidth)13098 TEST_F(FormatTest, ConfigurableIndentWidth) {
13099 FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13100 EightIndent.IndentWidth = 8;
13101 EightIndent.ContinuationIndentWidth = 8;
13102 verifyFormat("void f() {\n"
13103 " someFunction();\n"
13104 " if (true) {\n"
13105 " f();\n"
13106 " }\n"
13107 "}",
13108 EightIndent);
13109 verifyFormat("class X {\n"
13110 " void f() {\n"
13111 " }\n"
13112 "};",
13113 EightIndent);
13114 verifyFormat("int x[] = {\n"
13115 " call(),\n"
13116 " call()};",
13117 EightIndent);
13118 }
13119
TEST_F(FormatTest,ConfigurableFunctionDeclarationIndentAfterType)13120 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13121 verifyFormat("double\n"
13122 "f();",
13123 getLLVMStyleWithColumns(8));
13124 }
13125
TEST_F(FormatTest,ConfigurableUseOfTab)13126 TEST_F(FormatTest, ConfigurableUseOfTab) {
13127 FormatStyle Tab = getLLVMStyleWithColumns(42);
13128 Tab.IndentWidth = 8;
13129 Tab.UseTab = FormatStyle::UT_Always;
13130 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13131
13132 EXPECT_EQ("if (aaaaaaaa && // q\n"
13133 " bb)\t\t// w\n"
13134 "\t;",
13135 format("if (aaaaaaaa &&// q\n"
13136 "bb)// w\n"
13137 ";",
13138 Tab));
13139 EXPECT_EQ("if (aaa && bbb) // w\n"
13140 "\t;",
13141 format("if(aaa&&bbb)// w\n"
13142 ";",
13143 Tab));
13144
13145 verifyFormat("class X {\n"
13146 "\tvoid f() {\n"
13147 "\t\tsomeFunction(parameter1,\n"
13148 "\t\t\t parameter2);\n"
13149 "\t}\n"
13150 "};",
13151 Tab);
13152 verifyFormat("#define A \\\n"
13153 "\tvoid f() { \\\n"
13154 "\t\tsomeFunction( \\\n"
13155 "\t\t parameter1, \\\n"
13156 "\t\t parameter2); \\\n"
13157 "\t}",
13158 Tab);
13159 verifyFormat("int a;\t // x\n"
13160 "int bbbbbbbb; // x\n",
13161 Tab);
13162
13163 Tab.TabWidth = 4;
13164 Tab.IndentWidth = 8;
13165 verifyFormat("class TabWidth4Indent8 {\n"
13166 "\t\tvoid f() {\n"
13167 "\t\t\t\tsomeFunction(parameter1,\n"
13168 "\t\t\t\t\t\t\t parameter2);\n"
13169 "\t\t}\n"
13170 "};",
13171 Tab);
13172
13173 Tab.TabWidth = 4;
13174 Tab.IndentWidth = 4;
13175 verifyFormat("class TabWidth4Indent4 {\n"
13176 "\tvoid f() {\n"
13177 "\t\tsomeFunction(parameter1,\n"
13178 "\t\t\t\t\t parameter2);\n"
13179 "\t}\n"
13180 "};",
13181 Tab);
13182
13183 Tab.TabWidth = 8;
13184 Tab.IndentWidth = 4;
13185 verifyFormat("class TabWidth8Indent4 {\n"
13186 " void f() {\n"
13187 "\tsomeFunction(parameter1,\n"
13188 "\t\t parameter2);\n"
13189 " }\n"
13190 "};",
13191 Tab);
13192
13193 Tab.TabWidth = 8;
13194 Tab.IndentWidth = 8;
13195 EXPECT_EQ("/*\n"
13196 "\t a\t\tcomment\n"
13197 "\t in multiple lines\n"
13198 " */",
13199 format(" /*\t \t \n"
13200 " \t \t a\t\tcomment\t \t\n"
13201 " \t \t in multiple lines\t\n"
13202 " \t */",
13203 Tab));
13204
13205 Tab.UseTab = FormatStyle::UT_ForIndentation;
13206 verifyFormat("{\n"
13207 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13208 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13209 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13210 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13211 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13212 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13213 "};",
13214 Tab);
13215 verifyFormat("enum AA {\n"
13216 "\ta1, // Force multiple lines\n"
13217 "\ta2,\n"
13218 "\ta3\n"
13219 "};",
13220 Tab);
13221 EXPECT_EQ("if (aaaaaaaa && // q\n"
13222 " bb) // w\n"
13223 "\t;",
13224 format("if (aaaaaaaa &&// q\n"
13225 "bb)// w\n"
13226 ";",
13227 Tab));
13228 verifyFormat("class X {\n"
13229 "\tvoid f() {\n"
13230 "\t\tsomeFunction(parameter1,\n"
13231 "\t\t parameter2);\n"
13232 "\t}\n"
13233 "};",
13234 Tab);
13235 verifyFormat("{\n"
13236 "\tQ(\n"
13237 "\t {\n"
13238 "\t\t int a;\n"
13239 "\t\t someFunction(aaaaaaaa,\n"
13240 "\t\t bbbbbbb);\n"
13241 "\t },\n"
13242 "\t p);\n"
13243 "}",
13244 Tab);
13245 EXPECT_EQ("{\n"
13246 "\t/* aaaa\n"
13247 "\t bbbb */\n"
13248 "}",
13249 format("{\n"
13250 "/* aaaa\n"
13251 " bbbb */\n"
13252 "}",
13253 Tab));
13254 EXPECT_EQ("{\n"
13255 "\t/*\n"
13256 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13257 "\t bbbbbbbbbbbbb\n"
13258 "\t*/\n"
13259 "}",
13260 format("{\n"
13261 "/*\n"
13262 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13263 "*/\n"
13264 "}",
13265 Tab));
13266 EXPECT_EQ("{\n"
13267 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13268 "\t// bbbbbbbbbbbbb\n"
13269 "}",
13270 format("{\n"
13271 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13272 "}",
13273 Tab));
13274 EXPECT_EQ("{\n"
13275 "\t/*\n"
13276 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13277 "\t bbbbbbbbbbbbb\n"
13278 "\t*/\n"
13279 "}",
13280 format("{\n"
13281 "\t/*\n"
13282 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13283 "\t*/\n"
13284 "}",
13285 Tab));
13286 EXPECT_EQ("{\n"
13287 "\t/*\n"
13288 "\n"
13289 "\t*/\n"
13290 "}",
13291 format("{\n"
13292 "\t/*\n"
13293 "\n"
13294 "\t*/\n"
13295 "}",
13296 Tab));
13297 EXPECT_EQ("{\n"
13298 "\t/*\n"
13299 " asdf\n"
13300 "\t*/\n"
13301 "}",
13302 format("{\n"
13303 "\t/*\n"
13304 " asdf\n"
13305 "\t*/\n"
13306 "}",
13307 Tab));
13308
13309 Tab.UseTab = FormatStyle::UT_Never;
13310 EXPECT_EQ("/*\n"
13311 " a\t\tcomment\n"
13312 " in multiple lines\n"
13313 " */",
13314 format(" /*\t \t \n"
13315 " \t \t a\t\tcomment\t \t\n"
13316 " \t \t in multiple lines\t\n"
13317 " \t */",
13318 Tab));
13319 EXPECT_EQ("/* some\n"
13320 " comment */",
13321 format(" \t \t /* some\n"
13322 " \t \t comment */",
13323 Tab));
13324 EXPECT_EQ("int a; /* some\n"
13325 " comment */",
13326 format(" \t \t int a; /* some\n"
13327 " \t \t comment */",
13328 Tab));
13329
13330 EXPECT_EQ("int a; /* some\n"
13331 "comment */",
13332 format(" \t \t int\ta; /* some\n"
13333 " \t \t comment */",
13334 Tab));
13335 EXPECT_EQ("f(\"\t\t\"); /* some\n"
13336 " comment */",
13337 format(" \t \t f(\"\t\t\"); /* some\n"
13338 " \t \t comment */",
13339 Tab));
13340 EXPECT_EQ("{\n"
13341 " /*\n"
13342 " * Comment\n"
13343 " */\n"
13344 " int i;\n"
13345 "}",
13346 format("{\n"
13347 "\t/*\n"
13348 "\t * Comment\n"
13349 "\t */\n"
13350 "\t int i;\n"
13351 "}",
13352 Tab));
13353
13354 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13355 Tab.TabWidth = 8;
13356 Tab.IndentWidth = 8;
13357 EXPECT_EQ("if (aaaaaaaa && // q\n"
13358 " bb) // w\n"
13359 "\t;",
13360 format("if (aaaaaaaa &&// q\n"
13361 "bb)// w\n"
13362 ";",
13363 Tab));
13364 EXPECT_EQ("if (aaa && bbb) // w\n"
13365 "\t;",
13366 format("if(aaa&&bbb)// w\n"
13367 ";",
13368 Tab));
13369 verifyFormat("class X {\n"
13370 "\tvoid f() {\n"
13371 "\t\tsomeFunction(parameter1,\n"
13372 "\t\t\t parameter2);\n"
13373 "\t}\n"
13374 "};",
13375 Tab);
13376 verifyFormat("#define A \\\n"
13377 "\tvoid f() { \\\n"
13378 "\t\tsomeFunction( \\\n"
13379 "\t\t parameter1, \\\n"
13380 "\t\t parameter2); \\\n"
13381 "\t}",
13382 Tab);
13383 Tab.TabWidth = 4;
13384 Tab.IndentWidth = 8;
13385 verifyFormat("class TabWidth4Indent8 {\n"
13386 "\t\tvoid f() {\n"
13387 "\t\t\t\tsomeFunction(parameter1,\n"
13388 "\t\t\t\t\t\t\t parameter2);\n"
13389 "\t\t}\n"
13390 "};",
13391 Tab);
13392 Tab.TabWidth = 4;
13393 Tab.IndentWidth = 4;
13394 verifyFormat("class TabWidth4Indent4 {\n"
13395 "\tvoid f() {\n"
13396 "\t\tsomeFunction(parameter1,\n"
13397 "\t\t\t\t\t parameter2);\n"
13398 "\t}\n"
13399 "};",
13400 Tab);
13401 Tab.TabWidth = 8;
13402 Tab.IndentWidth = 4;
13403 verifyFormat("class TabWidth8Indent4 {\n"
13404 " void f() {\n"
13405 "\tsomeFunction(parameter1,\n"
13406 "\t\t parameter2);\n"
13407 " }\n"
13408 "};",
13409 Tab);
13410 Tab.TabWidth = 8;
13411 Tab.IndentWidth = 8;
13412 EXPECT_EQ("/*\n"
13413 "\t a\t\tcomment\n"
13414 "\t in multiple lines\n"
13415 " */",
13416 format(" /*\t \t \n"
13417 " \t \t a\t\tcomment\t \t\n"
13418 " \t \t in multiple lines\t\n"
13419 " \t */",
13420 Tab));
13421 verifyFormat("{\n"
13422 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13423 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13424 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13425 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13426 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13427 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13428 "};",
13429 Tab);
13430 verifyFormat("enum AA {\n"
13431 "\ta1, // Force multiple lines\n"
13432 "\ta2,\n"
13433 "\ta3\n"
13434 "};",
13435 Tab);
13436 EXPECT_EQ("if (aaaaaaaa && // q\n"
13437 " bb) // w\n"
13438 "\t;",
13439 format("if (aaaaaaaa &&// q\n"
13440 "bb)// w\n"
13441 ";",
13442 Tab));
13443 verifyFormat("class X {\n"
13444 "\tvoid f() {\n"
13445 "\t\tsomeFunction(parameter1,\n"
13446 "\t\t\t parameter2);\n"
13447 "\t}\n"
13448 "};",
13449 Tab);
13450 verifyFormat("{\n"
13451 "\tQ(\n"
13452 "\t {\n"
13453 "\t\t int a;\n"
13454 "\t\t someFunction(aaaaaaaa,\n"
13455 "\t\t\t\t bbbbbbb);\n"
13456 "\t },\n"
13457 "\t p);\n"
13458 "}",
13459 Tab);
13460 EXPECT_EQ("{\n"
13461 "\t/* aaaa\n"
13462 "\t bbbb */\n"
13463 "}",
13464 format("{\n"
13465 "/* aaaa\n"
13466 " bbbb */\n"
13467 "}",
13468 Tab));
13469 EXPECT_EQ("{\n"
13470 "\t/*\n"
13471 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13472 "\t bbbbbbbbbbbbb\n"
13473 "\t*/\n"
13474 "}",
13475 format("{\n"
13476 "/*\n"
13477 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13478 "*/\n"
13479 "}",
13480 Tab));
13481 EXPECT_EQ("{\n"
13482 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13483 "\t// bbbbbbbbbbbbb\n"
13484 "}",
13485 format("{\n"
13486 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13487 "}",
13488 Tab));
13489 EXPECT_EQ("{\n"
13490 "\t/*\n"
13491 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13492 "\t bbbbbbbbbbbbb\n"
13493 "\t*/\n"
13494 "}",
13495 format("{\n"
13496 "\t/*\n"
13497 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13498 "\t*/\n"
13499 "}",
13500 Tab));
13501 EXPECT_EQ("{\n"
13502 "\t/*\n"
13503 "\n"
13504 "\t*/\n"
13505 "}",
13506 format("{\n"
13507 "\t/*\n"
13508 "\n"
13509 "\t*/\n"
13510 "}",
13511 Tab));
13512 EXPECT_EQ("{\n"
13513 "\t/*\n"
13514 " asdf\n"
13515 "\t*/\n"
13516 "}",
13517 format("{\n"
13518 "\t/*\n"
13519 " asdf\n"
13520 "\t*/\n"
13521 "}",
13522 Tab));
13523 EXPECT_EQ("/* some\n"
13524 " comment */",
13525 format(" \t \t /* some\n"
13526 " \t \t comment */",
13527 Tab));
13528 EXPECT_EQ("int a; /* some\n"
13529 " comment */",
13530 format(" \t \t int a; /* some\n"
13531 " \t \t comment */",
13532 Tab));
13533 EXPECT_EQ("int a; /* some\n"
13534 "comment */",
13535 format(" \t \t int\ta; /* some\n"
13536 " \t \t comment */",
13537 Tab));
13538 EXPECT_EQ("f(\"\t\t\"); /* some\n"
13539 " comment */",
13540 format(" \t \t f(\"\t\t\"); /* some\n"
13541 " \t \t comment */",
13542 Tab));
13543 EXPECT_EQ("{\n"
13544 "\t/*\n"
13545 "\t * Comment\n"
13546 "\t */\n"
13547 "\tint i;\n"
13548 "}",
13549 format("{\n"
13550 "\t/*\n"
13551 "\t * Comment\n"
13552 "\t */\n"
13553 "\t int i;\n"
13554 "}",
13555 Tab));
13556 Tab.TabWidth = 2;
13557 Tab.IndentWidth = 2;
13558 EXPECT_EQ("{\n"
13559 "\t/* aaaa\n"
13560 "\t\t bbbb */\n"
13561 "}",
13562 format("{\n"
13563 "/* aaaa\n"
13564 "\t bbbb */\n"
13565 "}",
13566 Tab));
13567 EXPECT_EQ("{\n"
13568 "\t/*\n"
13569 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13570 "\t\tbbbbbbbbbbbbb\n"
13571 "\t*/\n"
13572 "}",
13573 format("{\n"
13574 "/*\n"
13575 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13576 "*/\n"
13577 "}",
13578 Tab));
13579 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13580 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13581 Tab.TabWidth = 4;
13582 Tab.IndentWidth = 4;
13583 verifyFormat("class Assign {\n"
13584 "\tvoid f() {\n"
13585 "\t\tint x = 123;\n"
13586 "\t\tint random = 4;\n"
13587 "\t\tstd::string alphabet =\n"
13588 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13589 "\t}\n"
13590 "};",
13591 Tab);
13592
13593 Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13594 Tab.TabWidth = 8;
13595 Tab.IndentWidth = 8;
13596 EXPECT_EQ("if (aaaaaaaa && // q\n"
13597 " bb) // w\n"
13598 "\t;",
13599 format("if (aaaaaaaa &&// q\n"
13600 "bb)// w\n"
13601 ";",
13602 Tab));
13603 EXPECT_EQ("if (aaa && bbb) // w\n"
13604 "\t;",
13605 format("if(aaa&&bbb)// w\n"
13606 ";",
13607 Tab));
13608 verifyFormat("class X {\n"
13609 "\tvoid f() {\n"
13610 "\t\tsomeFunction(parameter1,\n"
13611 "\t\t parameter2);\n"
13612 "\t}\n"
13613 "};",
13614 Tab);
13615 verifyFormat("#define A \\\n"
13616 "\tvoid f() { \\\n"
13617 "\t\tsomeFunction( \\\n"
13618 "\t\t parameter1, \\\n"
13619 "\t\t parameter2); \\\n"
13620 "\t}",
13621 Tab);
13622 Tab.TabWidth = 4;
13623 Tab.IndentWidth = 8;
13624 verifyFormat("class TabWidth4Indent8 {\n"
13625 "\t\tvoid f() {\n"
13626 "\t\t\t\tsomeFunction(parameter1,\n"
13627 "\t\t\t\t parameter2);\n"
13628 "\t\t}\n"
13629 "};",
13630 Tab);
13631 Tab.TabWidth = 4;
13632 Tab.IndentWidth = 4;
13633 verifyFormat("class TabWidth4Indent4 {\n"
13634 "\tvoid f() {\n"
13635 "\t\tsomeFunction(parameter1,\n"
13636 "\t\t parameter2);\n"
13637 "\t}\n"
13638 "};",
13639 Tab);
13640 Tab.TabWidth = 8;
13641 Tab.IndentWidth = 4;
13642 verifyFormat("class TabWidth8Indent4 {\n"
13643 " void f() {\n"
13644 "\tsomeFunction(parameter1,\n"
13645 "\t parameter2);\n"
13646 " }\n"
13647 "};",
13648 Tab);
13649 Tab.TabWidth = 8;
13650 Tab.IndentWidth = 8;
13651 EXPECT_EQ("/*\n"
13652 " a\t\tcomment\n"
13653 " in multiple lines\n"
13654 " */",
13655 format(" /*\t \t \n"
13656 " \t \t a\t\tcomment\t \t\n"
13657 " \t \t in multiple lines\t\n"
13658 " \t */",
13659 Tab));
13660 verifyFormat("{\n"
13661 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13662 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13663 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13664 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13665 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13666 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13667 "};",
13668 Tab);
13669 verifyFormat("enum AA {\n"
13670 "\ta1, // Force multiple lines\n"
13671 "\ta2,\n"
13672 "\ta3\n"
13673 "};",
13674 Tab);
13675 EXPECT_EQ("if (aaaaaaaa && // q\n"
13676 " bb) // w\n"
13677 "\t;",
13678 format("if (aaaaaaaa &&// q\n"
13679 "bb)// w\n"
13680 ";",
13681 Tab));
13682 verifyFormat("class X {\n"
13683 "\tvoid f() {\n"
13684 "\t\tsomeFunction(parameter1,\n"
13685 "\t\t parameter2);\n"
13686 "\t}\n"
13687 "};",
13688 Tab);
13689 verifyFormat("{\n"
13690 "\tQ(\n"
13691 "\t {\n"
13692 "\t\t int a;\n"
13693 "\t\t someFunction(aaaaaaaa,\n"
13694 "\t\t bbbbbbb);\n"
13695 "\t },\n"
13696 "\t p);\n"
13697 "}",
13698 Tab);
13699 EXPECT_EQ("{\n"
13700 "\t/* aaaa\n"
13701 "\t bbbb */\n"
13702 "}",
13703 format("{\n"
13704 "/* aaaa\n"
13705 " bbbb */\n"
13706 "}",
13707 Tab));
13708 EXPECT_EQ("{\n"
13709 "\t/*\n"
13710 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13711 "\t bbbbbbbbbbbbb\n"
13712 "\t*/\n"
13713 "}",
13714 format("{\n"
13715 "/*\n"
13716 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13717 "*/\n"
13718 "}",
13719 Tab));
13720 EXPECT_EQ("{\n"
13721 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13722 "\t// bbbbbbbbbbbbb\n"
13723 "}",
13724 format("{\n"
13725 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13726 "}",
13727 Tab));
13728 EXPECT_EQ("{\n"
13729 "\t/*\n"
13730 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13731 "\t bbbbbbbbbbbbb\n"
13732 "\t*/\n"
13733 "}",
13734 format("{\n"
13735 "\t/*\n"
13736 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13737 "\t*/\n"
13738 "}",
13739 Tab));
13740 EXPECT_EQ("{\n"
13741 "\t/*\n"
13742 "\n"
13743 "\t*/\n"
13744 "}",
13745 format("{\n"
13746 "\t/*\n"
13747 "\n"
13748 "\t*/\n"
13749 "}",
13750 Tab));
13751 EXPECT_EQ("{\n"
13752 "\t/*\n"
13753 " asdf\n"
13754 "\t*/\n"
13755 "}",
13756 format("{\n"
13757 "\t/*\n"
13758 " asdf\n"
13759 "\t*/\n"
13760 "}",
13761 Tab));
13762 EXPECT_EQ("/* some\n"
13763 " comment */",
13764 format(" \t \t /* some\n"
13765 " \t \t comment */",
13766 Tab));
13767 EXPECT_EQ("int a; /* some\n"
13768 " comment */",
13769 format(" \t \t int a; /* some\n"
13770 " \t \t comment */",
13771 Tab));
13772 EXPECT_EQ("int a; /* some\n"
13773 "comment */",
13774 format(" \t \t int\ta; /* some\n"
13775 " \t \t comment */",
13776 Tab));
13777 EXPECT_EQ("f(\"\t\t\"); /* some\n"
13778 " comment */",
13779 format(" \t \t f(\"\t\t\"); /* some\n"
13780 " \t \t comment */",
13781 Tab));
13782 EXPECT_EQ("{\n"
13783 "\t/*\n"
13784 "\t * Comment\n"
13785 "\t */\n"
13786 "\tint i;\n"
13787 "}",
13788 format("{\n"
13789 "\t/*\n"
13790 "\t * Comment\n"
13791 "\t */\n"
13792 "\t int i;\n"
13793 "}",
13794 Tab));
13795 Tab.TabWidth = 2;
13796 Tab.IndentWidth = 2;
13797 EXPECT_EQ("{\n"
13798 "\t/* aaaa\n"
13799 "\t bbbb */\n"
13800 "}",
13801 format("{\n"
13802 "/* aaaa\n"
13803 " bbbb */\n"
13804 "}",
13805 Tab));
13806 EXPECT_EQ("{\n"
13807 "\t/*\n"
13808 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13809 "\t bbbbbbbbbbbbb\n"
13810 "\t*/\n"
13811 "}",
13812 format("{\n"
13813 "/*\n"
13814 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13815 "*/\n"
13816 "}",
13817 Tab));
13818 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13819 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13820 Tab.TabWidth = 4;
13821 Tab.IndentWidth = 4;
13822 verifyFormat("class Assign {\n"
13823 "\tvoid f() {\n"
13824 "\t\tint x = 123;\n"
13825 "\t\tint random = 4;\n"
13826 "\t\tstd::string alphabet =\n"
13827 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13828 "\t}\n"
13829 "};",
13830 Tab);
13831 Tab.AlignOperands = FormatStyle::OAS_Align;
13832 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
13833 " cccccccccccccccccccc;",
13834 Tab);
13835 // no alignment
13836 verifyFormat("int aaaaaaaaaa =\n"
13837 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
13838 Tab);
13839 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
13840 " : bbbbbbbbbbbbbb ? 222222222222222\n"
13841 " : 333333333333333;",
13842 Tab);
13843 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
13844 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
13845 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
13846 " + cccccccccccccccccccc;",
13847 Tab);
13848 }
13849
TEST_F(FormatTest,ZeroTabWidth)13850 TEST_F(FormatTest, ZeroTabWidth) {
13851 FormatStyle Tab = getLLVMStyleWithColumns(42);
13852 Tab.IndentWidth = 8;
13853 Tab.UseTab = FormatStyle::UT_Never;
13854 Tab.TabWidth = 0;
13855 EXPECT_EQ("void a(){\n"
13856 " // line starts with '\t'\n"
13857 "};",
13858 format("void a(){\n"
13859 "\t// line starts with '\t'\n"
13860 "};",
13861 Tab));
13862
13863 EXPECT_EQ("void a(){\n"
13864 " // line starts with '\t'\n"
13865 "};",
13866 format("void a(){\n"
13867 "\t\t// line starts with '\t'\n"
13868 "};",
13869 Tab));
13870
13871 Tab.UseTab = FormatStyle::UT_ForIndentation;
13872 EXPECT_EQ("void a(){\n"
13873 " // line starts with '\t'\n"
13874 "};",
13875 format("void a(){\n"
13876 "\t// line starts with '\t'\n"
13877 "};",
13878 Tab));
13879
13880 EXPECT_EQ("void a(){\n"
13881 " // line starts with '\t'\n"
13882 "};",
13883 format("void a(){\n"
13884 "\t\t// line starts with '\t'\n"
13885 "};",
13886 Tab));
13887
13888 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13889 EXPECT_EQ("void a(){\n"
13890 " // line starts with '\t'\n"
13891 "};",
13892 format("void a(){\n"
13893 "\t// line starts with '\t'\n"
13894 "};",
13895 Tab));
13896
13897 EXPECT_EQ("void a(){\n"
13898 " // line starts with '\t'\n"
13899 "};",
13900 format("void a(){\n"
13901 "\t\t// line starts with '\t'\n"
13902 "};",
13903 Tab));
13904
13905 Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13906 EXPECT_EQ("void a(){\n"
13907 " // line starts with '\t'\n"
13908 "};",
13909 format("void a(){\n"
13910 "\t// line starts with '\t'\n"
13911 "};",
13912 Tab));
13913
13914 EXPECT_EQ("void a(){\n"
13915 " // line starts with '\t'\n"
13916 "};",
13917 format("void a(){\n"
13918 "\t\t// line starts with '\t'\n"
13919 "};",
13920 Tab));
13921
13922 Tab.UseTab = FormatStyle::UT_Always;
13923 EXPECT_EQ("void a(){\n"
13924 "// line starts with '\t'\n"
13925 "};",
13926 format("void a(){\n"
13927 "\t// line starts with '\t'\n"
13928 "};",
13929 Tab));
13930
13931 EXPECT_EQ("void a(){\n"
13932 "// line starts with '\t'\n"
13933 "};",
13934 format("void a(){\n"
13935 "\t\t// line starts with '\t'\n"
13936 "};",
13937 Tab));
13938 }
13939
TEST_F(FormatTest,CalculatesOriginalColumn)13940 TEST_F(FormatTest, CalculatesOriginalColumn) {
13941 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13942 "q\"; /* some\n"
13943 " comment */",
13944 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13945 "q\"; /* some\n"
13946 " comment */",
13947 getLLVMStyle()));
13948 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13949 "/* some\n"
13950 " comment */",
13951 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13952 " /* some\n"
13953 " comment */",
13954 getLLVMStyle()));
13955 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13956 "qqq\n"
13957 "/* some\n"
13958 " comment */",
13959 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13960 "qqq\n"
13961 " /* some\n"
13962 " comment */",
13963 getLLVMStyle()));
13964 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13965 "wwww; /* some\n"
13966 " comment */",
13967 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13968 "wwww; /* some\n"
13969 " comment */",
13970 getLLVMStyle()));
13971 }
13972
TEST_F(FormatTest,ConfigurableSpaceBeforeParens)13973 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
13974 FormatStyle NoSpace = getLLVMStyle();
13975 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
13976
13977 verifyFormat("while(true)\n"
13978 " continue;",
13979 NoSpace);
13980 verifyFormat("for(;;)\n"
13981 " continue;",
13982 NoSpace);
13983 verifyFormat("if(true)\n"
13984 " f();\n"
13985 "else if(true)\n"
13986 " f();",
13987 NoSpace);
13988 verifyFormat("do {\n"
13989 " do_something();\n"
13990 "} while(something());",
13991 NoSpace);
13992 verifyFormat("switch(x) {\n"
13993 "default:\n"
13994 " break;\n"
13995 "}",
13996 NoSpace);
13997 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
13998 verifyFormat("size_t x = sizeof(x);", NoSpace);
13999 verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14000 verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14001 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14002 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14003 verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14004 verifyFormat("alignas(128) char a[128];", NoSpace);
14005 verifyFormat("size_t x = alignof(MyType);", NoSpace);
14006 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14007 verifyFormat("int f() throw(Deprecated);", NoSpace);
14008 verifyFormat("typedef void (*cb)(int);", NoSpace);
14009 verifyFormat("T A::operator()();", NoSpace);
14010 verifyFormat("X A::operator++(T);", NoSpace);
14011 verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14012
14013 FormatStyle Space = getLLVMStyle();
14014 Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14015
14016 verifyFormat("int f ();", Space);
14017 verifyFormat("void f (int a, T b) {\n"
14018 " while (true)\n"
14019 " continue;\n"
14020 "}",
14021 Space);
14022 verifyFormat("if (true)\n"
14023 " f ();\n"
14024 "else if (true)\n"
14025 " f ();",
14026 Space);
14027 verifyFormat("do {\n"
14028 " do_something ();\n"
14029 "} while (something ());",
14030 Space);
14031 verifyFormat("switch (x) {\n"
14032 "default:\n"
14033 " break;\n"
14034 "}",
14035 Space);
14036 verifyFormat("A::A () : a (1) {}", Space);
14037 verifyFormat("void f () __attribute__ ((asdf));", Space);
14038 verifyFormat("*(&a + 1);\n"
14039 "&((&a)[1]);\n"
14040 "a[(b + c) * d];\n"
14041 "(((a + 1) * 2) + 3) * 4;",
14042 Space);
14043 verifyFormat("#define A(x) x", Space);
14044 verifyFormat("#define A (x) x", Space);
14045 verifyFormat("#if defined(x)\n"
14046 "#endif",
14047 Space);
14048 verifyFormat("auto i = std::make_unique<int> (5);", Space);
14049 verifyFormat("size_t x = sizeof (x);", Space);
14050 verifyFormat("auto f (int x) -> decltype (x);", Space);
14051 verifyFormat("auto f (int x) -> typeof (x);", Space);
14052 verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14053 verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14054 verifyFormat("int f (T x) noexcept (x.create ());", Space);
14055 verifyFormat("alignas (128) char a[128];", Space);
14056 verifyFormat("size_t x = alignof (MyType);", Space);
14057 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14058 verifyFormat("int f () throw (Deprecated);", Space);
14059 verifyFormat("typedef void (*cb) (int);", Space);
14060 verifyFormat("T A::operator() ();", Space);
14061 verifyFormat("X A::operator++ (T);", Space);
14062 verifyFormat("auto lambda = [] () { return 0; };", Space);
14063 verifyFormat("int x = int (y);", Space);
14064
14065 FormatStyle SomeSpace = getLLVMStyle();
14066 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14067
14068 verifyFormat("[]() -> float {}", SomeSpace);
14069 verifyFormat("[] (auto foo) {}", SomeSpace);
14070 verifyFormat("[foo]() -> int {}", SomeSpace);
14071 verifyFormat("int f();", SomeSpace);
14072 verifyFormat("void f (int a, T b) {\n"
14073 " while (true)\n"
14074 " continue;\n"
14075 "}",
14076 SomeSpace);
14077 verifyFormat("if (true)\n"
14078 " f();\n"
14079 "else if (true)\n"
14080 " f();",
14081 SomeSpace);
14082 verifyFormat("do {\n"
14083 " do_something();\n"
14084 "} while (something());",
14085 SomeSpace);
14086 verifyFormat("switch (x) {\n"
14087 "default:\n"
14088 " break;\n"
14089 "}",
14090 SomeSpace);
14091 verifyFormat("A::A() : a (1) {}", SomeSpace);
14092 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14093 verifyFormat("*(&a + 1);\n"
14094 "&((&a)[1]);\n"
14095 "a[(b + c) * d];\n"
14096 "(((a + 1) * 2) + 3) * 4;",
14097 SomeSpace);
14098 verifyFormat("#define A(x) x", SomeSpace);
14099 verifyFormat("#define A (x) x", SomeSpace);
14100 verifyFormat("#if defined(x)\n"
14101 "#endif",
14102 SomeSpace);
14103 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14104 verifyFormat("size_t x = sizeof (x);", SomeSpace);
14105 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14106 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14107 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14108 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14109 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14110 verifyFormat("alignas (128) char a[128];", SomeSpace);
14111 verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14112 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14113 SomeSpace);
14114 verifyFormat("int f() throw (Deprecated);", SomeSpace);
14115 verifyFormat("typedef void (*cb) (int);", SomeSpace);
14116 verifyFormat("T A::operator()();", SomeSpace);
14117 verifyFormat("X A::operator++ (T);", SomeSpace);
14118 verifyFormat("int x = int (y);", SomeSpace);
14119 verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14120 }
14121
TEST_F(FormatTest,SpaceAfterLogicalNot)14122 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14123 FormatStyle Spaces = getLLVMStyle();
14124 Spaces.SpaceAfterLogicalNot = true;
14125
14126 verifyFormat("bool x = ! y", Spaces);
14127 verifyFormat("if (! isFailure())", Spaces);
14128 verifyFormat("if (! (a && b))", Spaces);
14129 verifyFormat("\"Error!\"", Spaces);
14130 verifyFormat("! ! x", Spaces);
14131 }
14132
TEST_F(FormatTest,ConfigurableSpacesInParentheses)14133 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14134 FormatStyle Spaces = getLLVMStyle();
14135
14136 Spaces.SpacesInParentheses = true;
14137 verifyFormat("do_something( ::globalVar );", Spaces);
14138 verifyFormat("call( x, y, z );", Spaces);
14139 verifyFormat("call();", Spaces);
14140 verifyFormat("std::function<void( int, int )> callback;", Spaces);
14141 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14142 Spaces);
14143 verifyFormat("while ( (bool)1 )\n"
14144 " continue;",
14145 Spaces);
14146 verifyFormat("for ( ;; )\n"
14147 " continue;",
14148 Spaces);
14149 verifyFormat("if ( true )\n"
14150 " f();\n"
14151 "else if ( true )\n"
14152 " f();",
14153 Spaces);
14154 verifyFormat("do {\n"
14155 " do_something( (int)i );\n"
14156 "} while ( something() );",
14157 Spaces);
14158 verifyFormat("switch ( x ) {\n"
14159 "default:\n"
14160 " break;\n"
14161 "}",
14162 Spaces);
14163
14164 Spaces.SpacesInParentheses = false;
14165 Spaces.SpacesInCStyleCastParentheses = true;
14166 verifyFormat("Type *A = ( Type * )P;", Spaces);
14167 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14168 verifyFormat("x = ( int32 )y;", Spaces);
14169 verifyFormat("int a = ( int )(2.0f);", Spaces);
14170 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14171 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14172 verifyFormat("#define x (( int )-1)", Spaces);
14173
14174 // Run the first set of tests again with:
14175 Spaces.SpacesInParentheses = false;
14176 Spaces.SpaceInEmptyParentheses = true;
14177 Spaces.SpacesInCStyleCastParentheses = true;
14178 verifyFormat("call(x, y, z);", Spaces);
14179 verifyFormat("call( );", Spaces);
14180 verifyFormat("std::function<void(int, int)> callback;", Spaces);
14181 verifyFormat("while (( bool )1)\n"
14182 " continue;",
14183 Spaces);
14184 verifyFormat("for (;;)\n"
14185 " continue;",
14186 Spaces);
14187 verifyFormat("if (true)\n"
14188 " f( );\n"
14189 "else if (true)\n"
14190 " f( );",
14191 Spaces);
14192 verifyFormat("do {\n"
14193 " do_something(( int )i);\n"
14194 "} while (something( ));",
14195 Spaces);
14196 verifyFormat("switch (x) {\n"
14197 "default:\n"
14198 " break;\n"
14199 "}",
14200 Spaces);
14201
14202 // Run the first set of tests again with:
14203 Spaces.SpaceAfterCStyleCast = true;
14204 verifyFormat("call(x, y, z);", Spaces);
14205 verifyFormat("call( );", Spaces);
14206 verifyFormat("std::function<void(int, int)> callback;", Spaces);
14207 verifyFormat("while (( bool ) 1)\n"
14208 " continue;",
14209 Spaces);
14210 verifyFormat("for (;;)\n"
14211 " continue;",
14212 Spaces);
14213 verifyFormat("if (true)\n"
14214 " f( );\n"
14215 "else if (true)\n"
14216 " f( );",
14217 Spaces);
14218 verifyFormat("do {\n"
14219 " do_something(( int ) i);\n"
14220 "} while (something( ));",
14221 Spaces);
14222 verifyFormat("switch (x) {\n"
14223 "default:\n"
14224 " break;\n"
14225 "}",
14226 Spaces);
14227
14228 // Run subset of tests again with:
14229 Spaces.SpacesInCStyleCastParentheses = false;
14230 Spaces.SpaceAfterCStyleCast = true;
14231 verifyFormat("while ((bool) 1)\n"
14232 " continue;",
14233 Spaces);
14234 verifyFormat("do {\n"
14235 " do_something((int) i);\n"
14236 "} while (something( ));",
14237 Spaces);
14238
14239 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14240 verifyFormat("size_t idx = (size_t) a;", Spaces);
14241 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14242 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14243 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14244 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14245 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14246 Spaces.ColumnLimit = 80;
14247 Spaces.IndentWidth = 4;
14248 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14249 verifyFormat("void foo( ) {\n"
14250 " size_t foo = (*(function))(\n"
14251 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14252 "BarrrrrrrrrrrrLong,\n"
14253 " FoooooooooLooooong);\n"
14254 "}",
14255 Spaces);
14256 Spaces.SpaceAfterCStyleCast = false;
14257 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14258 verifyFormat("size_t idx = (size_t)a;", Spaces);
14259 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14260 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14261 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14262 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14263 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14264
14265 verifyFormat("void foo( ) {\n"
14266 " size_t foo = (*(function))(\n"
14267 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14268 "BarrrrrrrrrrrrLong,\n"
14269 " FoooooooooLooooong);\n"
14270 "}",
14271 Spaces);
14272 }
14273
TEST_F(FormatTest,ConfigurableSpacesInSquareBrackets)14274 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14275 verifyFormat("int a[5];");
14276 verifyFormat("a[3] += 42;");
14277
14278 FormatStyle Spaces = getLLVMStyle();
14279 Spaces.SpacesInSquareBrackets = true;
14280 // Not lambdas.
14281 verifyFormat("int a[ 5 ];", Spaces);
14282 verifyFormat("a[ 3 ] += 42;", Spaces);
14283 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14284 verifyFormat("double &operator[](int i) { return 0; }\n"
14285 "int i;",
14286 Spaces);
14287 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14288 verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14289 verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14290 // Lambdas.
14291 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14292 verifyFormat("return [ i, args... ] {};", Spaces);
14293 verifyFormat("int foo = [ &bar ]() {};", Spaces);
14294 verifyFormat("int foo = [ = ]() {};", Spaces);
14295 verifyFormat("int foo = [ & ]() {};", Spaces);
14296 verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14297 verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14298 }
14299
TEST_F(FormatTest,ConfigurableSpaceBeforeBrackets)14300 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14301 FormatStyle NoSpaceStyle = getLLVMStyle();
14302 verifyFormat("int a[5];", NoSpaceStyle);
14303 verifyFormat("a[3] += 42;", NoSpaceStyle);
14304
14305 verifyFormat("int a[1];", NoSpaceStyle);
14306 verifyFormat("int 1 [a];", NoSpaceStyle);
14307 verifyFormat("int a[1][2];", NoSpaceStyle);
14308 verifyFormat("a[7] = 5;", NoSpaceStyle);
14309 verifyFormat("int a = (f())[23];", NoSpaceStyle);
14310 verifyFormat("f([] {})", NoSpaceStyle);
14311
14312 FormatStyle Space = getLLVMStyle();
14313 Space.SpaceBeforeSquareBrackets = true;
14314 verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14315 verifyFormat("return [i, args...] {};", Space);
14316
14317 verifyFormat("int a [5];", Space);
14318 verifyFormat("a [3] += 42;", Space);
14319 verifyFormat("constexpr char hello []{\"hello\"};", Space);
14320 verifyFormat("double &operator[](int i) { return 0; }\n"
14321 "int i;",
14322 Space);
14323 verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14324 verifyFormat("int i = a [a][a]->f();", Space);
14325 verifyFormat("int i = (*b) [a]->f();", Space);
14326
14327 verifyFormat("int a [1];", Space);
14328 verifyFormat("int 1 [a];", Space);
14329 verifyFormat("int a [1][2];", Space);
14330 verifyFormat("a [7] = 5;", Space);
14331 verifyFormat("int a = (f()) [23];", Space);
14332 verifyFormat("f([] {})", Space);
14333 }
14334
TEST_F(FormatTest,ConfigurableSpaceBeforeAssignmentOperators)14335 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
14336 verifyFormat("int a = 5;");
14337 verifyFormat("a += 42;");
14338 verifyFormat("a or_eq 8;");
14339
14340 FormatStyle Spaces = getLLVMStyle();
14341 Spaces.SpaceBeforeAssignmentOperators = false;
14342 verifyFormat("int a= 5;", Spaces);
14343 verifyFormat("a+= 42;", Spaces);
14344 verifyFormat("a or_eq 8;", Spaces);
14345 }
14346
TEST_F(FormatTest,ConfigurableSpaceBeforeColon)14347 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
14348 verifyFormat("class Foo : public Bar {};");
14349 verifyFormat("Foo::Foo() : foo(1) {}");
14350 verifyFormat("for (auto a : b) {\n}");
14351 verifyFormat("int x = a ? b : c;");
14352 verifyFormat("{\n"
14353 "label0:\n"
14354 " int x = 0;\n"
14355 "}");
14356 verifyFormat("switch (x) {\n"
14357 "case 1:\n"
14358 "default:\n"
14359 "}");
14360 verifyFormat("switch (allBraces) {\n"
14361 "case 1: {\n"
14362 " break;\n"
14363 "}\n"
14364 "case 2: {\n"
14365 " [[fallthrough]];\n"
14366 "}\n"
14367 "default: {\n"
14368 " break;\n"
14369 "}\n"
14370 "}");
14371
14372 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
14373 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
14374 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
14375 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
14376 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
14377 verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
14378 verifyFormat("{\n"
14379 "label1:\n"
14380 " int x = 0;\n"
14381 "}",
14382 CtorInitializerStyle);
14383 verifyFormat("switch (x) {\n"
14384 "case 1:\n"
14385 "default:\n"
14386 "}",
14387 CtorInitializerStyle);
14388 verifyFormat("switch (allBraces) {\n"
14389 "case 1: {\n"
14390 " break;\n"
14391 "}\n"
14392 "case 2: {\n"
14393 " [[fallthrough]];\n"
14394 "}\n"
14395 "default: {\n"
14396 " break;\n"
14397 "}\n"
14398 "}",
14399 CtorInitializerStyle);
14400 CtorInitializerStyle.BreakConstructorInitializers =
14401 FormatStyle::BCIS_AfterColon;
14402 verifyFormat("Fooooooooooo::Fooooooooooo():\n"
14403 " aaaaaaaaaaaaaaaa(1),\n"
14404 " bbbbbbbbbbbbbbbb(2) {}",
14405 CtorInitializerStyle);
14406 CtorInitializerStyle.BreakConstructorInitializers =
14407 FormatStyle::BCIS_BeforeComma;
14408 verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14409 " : aaaaaaaaaaaaaaaa(1)\n"
14410 " , bbbbbbbbbbbbbbbb(2) {}",
14411 CtorInitializerStyle);
14412 CtorInitializerStyle.BreakConstructorInitializers =
14413 FormatStyle::BCIS_BeforeColon;
14414 verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14415 " : aaaaaaaaaaaaaaaa(1),\n"
14416 " bbbbbbbbbbbbbbbb(2) {}",
14417 CtorInitializerStyle);
14418 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
14419 verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14420 ": aaaaaaaaaaaaaaaa(1),\n"
14421 " bbbbbbbbbbbbbbbb(2) {}",
14422 CtorInitializerStyle);
14423
14424 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
14425 InheritanceStyle.SpaceBeforeInheritanceColon = false;
14426 verifyFormat("class Foo: public Bar {};", InheritanceStyle);
14427 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
14428 verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
14429 verifyFormat("int x = a ? b : c;", InheritanceStyle);
14430 verifyFormat("{\n"
14431 "label2:\n"
14432 " int x = 0;\n"
14433 "}",
14434 InheritanceStyle);
14435 verifyFormat("switch (x) {\n"
14436 "case 1:\n"
14437 "default:\n"
14438 "}",
14439 InheritanceStyle);
14440 verifyFormat("switch (allBraces) {\n"
14441 "case 1: {\n"
14442 " break;\n"
14443 "}\n"
14444 "case 2: {\n"
14445 " [[fallthrough]];\n"
14446 "}\n"
14447 "default: {\n"
14448 " break;\n"
14449 "}\n"
14450 "}",
14451 InheritanceStyle);
14452 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
14453 verifyFormat("class Foooooooooooooooooooooo\n"
14454 " : public aaaaaaaaaaaaaaaaaa,\n"
14455 " public bbbbbbbbbbbbbbbbbb {\n"
14456 "}",
14457 InheritanceStyle);
14458 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
14459 verifyFormat("class Foooooooooooooooooooooo:\n"
14460 " public aaaaaaaaaaaaaaaaaa,\n"
14461 " public bbbbbbbbbbbbbbbbbb {\n"
14462 "}",
14463 InheritanceStyle);
14464 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
14465 verifyFormat("class Foooooooooooooooooooooo\n"
14466 " : public aaaaaaaaaaaaaaaaaa\n"
14467 " , public bbbbbbbbbbbbbbbbbb {\n"
14468 "}",
14469 InheritanceStyle);
14470 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
14471 verifyFormat("class Foooooooooooooooooooooo\n"
14472 " : public aaaaaaaaaaaaaaaaaa,\n"
14473 " public bbbbbbbbbbbbbbbbbb {\n"
14474 "}",
14475 InheritanceStyle);
14476 InheritanceStyle.ConstructorInitializerIndentWidth = 0;
14477 verifyFormat("class Foooooooooooooooooooooo\n"
14478 ": public aaaaaaaaaaaaaaaaaa,\n"
14479 " public bbbbbbbbbbbbbbbbbb {}",
14480 InheritanceStyle);
14481
14482 FormatStyle ForLoopStyle = getLLVMStyle();
14483 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
14484 verifyFormat("class Foo : public Bar {};", ForLoopStyle);
14485 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
14486 verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
14487 verifyFormat("int x = a ? b : c;", ForLoopStyle);
14488 verifyFormat("{\n"
14489 "label2:\n"
14490 " int x = 0;\n"
14491 "}",
14492 ForLoopStyle);
14493 verifyFormat("switch (x) {\n"
14494 "case 1:\n"
14495 "default:\n"
14496 "}",
14497 ForLoopStyle);
14498 verifyFormat("switch (allBraces) {\n"
14499 "case 1: {\n"
14500 " break;\n"
14501 "}\n"
14502 "case 2: {\n"
14503 " [[fallthrough]];\n"
14504 "}\n"
14505 "default: {\n"
14506 " break;\n"
14507 "}\n"
14508 "}",
14509 ForLoopStyle);
14510
14511 FormatStyle CaseStyle = getLLVMStyle();
14512 CaseStyle.SpaceBeforeCaseColon = true;
14513 verifyFormat("class Foo : public Bar {};", CaseStyle);
14514 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
14515 verifyFormat("for (auto a : b) {\n}", CaseStyle);
14516 verifyFormat("int x = a ? b : c;", CaseStyle);
14517 verifyFormat("switch (x) {\n"
14518 "case 1 :\n"
14519 "default :\n"
14520 "}",
14521 CaseStyle);
14522 verifyFormat("switch (allBraces) {\n"
14523 "case 1 : {\n"
14524 " break;\n"
14525 "}\n"
14526 "case 2 : {\n"
14527 " [[fallthrough]];\n"
14528 "}\n"
14529 "default : {\n"
14530 " break;\n"
14531 "}\n"
14532 "}",
14533 CaseStyle);
14534
14535 FormatStyle NoSpaceStyle = getLLVMStyle();
14536 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
14537 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14538 NoSpaceStyle.SpaceBeforeInheritanceColon = false;
14539 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14540 verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
14541 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
14542 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
14543 verifyFormat("int x = a ? b : c;", NoSpaceStyle);
14544 verifyFormat("{\n"
14545 "label3:\n"
14546 " int x = 0;\n"
14547 "}",
14548 NoSpaceStyle);
14549 verifyFormat("switch (x) {\n"
14550 "case 1:\n"
14551 "default:\n"
14552 "}",
14553 NoSpaceStyle);
14554 verifyFormat("switch (allBraces) {\n"
14555 "case 1: {\n"
14556 " break;\n"
14557 "}\n"
14558 "case 2: {\n"
14559 " [[fallthrough]];\n"
14560 "}\n"
14561 "default: {\n"
14562 " break;\n"
14563 "}\n"
14564 "}",
14565 NoSpaceStyle);
14566
14567 FormatStyle InvertedSpaceStyle = getLLVMStyle();
14568 InvertedSpaceStyle.SpaceBeforeCaseColon = true;
14569 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14570 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
14571 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14572 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
14573 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
14574 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
14575 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
14576 verifyFormat("{\n"
14577 "label3:\n"
14578 " int x = 0;\n"
14579 "}",
14580 InvertedSpaceStyle);
14581 verifyFormat("switch (x) {\n"
14582 "case 1 :\n"
14583 "case 2 : {\n"
14584 " break;\n"
14585 "}\n"
14586 "default :\n"
14587 " break;\n"
14588 "}",
14589 InvertedSpaceStyle);
14590 verifyFormat("switch (allBraces) {\n"
14591 "case 1 : {\n"
14592 " break;\n"
14593 "}\n"
14594 "case 2 : {\n"
14595 " [[fallthrough]];\n"
14596 "}\n"
14597 "default : {\n"
14598 " break;\n"
14599 "}\n"
14600 "}",
14601 InvertedSpaceStyle);
14602 }
14603
TEST_F(FormatTest,ConfigurableSpaceAroundPointerQualifiers)14604 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
14605 FormatStyle Style = getLLVMStyle();
14606
14607 Style.PointerAlignment = FormatStyle::PAS_Left;
14608 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
14609 verifyFormat("void* const* x = NULL;", Style);
14610
14611 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \
14612 do { \
14613 Style.PointerAlignment = FormatStyle::Pointers; \
14614 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \
14615 verifyFormat(Code, Style); \
14616 } while (false)
14617
14618 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
14619 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
14620 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
14621
14622 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
14623 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
14624 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
14625
14626 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
14627 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
14628 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
14629
14630 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
14631 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
14632 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
14633
14634 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
14635 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
14636 SAPQ_Default);
14637 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14638 SAPQ_Default);
14639
14640 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
14641 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
14642 SAPQ_Before);
14643 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14644 SAPQ_Before);
14645
14646 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
14647 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
14648 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14649 SAPQ_After);
14650
14651 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
14652 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
14653 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
14654
14655 #undef verifyQualifierSpaces
14656
14657 FormatStyle Spaces = getLLVMStyle();
14658 Spaces.AttributeMacros.push_back("qualified");
14659 Spaces.PointerAlignment = FormatStyle::PAS_Right;
14660 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
14661 verifyFormat("SomeType *volatile *a = NULL;", Spaces);
14662 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
14663 verifyFormat("std::vector<SomeType *const *> x;", Spaces);
14664 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
14665 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14666 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
14667 verifyFormat("SomeType * volatile *a = NULL;", Spaces);
14668 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
14669 verifyFormat("std::vector<SomeType * const *> x;", Spaces);
14670 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
14671 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14672
14673 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
14674 Spaces.PointerAlignment = FormatStyle::PAS_Left;
14675 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
14676 verifyFormat("SomeType* volatile* a = NULL;", Spaces);
14677 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
14678 verifyFormat("std::vector<SomeType* const*> x;", Spaces);
14679 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
14680 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14681 // However, setting it to SAPQ_After should add spaces after __attribute, etc.
14682 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
14683 verifyFormat("SomeType* volatile * a = NULL;", Spaces);
14684 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
14685 verifyFormat("std::vector<SomeType* const *> x;", Spaces);
14686 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
14687 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14688
14689 // PAS_Middle should not have any noticeable changes even for SAPQ_Both
14690 Spaces.PointerAlignment = FormatStyle::PAS_Middle;
14691 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
14692 verifyFormat("SomeType * volatile * a = NULL;", Spaces);
14693 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
14694 verifyFormat("std::vector<SomeType * const *> x;", Spaces);
14695 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
14696 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14697 }
14698
TEST_F(FormatTest,AlignConsecutiveMacros)14699 TEST_F(FormatTest, AlignConsecutiveMacros) {
14700 FormatStyle Style = getLLVMStyle();
14701 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14702 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14703 Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
14704
14705 verifyFormat("#define a 3\n"
14706 "#define bbbb 4\n"
14707 "#define ccc (5)",
14708 Style);
14709
14710 verifyFormat("#define f(x) (x * x)\n"
14711 "#define fff(x, y, z) (x * y + z)\n"
14712 "#define ffff(x, y) (x - y)",
14713 Style);
14714
14715 verifyFormat("#define foo(x, y) (x + y)\n"
14716 "#define bar (5, 6)(2 + 2)",
14717 Style);
14718
14719 verifyFormat("#define a 3\n"
14720 "#define bbbb 4\n"
14721 "#define ccc (5)\n"
14722 "#define f(x) (x * x)\n"
14723 "#define fff(x, y, z) (x * y + z)\n"
14724 "#define ffff(x, y) (x - y)",
14725 Style);
14726
14727 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14728 verifyFormat("#define a 3\n"
14729 "#define bbbb 4\n"
14730 "#define ccc (5)",
14731 Style);
14732
14733 verifyFormat("#define f(x) (x * x)\n"
14734 "#define fff(x, y, z) (x * y + z)\n"
14735 "#define ffff(x, y) (x - y)",
14736 Style);
14737
14738 verifyFormat("#define foo(x, y) (x + y)\n"
14739 "#define bar (5, 6)(2 + 2)",
14740 Style);
14741
14742 verifyFormat("#define a 3\n"
14743 "#define bbbb 4\n"
14744 "#define ccc (5)\n"
14745 "#define f(x) (x * x)\n"
14746 "#define fff(x, y, z) (x * y + z)\n"
14747 "#define ffff(x, y) (x - y)",
14748 Style);
14749
14750 verifyFormat("#define a 5\n"
14751 "#define foo(x, y) (x + y)\n"
14752 "#define CCC (6)\n"
14753 "auto lambda = []() {\n"
14754 " auto ii = 0;\n"
14755 " float j = 0;\n"
14756 " return 0;\n"
14757 "};\n"
14758 "int i = 0;\n"
14759 "float i2 = 0;\n"
14760 "auto v = type{\n"
14761 " i = 1, //\n"
14762 " (i = 2), //\n"
14763 " i = 3 //\n"
14764 "};",
14765 Style);
14766
14767 Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
14768 Style.ColumnLimit = 20;
14769
14770 verifyFormat("#define a \\\n"
14771 " \"aabbbbbbbbbbbb\"\n"
14772 "#define D \\\n"
14773 " \"aabbbbbbbbbbbb\" \\\n"
14774 " \"ccddeeeeeeeee\"\n"
14775 "#define B \\\n"
14776 " \"QQQQQQQQQQQQQ\" \\\n"
14777 " \"FFFFFFFFFFFFF\" \\\n"
14778 " \"LLLLLLLL\"\n",
14779 Style);
14780
14781 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14782 verifyFormat("#define a \\\n"
14783 " \"aabbbbbbbbbbbb\"\n"
14784 "#define D \\\n"
14785 " \"aabbbbbbbbbbbb\" \\\n"
14786 " \"ccddeeeeeeeee\"\n"
14787 "#define B \\\n"
14788 " \"QQQQQQQQQQQQQ\" \\\n"
14789 " \"FFFFFFFFFFFFF\" \\\n"
14790 " \"LLLLLLLL\"\n",
14791 Style);
14792
14793 // Test across comments
14794 Style.MaxEmptyLinesToKeep = 10;
14795 Style.ReflowComments = false;
14796 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
14797 EXPECT_EQ("#define a 3\n"
14798 "// line comment\n"
14799 "#define bbbb 4\n"
14800 "#define ccc (5)",
14801 format("#define a 3\n"
14802 "// line comment\n"
14803 "#define bbbb 4\n"
14804 "#define ccc (5)",
14805 Style));
14806
14807 EXPECT_EQ("#define a 3\n"
14808 "/* block comment */\n"
14809 "#define bbbb 4\n"
14810 "#define ccc (5)",
14811 format("#define a 3\n"
14812 "/* block comment */\n"
14813 "#define bbbb 4\n"
14814 "#define ccc (5)",
14815 Style));
14816
14817 EXPECT_EQ("#define a 3\n"
14818 "/* multi-line *\n"
14819 " * block comment */\n"
14820 "#define bbbb 4\n"
14821 "#define ccc (5)",
14822 format("#define a 3\n"
14823 "/* multi-line *\n"
14824 " * block comment */\n"
14825 "#define bbbb 4\n"
14826 "#define ccc (5)",
14827 Style));
14828
14829 EXPECT_EQ("#define a 3\n"
14830 "// multi-line line comment\n"
14831 "//\n"
14832 "#define bbbb 4\n"
14833 "#define ccc (5)",
14834 format("#define a 3\n"
14835 "// multi-line line comment\n"
14836 "//\n"
14837 "#define bbbb 4\n"
14838 "#define ccc (5)",
14839 Style));
14840
14841 EXPECT_EQ("#define a 3\n"
14842 "// empty lines still break.\n"
14843 "\n"
14844 "#define bbbb 4\n"
14845 "#define ccc (5)",
14846 format("#define a 3\n"
14847 "// empty lines still break.\n"
14848 "\n"
14849 "#define bbbb 4\n"
14850 "#define ccc (5)",
14851 Style));
14852
14853 // Test across empty lines
14854 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
14855 EXPECT_EQ("#define a 3\n"
14856 "\n"
14857 "#define bbbb 4\n"
14858 "#define ccc (5)",
14859 format("#define a 3\n"
14860 "\n"
14861 "#define bbbb 4\n"
14862 "#define ccc (5)",
14863 Style));
14864
14865 EXPECT_EQ("#define a 3\n"
14866 "\n"
14867 "\n"
14868 "\n"
14869 "#define bbbb 4\n"
14870 "#define ccc (5)",
14871 format("#define a 3\n"
14872 "\n"
14873 "\n"
14874 "\n"
14875 "#define bbbb 4\n"
14876 "#define ccc (5)",
14877 Style));
14878
14879 EXPECT_EQ("#define a 3\n"
14880 "// comments should break alignment\n"
14881 "//\n"
14882 "#define bbbb 4\n"
14883 "#define ccc (5)",
14884 format("#define a 3\n"
14885 "// comments should break alignment\n"
14886 "//\n"
14887 "#define bbbb 4\n"
14888 "#define ccc (5)",
14889 Style));
14890
14891 // Test across empty lines and comments
14892 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
14893 verifyFormat("#define a 3\n"
14894 "\n"
14895 "// line comment\n"
14896 "#define bbbb 4\n"
14897 "#define ccc (5)",
14898 Style);
14899
14900 EXPECT_EQ("#define a 3\n"
14901 "\n"
14902 "\n"
14903 "/* multi-line *\n"
14904 " * block comment */\n"
14905 "\n"
14906 "\n"
14907 "#define bbbb 4\n"
14908 "#define ccc (5)",
14909 format("#define a 3\n"
14910 "\n"
14911 "\n"
14912 "/* multi-line *\n"
14913 " * block comment */\n"
14914 "\n"
14915 "\n"
14916 "#define bbbb 4\n"
14917 "#define ccc (5)",
14918 Style));
14919
14920 EXPECT_EQ("#define a 3\n"
14921 "\n"
14922 "\n"
14923 "/* multi-line *\n"
14924 " * block comment */\n"
14925 "\n"
14926 "\n"
14927 "#define bbbb 4\n"
14928 "#define ccc (5)",
14929 format("#define a 3\n"
14930 "\n"
14931 "\n"
14932 "/* multi-line *\n"
14933 " * block comment */\n"
14934 "\n"
14935 "\n"
14936 "#define bbbb 4\n"
14937 "#define ccc (5)",
14938 Style));
14939 }
14940
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossEmptyLines)14941 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
14942 FormatStyle Alignment = getLLVMStyle();
14943 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14944 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
14945
14946 Alignment.MaxEmptyLinesToKeep = 10;
14947 /* Test alignment across empty lines */
14948 EXPECT_EQ("int a = 5;\n"
14949 "\n"
14950 "int oneTwoThree = 123;",
14951 format("int a = 5;\n"
14952 "\n"
14953 "int oneTwoThree= 123;",
14954 Alignment));
14955 EXPECT_EQ("int a = 5;\n"
14956 "int one = 1;\n"
14957 "\n"
14958 "int oneTwoThree = 123;",
14959 format("int a = 5;\n"
14960 "int one = 1;\n"
14961 "\n"
14962 "int oneTwoThree = 123;",
14963 Alignment));
14964 EXPECT_EQ("int a = 5;\n"
14965 "int one = 1;\n"
14966 "\n"
14967 "int oneTwoThree = 123;\n"
14968 "int oneTwo = 12;",
14969 format("int a = 5;\n"
14970 "int one = 1;\n"
14971 "\n"
14972 "int oneTwoThree = 123;\n"
14973 "int oneTwo = 12;",
14974 Alignment));
14975
14976 /* Test across comments */
14977 EXPECT_EQ("int a = 5;\n"
14978 "/* block comment */\n"
14979 "int oneTwoThree = 123;",
14980 format("int a = 5;\n"
14981 "/* block comment */\n"
14982 "int oneTwoThree=123;",
14983 Alignment));
14984
14985 EXPECT_EQ("int a = 5;\n"
14986 "// line comment\n"
14987 "int oneTwoThree = 123;",
14988 format("int a = 5;\n"
14989 "// line comment\n"
14990 "int oneTwoThree=123;",
14991 Alignment));
14992
14993 /* Test across comments and newlines */
14994 EXPECT_EQ("int a = 5;\n"
14995 "\n"
14996 "/* block comment */\n"
14997 "int oneTwoThree = 123;",
14998 format("int a = 5;\n"
14999 "\n"
15000 "/* block comment */\n"
15001 "int oneTwoThree=123;",
15002 Alignment));
15003
15004 EXPECT_EQ("int a = 5;\n"
15005 "\n"
15006 "// line comment\n"
15007 "int oneTwoThree = 123;",
15008 format("int a = 5;\n"
15009 "\n"
15010 "// line comment\n"
15011 "int oneTwoThree=123;",
15012 Alignment));
15013 }
15014
TEST_F(FormatTest,AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments)15015 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15016 FormatStyle Alignment = getLLVMStyle();
15017 Alignment.AlignConsecutiveDeclarations =
15018 FormatStyle::ACS_AcrossEmptyLinesAndComments;
15019 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15020
15021 Alignment.MaxEmptyLinesToKeep = 10;
15022 /* Test alignment across empty lines */
15023 EXPECT_EQ("int a = 5;\n"
15024 "\n"
15025 "float const oneTwoThree = 123;",
15026 format("int a = 5;\n"
15027 "\n"
15028 "float const oneTwoThree = 123;",
15029 Alignment));
15030 EXPECT_EQ("int a = 5;\n"
15031 "float const one = 1;\n"
15032 "\n"
15033 "int oneTwoThree = 123;",
15034 format("int a = 5;\n"
15035 "float const one = 1;\n"
15036 "\n"
15037 "int oneTwoThree = 123;",
15038 Alignment));
15039
15040 /* Test across comments */
15041 EXPECT_EQ("float const a = 5;\n"
15042 "/* block comment */\n"
15043 "int oneTwoThree = 123;",
15044 format("float const a = 5;\n"
15045 "/* block comment */\n"
15046 "int oneTwoThree=123;",
15047 Alignment));
15048
15049 EXPECT_EQ("float const a = 5;\n"
15050 "// line comment\n"
15051 "int oneTwoThree = 123;",
15052 format("float const a = 5;\n"
15053 "// line comment\n"
15054 "int oneTwoThree=123;",
15055 Alignment));
15056
15057 /* Test across comments and newlines */
15058 EXPECT_EQ("float const a = 5;\n"
15059 "\n"
15060 "/* block comment */\n"
15061 "int oneTwoThree = 123;",
15062 format("float const a = 5;\n"
15063 "\n"
15064 "/* block comment */\n"
15065 "int oneTwoThree=123;",
15066 Alignment));
15067
15068 EXPECT_EQ("float const a = 5;\n"
15069 "\n"
15070 "// line comment\n"
15071 "int oneTwoThree = 123;",
15072 format("float const a = 5;\n"
15073 "\n"
15074 "// line comment\n"
15075 "int oneTwoThree=123;",
15076 Alignment));
15077 }
15078
TEST_F(FormatTest,AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments)15079 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15080 FormatStyle Alignment = getLLVMStyle();
15081 Alignment.AlignConsecutiveBitFields =
15082 FormatStyle::ACS_AcrossEmptyLinesAndComments;
15083
15084 Alignment.MaxEmptyLinesToKeep = 10;
15085 /* Test alignment across empty lines */
15086 EXPECT_EQ("int a : 5;\n"
15087 "\n"
15088 "int longbitfield : 6;",
15089 format("int a : 5;\n"
15090 "\n"
15091 "int longbitfield : 6;",
15092 Alignment));
15093 EXPECT_EQ("int a : 5;\n"
15094 "int one : 1;\n"
15095 "\n"
15096 "int longbitfield : 6;",
15097 format("int a : 5;\n"
15098 "int one : 1;\n"
15099 "\n"
15100 "int longbitfield : 6;",
15101 Alignment));
15102
15103 /* Test across comments */
15104 EXPECT_EQ("int a : 5;\n"
15105 "/* block comment */\n"
15106 "int longbitfield : 6;",
15107 format("int a : 5;\n"
15108 "/* block comment */\n"
15109 "int longbitfield : 6;",
15110 Alignment));
15111 EXPECT_EQ("int a : 5;\n"
15112 "int one : 1;\n"
15113 "// line comment\n"
15114 "int longbitfield : 6;",
15115 format("int a : 5;\n"
15116 "int one : 1;\n"
15117 "// line comment\n"
15118 "int longbitfield : 6;",
15119 Alignment));
15120
15121 /* Test across comments and newlines */
15122 EXPECT_EQ("int a : 5;\n"
15123 "/* block comment */\n"
15124 "\n"
15125 "int longbitfield : 6;",
15126 format("int a : 5;\n"
15127 "/* block comment */\n"
15128 "\n"
15129 "int longbitfield : 6;",
15130 Alignment));
15131 EXPECT_EQ("int a : 5;\n"
15132 "int one : 1;\n"
15133 "\n"
15134 "// line comment\n"
15135 "\n"
15136 "int longbitfield : 6;",
15137 format("int a : 5;\n"
15138 "int one : 1;\n"
15139 "\n"
15140 "// line comment \n"
15141 "\n"
15142 "int longbitfield : 6;",
15143 Alignment));
15144 }
15145
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossComments)15146 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15147 FormatStyle Alignment = getLLVMStyle();
15148 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15149 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15150
15151 Alignment.MaxEmptyLinesToKeep = 10;
15152 /* Test alignment across empty lines */
15153 EXPECT_EQ("int a = 5;\n"
15154 "\n"
15155 "int oneTwoThree = 123;",
15156 format("int a = 5;\n"
15157 "\n"
15158 "int oneTwoThree= 123;",
15159 Alignment));
15160 EXPECT_EQ("int a = 5;\n"
15161 "int one = 1;\n"
15162 "\n"
15163 "int oneTwoThree = 123;",
15164 format("int a = 5;\n"
15165 "int one = 1;\n"
15166 "\n"
15167 "int oneTwoThree = 123;",
15168 Alignment));
15169
15170 /* Test across comments */
15171 EXPECT_EQ("int a = 5;\n"
15172 "/* block comment */\n"
15173 "int oneTwoThree = 123;",
15174 format("int a = 5;\n"
15175 "/* block comment */\n"
15176 "int oneTwoThree=123;",
15177 Alignment));
15178
15179 EXPECT_EQ("int a = 5;\n"
15180 "// line comment\n"
15181 "int oneTwoThree = 123;",
15182 format("int a = 5;\n"
15183 "// line comment\n"
15184 "int oneTwoThree=123;",
15185 Alignment));
15186
15187 EXPECT_EQ("int a = 5;\n"
15188 "/*\n"
15189 " * multi-line block comment\n"
15190 " */\n"
15191 "int oneTwoThree = 123;",
15192 format("int a = 5;\n"
15193 "/*\n"
15194 " * multi-line block comment\n"
15195 " */\n"
15196 "int oneTwoThree=123;",
15197 Alignment));
15198
15199 EXPECT_EQ("int a = 5;\n"
15200 "//\n"
15201 "// multi-line line comment\n"
15202 "//\n"
15203 "int oneTwoThree = 123;",
15204 format("int a = 5;\n"
15205 "//\n"
15206 "// multi-line line comment\n"
15207 "//\n"
15208 "int oneTwoThree=123;",
15209 Alignment));
15210
15211 /* Test across comments and newlines */
15212 EXPECT_EQ("int a = 5;\n"
15213 "\n"
15214 "/* block comment */\n"
15215 "int oneTwoThree = 123;",
15216 format("int a = 5;\n"
15217 "\n"
15218 "/* block comment */\n"
15219 "int oneTwoThree=123;",
15220 Alignment));
15221
15222 EXPECT_EQ("int a = 5;\n"
15223 "\n"
15224 "// line comment\n"
15225 "int oneTwoThree = 123;",
15226 format("int a = 5;\n"
15227 "\n"
15228 "// line comment\n"
15229 "int oneTwoThree=123;",
15230 Alignment));
15231 }
15232
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments)15233 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15234 FormatStyle Alignment = getLLVMStyle();
15235 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15236 Alignment.AlignConsecutiveAssignments =
15237 FormatStyle::ACS_AcrossEmptyLinesAndComments;
15238 verifyFormat("int a = 5;\n"
15239 "int oneTwoThree = 123;",
15240 Alignment);
15241 verifyFormat("int a = method();\n"
15242 "int oneTwoThree = 133;",
15243 Alignment);
15244 verifyFormat("a &= 5;\n"
15245 "bcd *= 5;\n"
15246 "ghtyf += 5;\n"
15247 "dvfvdb -= 5;\n"
15248 "a /= 5;\n"
15249 "vdsvsv %= 5;\n"
15250 "sfdbddfbdfbb ^= 5;\n"
15251 "dvsdsv |= 5;\n"
15252 "int dsvvdvsdvvv = 123;",
15253 Alignment);
15254 verifyFormat("int i = 1, j = 10;\n"
15255 "something = 2000;",
15256 Alignment);
15257 verifyFormat("something = 2000;\n"
15258 "int i = 1, j = 10;\n",
15259 Alignment);
15260 verifyFormat("something = 2000;\n"
15261 "another = 911;\n"
15262 "int i = 1, j = 10;\n"
15263 "oneMore = 1;\n"
15264 "i = 2;",
15265 Alignment);
15266 verifyFormat("int a = 5;\n"
15267 "int one = 1;\n"
15268 "method();\n"
15269 "int oneTwoThree = 123;\n"
15270 "int oneTwo = 12;",
15271 Alignment);
15272 verifyFormat("int oneTwoThree = 123;\n"
15273 "int oneTwo = 12;\n"
15274 "method();\n",
15275 Alignment);
15276 verifyFormat("int oneTwoThree = 123; // comment\n"
15277 "int oneTwo = 12; // comment",
15278 Alignment);
15279
15280 // Bug 25167
15281 /* Uncomment when fixed
15282 verifyFormat("#if A\n"
15283 "#else\n"
15284 "int aaaaaaaa = 12;\n"
15285 "#endif\n"
15286 "#if B\n"
15287 "#else\n"
15288 "int a = 12;\n"
15289 "#endif\n",
15290 Alignment);
15291 verifyFormat("enum foo {\n"
15292 "#if A\n"
15293 "#else\n"
15294 " aaaaaaaa = 12;\n"
15295 "#endif\n"
15296 "#if B\n"
15297 "#else\n"
15298 " a = 12;\n"
15299 "#endif\n"
15300 "};\n",
15301 Alignment);
15302 */
15303
15304 Alignment.MaxEmptyLinesToKeep = 10;
15305 /* Test alignment across empty lines */
15306 EXPECT_EQ("int a = 5;\n"
15307 "\n"
15308 "int oneTwoThree = 123;",
15309 format("int a = 5;\n"
15310 "\n"
15311 "int oneTwoThree= 123;",
15312 Alignment));
15313 EXPECT_EQ("int a = 5;\n"
15314 "int one = 1;\n"
15315 "\n"
15316 "int oneTwoThree = 123;",
15317 format("int a = 5;\n"
15318 "int one = 1;\n"
15319 "\n"
15320 "int oneTwoThree = 123;",
15321 Alignment));
15322 EXPECT_EQ("int a = 5;\n"
15323 "int one = 1;\n"
15324 "\n"
15325 "int oneTwoThree = 123;\n"
15326 "int oneTwo = 12;",
15327 format("int a = 5;\n"
15328 "int one = 1;\n"
15329 "\n"
15330 "int oneTwoThree = 123;\n"
15331 "int oneTwo = 12;",
15332 Alignment));
15333
15334 /* Test across comments */
15335 EXPECT_EQ("int a = 5;\n"
15336 "/* block comment */\n"
15337 "int oneTwoThree = 123;",
15338 format("int a = 5;\n"
15339 "/* block comment */\n"
15340 "int oneTwoThree=123;",
15341 Alignment));
15342
15343 EXPECT_EQ("int a = 5;\n"
15344 "// line comment\n"
15345 "int oneTwoThree = 123;",
15346 format("int a = 5;\n"
15347 "// line comment\n"
15348 "int oneTwoThree=123;",
15349 Alignment));
15350
15351 /* Test across comments and newlines */
15352 EXPECT_EQ("int a = 5;\n"
15353 "\n"
15354 "/* block comment */\n"
15355 "int oneTwoThree = 123;",
15356 format("int a = 5;\n"
15357 "\n"
15358 "/* block comment */\n"
15359 "int oneTwoThree=123;",
15360 Alignment));
15361
15362 EXPECT_EQ("int a = 5;\n"
15363 "\n"
15364 "// line comment\n"
15365 "int oneTwoThree = 123;",
15366 format("int a = 5;\n"
15367 "\n"
15368 "// line comment\n"
15369 "int oneTwoThree=123;",
15370 Alignment));
15371
15372 EXPECT_EQ("int a = 5;\n"
15373 "//\n"
15374 "// multi-line line comment\n"
15375 "//\n"
15376 "int oneTwoThree = 123;",
15377 format("int a = 5;\n"
15378 "//\n"
15379 "// multi-line line comment\n"
15380 "//\n"
15381 "int oneTwoThree=123;",
15382 Alignment));
15383
15384 EXPECT_EQ("int a = 5;\n"
15385 "/*\n"
15386 " * multi-line block comment\n"
15387 " */\n"
15388 "int oneTwoThree = 123;",
15389 format("int a = 5;\n"
15390 "/*\n"
15391 " * multi-line block comment\n"
15392 " */\n"
15393 "int oneTwoThree=123;",
15394 Alignment));
15395
15396 EXPECT_EQ("int a = 5;\n"
15397 "\n"
15398 "/* block comment */\n"
15399 "\n"
15400 "\n"
15401 "\n"
15402 "int oneTwoThree = 123;",
15403 format("int a = 5;\n"
15404 "\n"
15405 "/* block comment */\n"
15406 "\n"
15407 "\n"
15408 "\n"
15409 "int oneTwoThree=123;",
15410 Alignment));
15411
15412 EXPECT_EQ("int a = 5;\n"
15413 "\n"
15414 "// line comment\n"
15415 "\n"
15416 "\n"
15417 "\n"
15418 "int oneTwoThree = 123;",
15419 format("int a = 5;\n"
15420 "\n"
15421 "// line comment\n"
15422 "\n"
15423 "\n"
15424 "\n"
15425 "int oneTwoThree=123;",
15426 Alignment));
15427
15428 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15429 verifyFormat("#define A \\\n"
15430 " int aaaa = 12; \\\n"
15431 " int b = 23; \\\n"
15432 " int ccc = 234; \\\n"
15433 " int dddddddddd = 2345;",
15434 Alignment);
15435 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15436 verifyFormat("#define A \\\n"
15437 " int aaaa = 12; \\\n"
15438 " int b = 23; \\\n"
15439 " int ccc = 234; \\\n"
15440 " int dddddddddd = 2345;",
15441 Alignment);
15442 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15443 verifyFormat("#define A "
15444 " \\\n"
15445 " int aaaa = 12; "
15446 " \\\n"
15447 " int b = 23; "
15448 " \\\n"
15449 " int ccc = 234; "
15450 " \\\n"
15451 " int dddddddddd = 2345;",
15452 Alignment);
15453 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15454 "k = 4, int l = 5,\n"
15455 " int m = 6) {\n"
15456 " int j = 10;\n"
15457 " otherThing = 1;\n"
15458 "}",
15459 Alignment);
15460 verifyFormat("void SomeFunction(int parameter = 0) {\n"
15461 " int i = 1;\n"
15462 " int j = 2;\n"
15463 " int big = 10000;\n"
15464 "}",
15465 Alignment);
15466 verifyFormat("class C {\n"
15467 "public:\n"
15468 " int i = 1;\n"
15469 " virtual void f() = 0;\n"
15470 "};",
15471 Alignment);
15472 verifyFormat("int i = 1;\n"
15473 "if (SomeType t = getSomething()) {\n"
15474 "}\n"
15475 "int j = 2;\n"
15476 "int big = 10000;",
15477 Alignment);
15478 verifyFormat("int j = 7;\n"
15479 "for (int k = 0; k < N; ++k) {\n"
15480 "}\n"
15481 "int j = 2;\n"
15482 "int big = 10000;\n"
15483 "}",
15484 Alignment);
15485 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15486 verifyFormat("int i = 1;\n"
15487 "LooooooooooongType loooooooooooooooooooooongVariable\n"
15488 " = someLooooooooooooooooongFunction();\n"
15489 "int j = 2;",
15490 Alignment);
15491 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15492 verifyFormat("int i = 1;\n"
15493 "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15494 " someLooooooooooooooooongFunction();\n"
15495 "int j = 2;",
15496 Alignment);
15497
15498 verifyFormat("auto lambda = []() {\n"
15499 " auto i = 0;\n"
15500 " return 0;\n"
15501 "};\n"
15502 "int i = 0;\n"
15503 "auto v = type{\n"
15504 " i = 1, //\n"
15505 " (i = 2), //\n"
15506 " i = 3 //\n"
15507 "};",
15508 Alignment);
15509
15510 verifyFormat(
15511 "int i = 1;\n"
15512 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15513 " loooooooooooooooooooooongParameterB);\n"
15514 "int j = 2;",
15515 Alignment);
15516
15517 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15518 " typename B = very_long_type_name_1,\n"
15519 " typename T_2 = very_long_type_name_2>\n"
15520 "auto foo() {}\n",
15521 Alignment);
15522 verifyFormat("int a, b = 1;\n"
15523 "int c = 2;\n"
15524 "int dd = 3;\n",
15525 Alignment);
15526 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
15527 "float b[1][] = {{3.f}};\n",
15528 Alignment);
15529 verifyFormat("for (int i = 0; i < 1; i++)\n"
15530 " int x = 1;\n",
15531 Alignment);
15532 verifyFormat("for (i = 0; i < 1; i++)\n"
15533 " x = 1;\n"
15534 "y = 1;\n",
15535 Alignment);
15536
15537 Alignment.ReflowComments = true;
15538 Alignment.ColumnLimit = 50;
15539 EXPECT_EQ("int x = 0;\n"
15540 "int yy = 1; /// specificlennospace\n"
15541 "int zzz = 2;\n",
15542 format("int x = 0;\n"
15543 "int yy = 1; ///specificlennospace\n"
15544 "int zzz = 2;\n",
15545 Alignment));
15546 }
15547
TEST_F(FormatTest,AlignConsecutiveAssignments)15548 TEST_F(FormatTest, AlignConsecutiveAssignments) {
15549 FormatStyle Alignment = getLLVMStyle();
15550 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15551 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15552 verifyFormat("int a = 5;\n"
15553 "int oneTwoThree = 123;",
15554 Alignment);
15555 verifyFormat("int a = 5;\n"
15556 "int oneTwoThree = 123;",
15557 Alignment);
15558
15559 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15560 verifyFormat("int a = 5;\n"
15561 "int oneTwoThree = 123;",
15562 Alignment);
15563 verifyFormat("int a = method();\n"
15564 "int oneTwoThree = 133;",
15565 Alignment);
15566 verifyFormat("a &= 5;\n"
15567 "bcd *= 5;\n"
15568 "ghtyf += 5;\n"
15569 "dvfvdb -= 5;\n"
15570 "a /= 5;\n"
15571 "vdsvsv %= 5;\n"
15572 "sfdbddfbdfbb ^= 5;\n"
15573 "dvsdsv |= 5;\n"
15574 "int dsvvdvsdvvv = 123;",
15575 Alignment);
15576 verifyFormat("int i = 1, j = 10;\n"
15577 "something = 2000;",
15578 Alignment);
15579 verifyFormat("something = 2000;\n"
15580 "int i = 1, j = 10;\n",
15581 Alignment);
15582 verifyFormat("something = 2000;\n"
15583 "another = 911;\n"
15584 "int i = 1, j = 10;\n"
15585 "oneMore = 1;\n"
15586 "i = 2;",
15587 Alignment);
15588 verifyFormat("int a = 5;\n"
15589 "int one = 1;\n"
15590 "method();\n"
15591 "int oneTwoThree = 123;\n"
15592 "int oneTwo = 12;",
15593 Alignment);
15594 verifyFormat("int oneTwoThree = 123;\n"
15595 "int oneTwo = 12;\n"
15596 "method();\n",
15597 Alignment);
15598 verifyFormat("int oneTwoThree = 123; // comment\n"
15599 "int oneTwo = 12; // comment",
15600 Alignment);
15601
15602 // Bug 25167
15603 /* Uncomment when fixed
15604 verifyFormat("#if A\n"
15605 "#else\n"
15606 "int aaaaaaaa = 12;\n"
15607 "#endif\n"
15608 "#if B\n"
15609 "#else\n"
15610 "int a = 12;\n"
15611 "#endif\n",
15612 Alignment);
15613 verifyFormat("enum foo {\n"
15614 "#if A\n"
15615 "#else\n"
15616 " aaaaaaaa = 12;\n"
15617 "#endif\n"
15618 "#if B\n"
15619 "#else\n"
15620 " a = 12;\n"
15621 "#endif\n"
15622 "};\n",
15623 Alignment);
15624 */
15625
15626 EXPECT_EQ("int a = 5;\n"
15627 "\n"
15628 "int oneTwoThree = 123;",
15629 format("int a = 5;\n"
15630 "\n"
15631 "int oneTwoThree= 123;",
15632 Alignment));
15633 EXPECT_EQ("int a = 5;\n"
15634 "int one = 1;\n"
15635 "\n"
15636 "int oneTwoThree = 123;",
15637 format("int a = 5;\n"
15638 "int one = 1;\n"
15639 "\n"
15640 "int oneTwoThree = 123;",
15641 Alignment));
15642 EXPECT_EQ("int a = 5;\n"
15643 "int one = 1;\n"
15644 "\n"
15645 "int oneTwoThree = 123;\n"
15646 "int oneTwo = 12;",
15647 format("int a = 5;\n"
15648 "int one = 1;\n"
15649 "\n"
15650 "int oneTwoThree = 123;\n"
15651 "int oneTwo = 12;",
15652 Alignment));
15653 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15654 verifyFormat("#define A \\\n"
15655 " int aaaa = 12; \\\n"
15656 " int b = 23; \\\n"
15657 " int ccc = 234; \\\n"
15658 " int dddddddddd = 2345;",
15659 Alignment);
15660 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15661 verifyFormat("#define A \\\n"
15662 " int aaaa = 12; \\\n"
15663 " int b = 23; \\\n"
15664 " int ccc = 234; \\\n"
15665 " int dddddddddd = 2345;",
15666 Alignment);
15667 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15668 verifyFormat("#define A "
15669 " \\\n"
15670 " int aaaa = 12; "
15671 " \\\n"
15672 " int b = 23; "
15673 " \\\n"
15674 " int ccc = 234; "
15675 " \\\n"
15676 " int dddddddddd = 2345;",
15677 Alignment);
15678 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15679 "k = 4, int l = 5,\n"
15680 " int m = 6) {\n"
15681 " int j = 10;\n"
15682 " otherThing = 1;\n"
15683 "}",
15684 Alignment);
15685 verifyFormat("void SomeFunction(int parameter = 0) {\n"
15686 " int i = 1;\n"
15687 " int j = 2;\n"
15688 " int big = 10000;\n"
15689 "}",
15690 Alignment);
15691 verifyFormat("class C {\n"
15692 "public:\n"
15693 " int i = 1;\n"
15694 " virtual void f() = 0;\n"
15695 "};",
15696 Alignment);
15697 verifyFormat("int i = 1;\n"
15698 "if (SomeType t = getSomething()) {\n"
15699 "}\n"
15700 "int j = 2;\n"
15701 "int big = 10000;",
15702 Alignment);
15703 verifyFormat("int j = 7;\n"
15704 "for (int k = 0; k < N; ++k) {\n"
15705 "}\n"
15706 "int j = 2;\n"
15707 "int big = 10000;\n"
15708 "}",
15709 Alignment);
15710 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15711 verifyFormat("int i = 1;\n"
15712 "LooooooooooongType loooooooooooooooooooooongVariable\n"
15713 " = someLooooooooooooooooongFunction();\n"
15714 "int j = 2;",
15715 Alignment);
15716 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15717 verifyFormat("int i = 1;\n"
15718 "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15719 " someLooooooooooooooooongFunction();\n"
15720 "int j = 2;",
15721 Alignment);
15722
15723 verifyFormat("auto lambda = []() {\n"
15724 " auto i = 0;\n"
15725 " return 0;\n"
15726 "};\n"
15727 "int i = 0;\n"
15728 "auto v = type{\n"
15729 " i = 1, //\n"
15730 " (i = 2), //\n"
15731 " i = 3 //\n"
15732 "};",
15733 Alignment);
15734
15735 verifyFormat(
15736 "int i = 1;\n"
15737 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15738 " loooooooooooooooooooooongParameterB);\n"
15739 "int j = 2;",
15740 Alignment);
15741
15742 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15743 " typename B = very_long_type_name_1,\n"
15744 " typename T_2 = very_long_type_name_2>\n"
15745 "auto foo() {}\n",
15746 Alignment);
15747 verifyFormat("int a, b = 1;\n"
15748 "int c = 2;\n"
15749 "int dd = 3;\n",
15750 Alignment);
15751 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
15752 "float b[1][] = {{3.f}};\n",
15753 Alignment);
15754 verifyFormat("for (int i = 0; i < 1; i++)\n"
15755 " int x = 1;\n",
15756 Alignment);
15757 verifyFormat("for (i = 0; i < 1; i++)\n"
15758 " x = 1;\n"
15759 "y = 1;\n",
15760 Alignment);
15761
15762 Alignment.ReflowComments = true;
15763 Alignment.ColumnLimit = 50;
15764 EXPECT_EQ("int x = 0;\n"
15765 "int yy = 1; /// specificlennospace\n"
15766 "int zzz = 2;\n",
15767 format("int x = 0;\n"
15768 "int yy = 1; ///specificlennospace\n"
15769 "int zzz = 2;\n",
15770 Alignment));
15771 }
15772
TEST_F(FormatTest,AlignConsecutiveBitFields)15773 TEST_F(FormatTest, AlignConsecutiveBitFields) {
15774 FormatStyle Alignment = getLLVMStyle();
15775 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
15776 verifyFormat("int const a : 5;\n"
15777 "int oneTwoThree : 23;",
15778 Alignment);
15779
15780 // Initializers are allowed starting with c++2a
15781 verifyFormat("int const a : 5 = 1;\n"
15782 "int oneTwoThree : 23 = 0;",
15783 Alignment);
15784
15785 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15786 verifyFormat("int const a : 5;\n"
15787 "int oneTwoThree : 23;",
15788 Alignment);
15789
15790 verifyFormat("int const a : 5; // comment\n"
15791 "int oneTwoThree : 23; // comment",
15792 Alignment);
15793
15794 verifyFormat("int const a : 5 = 1;\n"
15795 "int oneTwoThree : 23 = 0;",
15796 Alignment);
15797
15798 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15799 verifyFormat("int const a : 5 = 1;\n"
15800 "int oneTwoThree : 23 = 0;",
15801 Alignment);
15802 verifyFormat("int const a : 5 = {1};\n"
15803 "int oneTwoThree : 23 = 0;",
15804 Alignment);
15805
15806 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
15807 verifyFormat("int const a :5;\n"
15808 "int oneTwoThree:23;",
15809 Alignment);
15810
15811 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
15812 verifyFormat("int const a :5;\n"
15813 "int oneTwoThree :23;",
15814 Alignment);
15815
15816 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
15817 verifyFormat("int const a : 5;\n"
15818 "int oneTwoThree: 23;",
15819 Alignment);
15820
15821 // Known limitations: ':' is only recognized as a bitfield colon when
15822 // followed by a number.
15823 /*
15824 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
15825 "int a : 5;",
15826 Alignment);
15827 */
15828 }
15829
TEST_F(FormatTest,AlignConsecutiveDeclarations)15830 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
15831 FormatStyle Alignment = getLLVMStyle();
15832 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15833 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
15834 Alignment.PointerAlignment = FormatStyle::PAS_Right;
15835 verifyFormat("float const a = 5;\n"
15836 "int oneTwoThree = 123;",
15837 Alignment);
15838 verifyFormat("int a = 5;\n"
15839 "float const oneTwoThree = 123;",
15840 Alignment);
15841
15842 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15843 verifyFormat("float const a = 5;\n"
15844 "int oneTwoThree = 123;",
15845 Alignment);
15846 verifyFormat("int a = method();\n"
15847 "float const oneTwoThree = 133;",
15848 Alignment);
15849 verifyFormat("int i = 1, j = 10;\n"
15850 "something = 2000;",
15851 Alignment);
15852 verifyFormat("something = 2000;\n"
15853 "int i = 1, j = 10;\n",
15854 Alignment);
15855 verifyFormat("float something = 2000;\n"
15856 "double another = 911;\n"
15857 "int i = 1, j = 10;\n"
15858 "const int *oneMore = 1;\n"
15859 "unsigned i = 2;",
15860 Alignment);
15861 verifyFormat("float a = 5;\n"
15862 "int one = 1;\n"
15863 "method();\n"
15864 "const double oneTwoThree = 123;\n"
15865 "const unsigned int oneTwo = 12;",
15866 Alignment);
15867 verifyFormat("int oneTwoThree{0}; // comment\n"
15868 "unsigned oneTwo; // comment",
15869 Alignment);
15870 verifyFormat("unsigned int *a;\n"
15871 "int *b;\n"
15872 "unsigned int Const *c;\n"
15873 "unsigned int const *d;\n"
15874 "unsigned int Const &e;\n"
15875 "unsigned int const &f;",
15876 Alignment);
15877 verifyFormat("Const unsigned int *c;\n"
15878 "const unsigned int *d;\n"
15879 "Const unsigned int &e;\n"
15880 "const unsigned int &f;\n"
15881 "const unsigned g;\n"
15882 "Const unsigned h;",
15883 Alignment);
15884 EXPECT_EQ("float const a = 5;\n"
15885 "\n"
15886 "int oneTwoThree = 123;",
15887 format("float const a = 5;\n"
15888 "\n"
15889 "int oneTwoThree= 123;",
15890 Alignment));
15891 EXPECT_EQ("float a = 5;\n"
15892 "int one = 1;\n"
15893 "\n"
15894 "unsigned oneTwoThree = 123;",
15895 format("float a = 5;\n"
15896 "int one = 1;\n"
15897 "\n"
15898 "unsigned oneTwoThree = 123;",
15899 Alignment));
15900 EXPECT_EQ("float a = 5;\n"
15901 "int one = 1;\n"
15902 "\n"
15903 "unsigned oneTwoThree = 123;\n"
15904 "int oneTwo = 12;",
15905 format("float a = 5;\n"
15906 "int one = 1;\n"
15907 "\n"
15908 "unsigned oneTwoThree = 123;\n"
15909 "int oneTwo = 12;",
15910 Alignment));
15911 // Function prototype alignment
15912 verifyFormat("int a();\n"
15913 "double b();",
15914 Alignment);
15915 verifyFormat("int a(int x);\n"
15916 "double b();",
15917 Alignment);
15918 unsigned OldColumnLimit = Alignment.ColumnLimit;
15919 // We need to set ColumnLimit to zero, in order to stress nested alignments,
15920 // otherwise the function parameters will be re-flowed onto a single line.
15921 Alignment.ColumnLimit = 0;
15922 EXPECT_EQ("int a(int x,\n"
15923 " float y);\n"
15924 "double b(int x,\n"
15925 " double y);",
15926 format("int a(int x,\n"
15927 " float y);\n"
15928 "double b(int x,\n"
15929 " double y);",
15930 Alignment));
15931 // This ensures that function parameters of function declarations are
15932 // correctly indented when their owning functions are indented.
15933 // The failure case here is for 'double y' to not be indented enough.
15934 EXPECT_EQ("double a(int x);\n"
15935 "int b(int y,\n"
15936 " double z);",
15937 format("double a(int x);\n"
15938 "int b(int y,\n"
15939 " double z);",
15940 Alignment));
15941 // Set ColumnLimit low so that we induce wrapping immediately after
15942 // the function name and opening paren.
15943 Alignment.ColumnLimit = 13;
15944 verifyFormat("int function(\n"
15945 " int x,\n"
15946 " bool y);",
15947 Alignment);
15948 Alignment.ColumnLimit = OldColumnLimit;
15949 // Ensure function pointers don't screw up recursive alignment
15950 verifyFormat("int a(int x, void (*fp)(int y));\n"
15951 "double b();",
15952 Alignment);
15953 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15954 // Ensure recursive alignment is broken by function braces, so that the
15955 // "a = 1" does not align with subsequent assignments inside the function
15956 // body.
15957 verifyFormat("int func(int a = 1) {\n"
15958 " int b = 2;\n"
15959 " int cc = 3;\n"
15960 "}",
15961 Alignment);
15962 verifyFormat("float something = 2000;\n"
15963 "double another = 911;\n"
15964 "int i = 1, j = 10;\n"
15965 "const int *oneMore = 1;\n"
15966 "unsigned i = 2;",
15967 Alignment);
15968 verifyFormat("int oneTwoThree = {0}; // comment\n"
15969 "unsigned oneTwo = 0; // comment",
15970 Alignment);
15971 // Make sure that scope is correctly tracked, in the absence of braces
15972 verifyFormat("for (int i = 0; i < n; i++)\n"
15973 " j = i;\n"
15974 "double x = 1;\n",
15975 Alignment);
15976 verifyFormat("if (int i = 0)\n"
15977 " j = i;\n"
15978 "double x = 1;\n",
15979 Alignment);
15980 // Ensure operator[] and operator() are comprehended
15981 verifyFormat("struct test {\n"
15982 " long long int foo();\n"
15983 " int operator[](int a);\n"
15984 " double bar();\n"
15985 "};\n",
15986 Alignment);
15987 verifyFormat("struct test {\n"
15988 " long long int foo();\n"
15989 " int operator()(int a);\n"
15990 " double bar();\n"
15991 "};\n",
15992 Alignment);
15993
15994 // PAS_Right
15995 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
15996 " int const i = 1;\n"
15997 " int *j = 2;\n"
15998 " int big = 10000;\n"
15999 "\n"
16000 " unsigned oneTwoThree = 123;\n"
16001 " int oneTwo = 12;\n"
16002 " method();\n"
16003 " float k = 2;\n"
16004 " int ll = 10000;\n"
16005 "}",
16006 format("void SomeFunction(int parameter= 0) {\n"
16007 " int const i= 1;\n"
16008 " int *j=2;\n"
16009 " int big = 10000;\n"
16010 "\n"
16011 "unsigned oneTwoThree =123;\n"
16012 "int oneTwo = 12;\n"
16013 " method();\n"
16014 "float k= 2;\n"
16015 "int ll=10000;\n"
16016 "}",
16017 Alignment));
16018 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16019 " int const i = 1;\n"
16020 " int **j = 2, ***k;\n"
16021 " int &k = i;\n"
16022 " int &&l = i + j;\n"
16023 " int big = 10000;\n"
16024 "\n"
16025 " unsigned oneTwoThree = 123;\n"
16026 " int oneTwo = 12;\n"
16027 " method();\n"
16028 " float k = 2;\n"
16029 " int ll = 10000;\n"
16030 "}",
16031 format("void SomeFunction(int parameter= 0) {\n"
16032 " int const i= 1;\n"
16033 " int **j=2,***k;\n"
16034 "int &k=i;\n"
16035 "int &&l=i+j;\n"
16036 " int big = 10000;\n"
16037 "\n"
16038 "unsigned oneTwoThree =123;\n"
16039 "int oneTwo = 12;\n"
16040 " method();\n"
16041 "float k= 2;\n"
16042 "int ll=10000;\n"
16043 "}",
16044 Alignment));
16045 // variables are aligned at their name, pointers are at the right most
16046 // position
16047 verifyFormat("int *a;\n"
16048 "int **b;\n"
16049 "int ***c;\n"
16050 "int foobar;\n",
16051 Alignment);
16052
16053 // PAS_Left
16054 FormatStyle AlignmentLeft = Alignment;
16055 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16056 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16057 " int const i = 1;\n"
16058 " int* j = 2;\n"
16059 " int big = 10000;\n"
16060 "\n"
16061 " unsigned oneTwoThree = 123;\n"
16062 " int oneTwo = 12;\n"
16063 " method();\n"
16064 " float k = 2;\n"
16065 " int ll = 10000;\n"
16066 "}",
16067 format("void SomeFunction(int parameter= 0) {\n"
16068 " int const i= 1;\n"
16069 " int *j=2;\n"
16070 " int big = 10000;\n"
16071 "\n"
16072 "unsigned oneTwoThree =123;\n"
16073 "int oneTwo = 12;\n"
16074 " method();\n"
16075 "float k= 2;\n"
16076 "int ll=10000;\n"
16077 "}",
16078 AlignmentLeft));
16079 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16080 " int const i = 1;\n"
16081 " int** j = 2;\n"
16082 " int& k = i;\n"
16083 " int&& l = i + j;\n"
16084 " int big = 10000;\n"
16085 "\n"
16086 " unsigned oneTwoThree = 123;\n"
16087 " int oneTwo = 12;\n"
16088 " method();\n"
16089 " float k = 2;\n"
16090 " int ll = 10000;\n"
16091 "}",
16092 format("void SomeFunction(int parameter= 0) {\n"
16093 " int const i= 1;\n"
16094 " int **j=2;\n"
16095 "int &k=i;\n"
16096 "int &&l=i+j;\n"
16097 " int big = 10000;\n"
16098 "\n"
16099 "unsigned oneTwoThree =123;\n"
16100 "int oneTwo = 12;\n"
16101 " method();\n"
16102 "float k= 2;\n"
16103 "int ll=10000;\n"
16104 "}",
16105 AlignmentLeft));
16106 // variables are aligned at their name, pointers are at the left most position
16107 verifyFormat("int* a;\n"
16108 "int** b;\n"
16109 "int*** c;\n"
16110 "int foobar;\n",
16111 AlignmentLeft);
16112
16113 // PAS_Middle
16114 FormatStyle AlignmentMiddle = Alignment;
16115 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16116 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16117 " int const i = 1;\n"
16118 " int * j = 2;\n"
16119 " int big = 10000;\n"
16120 "\n"
16121 " unsigned oneTwoThree = 123;\n"
16122 " int oneTwo = 12;\n"
16123 " method();\n"
16124 " float k = 2;\n"
16125 " int ll = 10000;\n"
16126 "}",
16127 format("void SomeFunction(int parameter= 0) {\n"
16128 " int const i= 1;\n"
16129 " int *j=2;\n"
16130 " int big = 10000;\n"
16131 "\n"
16132 "unsigned oneTwoThree =123;\n"
16133 "int oneTwo = 12;\n"
16134 " method();\n"
16135 "float k= 2;\n"
16136 "int ll=10000;\n"
16137 "}",
16138 AlignmentMiddle));
16139 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16140 " int const i = 1;\n"
16141 " int ** j = 2, ***k;\n"
16142 " int & k = i;\n"
16143 " int && l = i + j;\n"
16144 " int big = 10000;\n"
16145 "\n"
16146 " unsigned oneTwoThree = 123;\n"
16147 " int oneTwo = 12;\n"
16148 " method();\n"
16149 " float k = 2;\n"
16150 " int ll = 10000;\n"
16151 "}",
16152 format("void SomeFunction(int parameter= 0) {\n"
16153 " int const i= 1;\n"
16154 " int **j=2,***k;\n"
16155 "int &k=i;\n"
16156 "int &&l=i+j;\n"
16157 " int big = 10000;\n"
16158 "\n"
16159 "unsigned oneTwoThree =123;\n"
16160 "int oneTwo = 12;\n"
16161 " method();\n"
16162 "float k= 2;\n"
16163 "int ll=10000;\n"
16164 "}",
16165 AlignmentMiddle));
16166 // variables are aligned at their name, pointers are in the middle
16167 verifyFormat("int * a;\n"
16168 "int * b;\n"
16169 "int *** c;\n"
16170 "int foobar;\n",
16171 AlignmentMiddle);
16172
16173 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16174 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16175 verifyFormat("#define A \\\n"
16176 " int aaaa = 12; \\\n"
16177 " float b = 23; \\\n"
16178 " const int ccc = 234; \\\n"
16179 " unsigned dddddddddd = 2345;",
16180 Alignment);
16181 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16182 verifyFormat("#define A \\\n"
16183 " int aaaa = 12; \\\n"
16184 " float b = 23; \\\n"
16185 " const int ccc = 234; \\\n"
16186 " unsigned dddddddddd = 2345;",
16187 Alignment);
16188 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16189 Alignment.ColumnLimit = 30;
16190 verifyFormat("#define A \\\n"
16191 " int aaaa = 12; \\\n"
16192 " float b = 23; \\\n"
16193 " const int ccc = 234; \\\n"
16194 " int dddddddddd = 2345;",
16195 Alignment);
16196 Alignment.ColumnLimit = 80;
16197 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16198 "k = 4, int l = 5,\n"
16199 " int m = 6) {\n"
16200 " const int j = 10;\n"
16201 " otherThing = 1;\n"
16202 "}",
16203 Alignment);
16204 verifyFormat("void SomeFunction(int parameter = 0) {\n"
16205 " int const i = 1;\n"
16206 " int *j = 2;\n"
16207 " int big = 10000;\n"
16208 "}",
16209 Alignment);
16210 verifyFormat("class C {\n"
16211 "public:\n"
16212 " int i = 1;\n"
16213 " virtual void f() = 0;\n"
16214 "};",
16215 Alignment);
16216 verifyFormat("float i = 1;\n"
16217 "if (SomeType t = getSomething()) {\n"
16218 "}\n"
16219 "const unsigned j = 2;\n"
16220 "int big = 10000;",
16221 Alignment);
16222 verifyFormat("float j = 7;\n"
16223 "for (int k = 0; k < N; ++k) {\n"
16224 "}\n"
16225 "unsigned j = 2;\n"
16226 "int big = 10000;\n"
16227 "}",
16228 Alignment);
16229 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16230 verifyFormat("float i = 1;\n"
16231 "LooooooooooongType loooooooooooooooooooooongVariable\n"
16232 " = someLooooooooooooooooongFunction();\n"
16233 "int j = 2;",
16234 Alignment);
16235 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16236 verifyFormat("int i = 1;\n"
16237 "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16238 " someLooooooooooooooooongFunction();\n"
16239 "int j = 2;",
16240 Alignment);
16241
16242 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16243 verifyFormat("auto lambda = []() {\n"
16244 " auto ii = 0;\n"
16245 " float j = 0;\n"
16246 " return 0;\n"
16247 "};\n"
16248 "int i = 0;\n"
16249 "float i2 = 0;\n"
16250 "auto v = type{\n"
16251 " i = 1, //\n"
16252 " (i = 2), //\n"
16253 " i = 3 //\n"
16254 "};",
16255 Alignment);
16256 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16257
16258 verifyFormat(
16259 "int i = 1;\n"
16260 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16261 " loooooooooooooooooooooongParameterB);\n"
16262 "int j = 2;",
16263 Alignment);
16264
16265 // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16266 // We expect declarations and assignments to align, as long as it doesn't
16267 // exceed the column limit, starting a new alignment sequence whenever it
16268 // happens.
16269 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16270 Alignment.ColumnLimit = 30;
16271 verifyFormat("float ii = 1;\n"
16272 "unsigned j = 2;\n"
16273 "int someVerylongVariable = 1;\n"
16274 "AnotherLongType ll = 123456;\n"
16275 "VeryVeryLongType k = 2;\n"
16276 "int myvar = 1;",
16277 Alignment);
16278 Alignment.ColumnLimit = 80;
16279 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16280
16281 verifyFormat(
16282 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
16283 " typename LongType, typename B>\n"
16284 "auto foo() {}\n",
16285 Alignment);
16286 verifyFormat("float a, b = 1;\n"
16287 "int c = 2;\n"
16288 "int dd = 3;\n",
16289 Alignment);
16290 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
16291 "float b[1][] = {{3.f}};\n",
16292 Alignment);
16293 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16294 verifyFormat("float a, b = 1;\n"
16295 "int c = 2;\n"
16296 "int dd = 3;\n",
16297 Alignment);
16298 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
16299 "float b[1][] = {{3.f}};\n",
16300 Alignment);
16301 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16302
16303 Alignment.ColumnLimit = 30;
16304 Alignment.BinPackParameters = false;
16305 verifyFormat("void foo(float a,\n"
16306 " float b,\n"
16307 " int c,\n"
16308 " uint32_t *d) {\n"
16309 " int *e = 0;\n"
16310 " float f = 0;\n"
16311 " double g = 0;\n"
16312 "}\n"
16313 "void bar(ino_t a,\n"
16314 " int b,\n"
16315 " uint32_t *c,\n"
16316 " bool d) {}\n",
16317 Alignment);
16318 Alignment.BinPackParameters = true;
16319 Alignment.ColumnLimit = 80;
16320
16321 // Bug 33507
16322 Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16323 verifyFormat(
16324 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
16325 " static const Version verVs2017;\n"
16326 " return true;\n"
16327 "});\n",
16328 Alignment);
16329 Alignment.PointerAlignment = FormatStyle::PAS_Right;
16330
16331 // See llvm.org/PR35641
16332 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16333 verifyFormat("int func() { //\n"
16334 " int b;\n"
16335 " unsigned c;\n"
16336 "}",
16337 Alignment);
16338
16339 // See PR37175
16340 FormatStyle Style = getMozillaStyle();
16341 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16342 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
16343 "foo(int a);",
16344 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
16345
16346 Alignment.PointerAlignment = FormatStyle::PAS_Left;
16347 verifyFormat("unsigned int* a;\n"
16348 "int* b;\n"
16349 "unsigned int Const* c;\n"
16350 "unsigned int const* d;\n"
16351 "unsigned int Const& e;\n"
16352 "unsigned int const& f;",
16353 Alignment);
16354 verifyFormat("Const unsigned int* c;\n"
16355 "const unsigned int* d;\n"
16356 "Const unsigned int& e;\n"
16357 "const unsigned int& f;\n"
16358 "const unsigned g;\n"
16359 "Const unsigned h;",
16360 Alignment);
16361
16362 Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16363 verifyFormat("unsigned int * a;\n"
16364 "int * b;\n"
16365 "unsigned int Const * c;\n"
16366 "unsigned int const * d;\n"
16367 "unsigned int Const & e;\n"
16368 "unsigned int const & f;",
16369 Alignment);
16370 verifyFormat("Const unsigned int * c;\n"
16371 "const unsigned int * d;\n"
16372 "Const unsigned int & e;\n"
16373 "const unsigned int & f;\n"
16374 "const unsigned g;\n"
16375 "Const unsigned h;",
16376 Alignment);
16377 }
16378
TEST_F(FormatTest,AlignWithLineBreaks)16379 TEST_F(FormatTest, AlignWithLineBreaks) {
16380 auto Style = getLLVMStyleWithColumns(120);
16381
16382 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
16383 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16384 verifyFormat("void foo() {\n"
16385 " int myVar = 5;\n"
16386 " double x = 3.14;\n"
16387 " auto str = \"Hello \"\n"
16388 " \"World\";\n"
16389 " auto s = \"Hello \"\n"
16390 " \"Again\";\n"
16391 "}",
16392 Style);
16393
16394 // clang-format off
16395 verifyFormat("void foo() {\n"
16396 " const int capacityBefore = Entries.capacity();\n"
16397 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16398 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16399 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16400 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16401 "}",
16402 Style);
16403 // clang-format on
16404
16405 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16406 verifyFormat("void foo() {\n"
16407 " int myVar = 5;\n"
16408 " double x = 3.14;\n"
16409 " auto str = \"Hello \"\n"
16410 " \"World\";\n"
16411 " auto s = \"Hello \"\n"
16412 " \"Again\";\n"
16413 "}",
16414 Style);
16415
16416 // clang-format off
16417 verifyFormat("void foo() {\n"
16418 " const int capacityBefore = Entries.capacity();\n"
16419 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16420 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16421 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16422 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16423 "}",
16424 Style);
16425 // clang-format on
16426
16427 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16428 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16429 verifyFormat("void foo() {\n"
16430 " int myVar = 5;\n"
16431 " double x = 3.14;\n"
16432 " auto str = \"Hello \"\n"
16433 " \"World\";\n"
16434 " auto s = \"Hello \"\n"
16435 " \"Again\";\n"
16436 "}",
16437 Style);
16438
16439 // clang-format off
16440 verifyFormat("void foo() {\n"
16441 " const int capacityBefore = Entries.capacity();\n"
16442 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16443 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16444 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16445 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16446 "}",
16447 Style);
16448 // clang-format on
16449
16450 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16451 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16452
16453 verifyFormat("void foo() {\n"
16454 " int myVar = 5;\n"
16455 " double x = 3.14;\n"
16456 " auto str = \"Hello \"\n"
16457 " \"World\";\n"
16458 " auto s = \"Hello \"\n"
16459 " \"Again\";\n"
16460 "}",
16461 Style);
16462
16463 // clang-format off
16464 verifyFormat("void foo() {\n"
16465 " const int capacityBefore = Entries.capacity();\n"
16466 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16467 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16468 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16469 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16470 "}",
16471 Style);
16472 // clang-format on
16473
16474 Style = getLLVMStyleWithColumns(120);
16475 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16476 Style.ContinuationIndentWidth = 4;
16477 Style.IndentWidth = 4;
16478
16479 // clang-format off
16480 verifyFormat("void SomeFunc() {\n"
16481 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16482 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16483 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16484 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16485 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16486 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16487 "}",
16488 Style);
16489 // clang-format on
16490
16491 Style.BinPackArguments = false;
16492
16493 // clang-format off
16494 verifyFormat("void SomeFunc() {\n"
16495 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
16496 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16497 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n"
16498 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16499 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n"
16500 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16501 "}",
16502 Style);
16503 // clang-format on
16504 }
16505
TEST_F(FormatTest,AlignWithInitializerPeriods)16506 TEST_F(FormatTest, AlignWithInitializerPeriods) {
16507 auto Style = getLLVMStyleWithColumns(60);
16508
16509 verifyFormat("void foo1(void) {\n"
16510 " BYTE p[1] = 1;\n"
16511 " A B = {.one_foooooooooooooooo = 2,\n"
16512 " .two_fooooooooooooo = 3,\n"
16513 " .three_fooooooooooooo = 4};\n"
16514 " BYTE payload = 2;\n"
16515 "}",
16516 Style);
16517
16518 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16519 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16520 verifyFormat("void foo2(void) {\n"
16521 " BYTE p[1] = 1;\n"
16522 " A B = {.one_foooooooooooooooo = 2,\n"
16523 " .two_fooooooooooooo = 3,\n"
16524 " .three_fooooooooooooo = 4};\n"
16525 " BYTE payload = 2;\n"
16526 "}",
16527 Style);
16528
16529 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16530 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16531 verifyFormat("void foo3(void) {\n"
16532 " BYTE p[1] = 1;\n"
16533 " A B = {.one_foooooooooooooooo = 2,\n"
16534 " .two_fooooooooooooo = 3,\n"
16535 " .three_fooooooooooooo = 4};\n"
16536 " BYTE payload = 2;\n"
16537 "}",
16538 Style);
16539
16540 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16541 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16542 verifyFormat("void foo4(void) {\n"
16543 " BYTE p[1] = 1;\n"
16544 " A B = {.one_foooooooooooooooo = 2,\n"
16545 " .two_fooooooooooooo = 3,\n"
16546 " .three_fooooooooooooo = 4};\n"
16547 " BYTE payload = 2;\n"
16548 "}",
16549 Style);
16550 }
16551
TEST_F(FormatTest,LinuxBraceBreaking)16552 TEST_F(FormatTest, LinuxBraceBreaking) {
16553 FormatStyle LinuxBraceStyle = getLLVMStyle();
16554 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
16555 verifyFormat("namespace a\n"
16556 "{\n"
16557 "class A\n"
16558 "{\n"
16559 " void f()\n"
16560 " {\n"
16561 " if (true) {\n"
16562 " a();\n"
16563 " b();\n"
16564 " } else {\n"
16565 " a();\n"
16566 " }\n"
16567 " }\n"
16568 " void g() { return; }\n"
16569 "};\n"
16570 "struct B {\n"
16571 " int x;\n"
16572 "};\n"
16573 "} // namespace a\n",
16574 LinuxBraceStyle);
16575 verifyFormat("enum X {\n"
16576 " Y = 0,\n"
16577 "}\n",
16578 LinuxBraceStyle);
16579 verifyFormat("struct S {\n"
16580 " int Type;\n"
16581 " union {\n"
16582 " int x;\n"
16583 " double y;\n"
16584 " } Value;\n"
16585 " class C\n"
16586 " {\n"
16587 " MyFavoriteType Value;\n"
16588 " } Class;\n"
16589 "}\n",
16590 LinuxBraceStyle);
16591 }
16592
TEST_F(FormatTest,MozillaBraceBreaking)16593 TEST_F(FormatTest, MozillaBraceBreaking) {
16594 FormatStyle MozillaBraceStyle = getLLVMStyle();
16595 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
16596 MozillaBraceStyle.FixNamespaceComments = false;
16597 verifyFormat("namespace a {\n"
16598 "class A\n"
16599 "{\n"
16600 " void f()\n"
16601 " {\n"
16602 " if (true) {\n"
16603 " a();\n"
16604 " b();\n"
16605 " }\n"
16606 " }\n"
16607 " void g() { return; }\n"
16608 "};\n"
16609 "enum E\n"
16610 "{\n"
16611 " A,\n"
16612 " // foo\n"
16613 " B,\n"
16614 " C\n"
16615 "};\n"
16616 "struct B\n"
16617 "{\n"
16618 " int x;\n"
16619 "};\n"
16620 "}\n",
16621 MozillaBraceStyle);
16622 verifyFormat("struct S\n"
16623 "{\n"
16624 " int Type;\n"
16625 " union\n"
16626 " {\n"
16627 " int x;\n"
16628 " double y;\n"
16629 " } Value;\n"
16630 " class C\n"
16631 " {\n"
16632 " MyFavoriteType Value;\n"
16633 " } Class;\n"
16634 "}\n",
16635 MozillaBraceStyle);
16636 }
16637
TEST_F(FormatTest,StroustrupBraceBreaking)16638 TEST_F(FormatTest, StroustrupBraceBreaking) {
16639 FormatStyle StroustrupBraceStyle = getLLVMStyle();
16640 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
16641 verifyFormat("namespace a {\n"
16642 "class A {\n"
16643 " void f()\n"
16644 " {\n"
16645 " if (true) {\n"
16646 " a();\n"
16647 " b();\n"
16648 " }\n"
16649 " }\n"
16650 " void g() { return; }\n"
16651 "};\n"
16652 "struct B {\n"
16653 " int x;\n"
16654 "};\n"
16655 "} // namespace a\n",
16656 StroustrupBraceStyle);
16657
16658 verifyFormat("void foo()\n"
16659 "{\n"
16660 " if (a) {\n"
16661 " a();\n"
16662 " }\n"
16663 " else {\n"
16664 " b();\n"
16665 " }\n"
16666 "}\n",
16667 StroustrupBraceStyle);
16668
16669 verifyFormat("#ifdef _DEBUG\n"
16670 "int foo(int i = 0)\n"
16671 "#else\n"
16672 "int foo(int i = 5)\n"
16673 "#endif\n"
16674 "{\n"
16675 " return i;\n"
16676 "}",
16677 StroustrupBraceStyle);
16678
16679 verifyFormat("void foo() {}\n"
16680 "void bar()\n"
16681 "#ifdef _DEBUG\n"
16682 "{\n"
16683 " foo();\n"
16684 "}\n"
16685 "#else\n"
16686 "{\n"
16687 "}\n"
16688 "#endif",
16689 StroustrupBraceStyle);
16690
16691 verifyFormat("void foobar() { int i = 5; }\n"
16692 "#ifdef _DEBUG\n"
16693 "void bar() {}\n"
16694 "#else\n"
16695 "void bar() { foobar(); }\n"
16696 "#endif",
16697 StroustrupBraceStyle);
16698 }
16699
TEST_F(FormatTest,AllmanBraceBreaking)16700 TEST_F(FormatTest, AllmanBraceBreaking) {
16701 FormatStyle AllmanBraceStyle = getLLVMStyle();
16702 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
16703
16704 EXPECT_EQ("namespace a\n"
16705 "{\n"
16706 "void f();\n"
16707 "void g();\n"
16708 "} // namespace a\n",
16709 format("namespace a\n"
16710 "{\n"
16711 "void f();\n"
16712 "void g();\n"
16713 "}\n",
16714 AllmanBraceStyle));
16715
16716 verifyFormat("namespace a\n"
16717 "{\n"
16718 "class A\n"
16719 "{\n"
16720 " void f()\n"
16721 " {\n"
16722 " if (true)\n"
16723 " {\n"
16724 " a();\n"
16725 " b();\n"
16726 " }\n"
16727 " }\n"
16728 " void g() { return; }\n"
16729 "};\n"
16730 "struct B\n"
16731 "{\n"
16732 " int x;\n"
16733 "};\n"
16734 "union C\n"
16735 "{\n"
16736 "};\n"
16737 "} // namespace a",
16738 AllmanBraceStyle);
16739
16740 verifyFormat("void f()\n"
16741 "{\n"
16742 " if (true)\n"
16743 " {\n"
16744 " a();\n"
16745 " }\n"
16746 " else if (false)\n"
16747 " {\n"
16748 " b();\n"
16749 " }\n"
16750 " else\n"
16751 " {\n"
16752 " c();\n"
16753 " }\n"
16754 "}\n",
16755 AllmanBraceStyle);
16756
16757 verifyFormat("void f()\n"
16758 "{\n"
16759 " for (int i = 0; i < 10; ++i)\n"
16760 " {\n"
16761 " a();\n"
16762 " }\n"
16763 " while (false)\n"
16764 " {\n"
16765 " b();\n"
16766 " }\n"
16767 " do\n"
16768 " {\n"
16769 " c();\n"
16770 " } while (false)\n"
16771 "}\n",
16772 AllmanBraceStyle);
16773
16774 verifyFormat("void f(int a)\n"
16775 "{\n"
16776 " switch (a)\n"
16777 " {\n"
16778 " case 0:\n"
16779 " break;\n"
16780 " case 1:\n"
16781 " {\n"
16782 " break;\n"
16783 " }\n"
16784 " case 2:\n"
16785 " {\n"
16786 " }\n"
16787 " break;\n"
16788 " default:\n"
16789 " break;\n"
16790 " }\n"
16791 "}\n",
16792 AllmanBraceStyle);
16793
16794 verifyFormat("enum X\n"
16795 "{\n"
16796 " Y = 0,\n"
16797 "}\n",
16798 AllmanBraceStyle);
16799 verifyFormat("enum X\n"
16800 "{\n"
16801 " Y = 0\n"
16802 "}\n",
16803 AllmanBraceStyle);
16804
16805 verifyFormat("@interface BSApplicationController ()\n"
16806 "{\n"
16807 "@private\n"
16808 " id _extraIvar;\n"
16809 "}\n"
16810 "@end\n",
16811 AllmanBraceStyle);
16812
16813 verifyFormat("#ifdef _DEBUG\n"
16814 "int foo(int i = 0)\n"
16815 "#else\n"
16816 "int foo(int i = 5)\n"
16817 "#endif\n"
16818 "{\n"
16819 " return i;\n"
16820 "}",
16821 AllmanBraceStyle);
16822
16823 verifyFormat("void foo() {}\n"
16824 "void bar()\n"
16825 "#ifdef _DEBUG\n"
16826 "{\n"
16827 " foo();\n"
16828 "}\n"
16829 "#else\n"
16830 "{\n"
16831 "}\n"
16832 "#endif",
16833 AllmanBraceStyle);
16834
16835 verifyFormat("void foobar() { int i = 5; }\n"
16836 "#ifdef _DEBUG\n"
16837 "void bar() {}\n"
16838 "#else\n"
16839 "void bar() { foobar(); }\n"
16840 "#endif",
16841 AllmanBraceStyle);
16842
16843 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
16844 FormatStyle::SLS_All);
16845
16846 verifyFormat("[](int i) { return i + 2; };\n"
16847 "[](int i, int j)\n"
16848 "{\n"
16849 " auto x = i + j;\n"
16850 " auto y = i * j;\n"
16851 " return x ^ y;\n"
16852 "};\n"
16853 "void foo()\n"
16854 "{\n"
16855 " auto shortLambda = [](int i) { return i + 2; };\n"
16856 " auto longLambda = [](int i, int j)\n"
16857 " {\n"
16858 " auto x = i + j;\n"
16859 " auto y = i * j;\n"
16860 " return x ^ y;\n"
16861 " };\n"
16862 "}",
16863 AllmanBraceStyle);
16864
16865 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
16866
16867 verifyFormat("[](int i)\n"
16868 "{\n"
16869 " return i + 2;\n"
16870 "};\n"
16871 "[](int i, int j)\n"
16872 "{\n"
16873 " auto x = i + j;\n"
16874 " auto y = i * j;\n"
16875 " return x ^ y;\n"
16876 "};\n"
16877 "void foo()\n"
16878 "{\n"
16879 " auto shortLambda = [](int i)\n"
16880 " {\n"
16881 " return i + 2;\n"
16882 " };\n"
16883 " auto longLambda = [](int i, int j)\n"
16884 " {\n"
16885 " auto x = i + j;\n"
16886 " auto y = i * j;\n"
16887 " return x ^ y;\n"
16888 " };\n"
16889 "}",
16890 AllmanBraceStyle);
16891
16892 // Reset
16893 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
16894
16895 // This shouldn't affect ObjC blocks..
16896 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
16897 " // ...\n"
16898 " int i;\n"
16899 "}];",
16900 AllmanBraceStyle);
16901 verifyFormat("void (^block)(void) = ^{\n"
16902 " // ...\n"
16903 " int i;\n"
16904 "};",
16905 AllmanBraceStyle);
16906 // .. or dict literals.
16907 verifyFormat("void f()\n"
16908 "{\n"
16909 " // ...\n"
16910 " [object someMethod:@{@\"a\" : @\"b\"}];\n"
16911 "}",
16912 AllmanBraceStyle);
16913 verifyFormat("void f()\n"
16914 "{\n"
16915 " // ...\n"
16916 " [object someMethod:@{a : @\"b\"}];\n"
16917 "}",
16918 AllmanBraceStyle);
16919 verifyFormat("int f()\n"
16920 "{ // comment\n"
16921 " return 42;\n"
16922 "}",
16923 AllmanBraceStyle);
16924
16925 AllmanBraceStyle.ColumnLimit = 19;
16926 verifyFormat("void f() { int i; }", AllmanBraceStyle);
16927 AllmanBraceStyle.ColumnLimit = 18;
16928 verifyFormat("void f()\n"
16929 "{\n"
16930 " int i;\n"
16931 "}",
16932 AllmanBraceStyle);
16933 AllmanBraceStyle.ColumnLimit = 80;
16934
16935 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
16936 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
16937 FormatStyle::SIS_WithoutElse;
16938 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
16939 verifyFormat("void f(bool b)\n"
16940 "{\n"
16941 " if (b)\n"
16942 " {\n"
16943 " return;\n"
16944 " }\n"
16945 "}\n",
16946 BreakBeforeBraceShortIfs);
16947 verifyFormat("void f(bool b)\n"
16948 "{\n"
16949 " if constexpr (b)\n"
16950 " {\n"
16951 " return;\n"
16952 " }\n"
16953 "}\n",
16954 BreakBeforeBraceShortIfs);
16955 verifyFormat("void f(bool b)\n"
16956 "{\n"
16957 " if CONSTEXPR (b)\n"
16958 " {\n"
16959 " return;\n"
16960 " }\n"
16961 "}\n",
16962 BreakBeforeBraceShortIfs);
16963 verifyFormat("void f(bool b)\n"
16964 "{\n"
16965 " if (b) return;\n"
16966 "}\n",
16967 BreakBeforeBraceShortIfs);
16968 verifyFormat("void f(bool b)\n"
16969 "{\n"
16970 " if constexpr (b) return;\n"
16971 "}\n",
16972 BreakBeforeBraceShortIfs);
16973 verifyFormat("void f(bool b)\n"
16974 "{\n"
16975 " if CONSTEXPR (b) return;\n"
16976 "}\n",
16977 BreakBeforeBraceShortIfs);
16978 verifyFormat("void f(bool b)\n"
16979 "{\n"
16980 " while (b)\n"
16981 " {\n"
16982 " return;\n"
16983 " }\n"
16984 "}\n",
16985 BreakBeforeBraceShortIfs);
16986 }
16987
TEST_F(FormatTest,WhitesmithsBraceBreaking)16988 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
16989 FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
16990 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
16991
16992 // Make a few changes to the style for testing purposes
16993 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
16994 FormatStyle::SFS_Empty;
16995 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
16996 WhitesmithsBraceStyle.ColumnLimit = 0;
16997
16998 // FIXME: this test case can't decide whether there should be a blank line
16999 // after the ~D() line or not. It adds one if one doesn't exist in the test
17000 // and it removes the line if one exists.
17001 /*
17002 verifyFormat("class A;\n"
17003 "namespace B\n"
17004 " {\n"
17005 "class C;\n"
17006 "// Comment\n"
17007 "class D\n"
17008 " {\n"
17009 "public:\n"
17010 " D();\n"
17011 " ~D() {}\n"
17012 "private:\n"
17013 " enum E\n"
17014 " {\n"
17015 " F\n"
17016 " }\n"
17017 " };\n"
17018 " } // namespace B\n",
17019 WhitesmithsBraceStyle);
17020 */
17021
17022 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17023 verifyFormat("namespace a\n"
17024 " {\n"
17025 "class A\n"
17026 " {\n"
17027 " void f()\n"
17028 " {\n"
17029 " if (true)\n"
17030 " {\n"
17031 " a();\n"
17032 " b();\n"
17033 " }\n"
17034 " }\n"
17035 " void g()\n"
17036 " {\n"
17037 " return;\n"
17038 " }\n"
17039 " };\n"
17040 "struct B\n"
17041 " {\n"
17042 " int x;\n"
17043 " };\n"
17044 " } // namespace a",
17045 WhitesmithsBraceStyle);
17046
17047 verifyFormat("namespace a\n"
17048 " {\n"
17049 "namespace b\n"
17050 " {\n"
17051 "class A\n"
17052 " {\n"
17053 " void f()\n"
17054 " {\n"
17055 " if (true)\n"
17056 " {\n"
17057 " a();\n"
17058 " b();\n"
17059 " }\n"
17060 " }\n"
17061 " void g()\n"
17062 " {\n"
17063 " return;\n"
17064 " }\n"
17065 " };\n"
17066 "struct B\n"
17067 " {\n"
17068 " int x;\n"
17069 " };\n"
17070 " } // namespace b\n"
17071 " } // namespace a",
17072 WhitesmithsBraceStyle);
17073
17074 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17075 verifyFormat("namespace a\n"
17076 " {\n"
17077 "namespace b\n"
17078 " {\n"
17079 " class A\n"
17080 " {\n"
17081 " void f()\n"
17082 " {\n"
17083 " if (true)\n"
17084 " {\n"
17085 " a();\n"
17086 " b();\n"
17087 " }\n"
17088 " }\n"
17089 " void g()\n"
17090 " {\n"
17091 " return;\n"
17092 " }\n"
17093 " };\n"
17094 " struct B\n"
17095 " {\n"
17096 " int x;\n"
17097 " };\n"
17098 " } // namespace b\n"
17099 " } // namespace a",
17100 WhitesmithsBraceStyle);
17101
17102 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17103 verifyFormat("namespace a\n"
17104 " {\n"
17105 " namespace b\n"
17106 " {\n"
17107 " class A\n"
17108 " {\n"
17109 " void f()\n"
17110 " {\n"
17111 " if (true)\n"
17112 " {\n"
17113 " a();\n"
17114 " b();\n"
17115 " }\n"
17116 " }\n"
17117 " void g()\n"
17118 " {\n"
17119 " return;\n"
17120 " }\n"
17121 " };\n"
17122 " struct B\n"
17123 " {\n"
17124 " int x;\n"
17125 " };\n"
17126 " } // namespace b\n"
17127 " } // namespace a",
17128 WhitesmithsBraceStyle);
17129
17130 verifyFormat("void f()\n"
17131 " {\n"
17132 " if (true)\n"
17133 " {\n"
17134 " a();\n"
17135 " }\n"
17136 " else if (false)\n"
17137 " {\n"
17138 " b();\n"
17139 " }\n"
17140 " else\n"
17141 " {\n"
17142 " c();\n"
17143 " }\n"
17144 " }\n",
17145 WhitesmithsBraceStyle);
17146
17147 verifyFormat("void f()\n"
17148 " {\n"
17149 " for (int i = 0; i < 10; ++i)\n"
17150 " {\n"
17151 " a();\n"
17152 " }\n"
17153 " while (false)\n"
17154 " {\n"
17155 " b();\n"
17156 " }\n"
17157 " do\n"
17158 " {\n"
17159 " c();\n"
17160 " } while (false)\n"
17161 " }\n",
17162 WhitesmithsBraceStyle);
17163
17164 WhitesmithsBraceStyle.IndentCaseLabels = true;
17165 verifyFormat("void switchTest1(int a)\n"
17166 " {\n"
17167 " switch (a)\n"
17168 " {\n"
17169 " case 2:\n"
17170 " {\n"
17171 " }\n"
17172 " break;\n"
17173 " }\n"
17174 " }\n",
17175 WhitesmithsBraceStyle);
17176
17177 verifyFormat("void switchTest2(int a)\n"
17178 " {\n"
17179 " switch (a)\n"
17180 " {\n"
17181 " case 0:\n"
17182 " break;\n"
17183 " case 1:\n"
17184 " {\n"
17185 " break;\n"
17186 " }\n"
17187 " case 2:\n"
17188 " {\n"
17189 " }\n"
17190 " break;\n"
17191 " default:\n"
17192 " break;\n"
17193 " }\n"
17194 " }\n",
17195 WhitesmithsBraceStyle);
17196
17197 verifyFormat("void switchTest3(int a)\n"
17198 " {\n"
17199 " switch (a)\n"
17200 " {\n"
17201 " case 0:\n"
17202 " {\n"
17203 " foo(x);\n"
17204 " }\n"
17205 " break;\n"
17206 " default:\n"
17207 " {\n"
17208 " foo(1);\n"
17209 " }\n"
17210 " break;\n"
17211 " }\n"
17212 " }\n",
17213 WhitesmithsBraceStyle);
17214
17215 WhitesmithsBraceStyle.IndentCaseLabels = false;
17216
17217 verifyFormat("void switchTest4(int a)\n"
17218 " {\n"
17219 " switch (a)\n"
17220 " {\n"
17221 " case 2:\n"
17222 " {\n"
17223 " }\n"
17224 " break;\n"
17225 " }\n"
17226 " }\n",
17227 WhitesmithsBraceStyle);
17228
17229 verifyFormat("void switchTest5(int a)\n"
17230 " {\n"
17231 " switch (a)\n"
17232 " {\n"
17233 " case 0:\n"
17234 " break;\n"
17235 " case 1:\n"
17236 " {\n"
17237 " foo();\n"
17238 " break;\n"
17239 " }\n"
17240 " case 2:\n"
17241 " {\n"
17242 " }\n"
17243 " break;\n"
17244 " default:\n"
17245 " break;\n"
17246 " }\n"
17247 " }\n",
17248 WhitesmithsBraceStyle);
17249
17250 verifyFormat("void switchTest6(int a)\n"
17251 " {\n"
17252 " switch (a)\n"
17253 " {\n"
17254 " case 0:\n"
17255 " {\n"
17256 " foo(x);\n"
17257 " }\n"
17258 " break;\n"
17259 " default:\n"
17260 " {\n"
17261 " foo(1);\n"
17262 " }\n"
17263 " break;\n"
17264 " }\n"
17265 " }\n",
17266 WhitesmithsBraceStyle);
17267
17268 verifyFormat("enum X\n"
17269 " {\n"
17270 " Y = 0, // testing\n"
17271 " }\n",
17272 WhitesmithsBraceStyle);
17273
17274 verifyFormat("enum X\n"
17275 " {\n"
17276 " Y = 0\n"
17277 " }\n",
17278 WhitesmithsBraceStyle);
17279 verifyFormat("enum X\n"
17280 " {\n"
17281 " Y = 0,\n"
17282 " Z = 1\n"
17283 " };\n",
17284 WhitesmithsBraceStyle);
17285
17286 verifyFormat("@interface BSApplicationController ()\n"
17287 " {\n"
17288 "@private\n"
17289 " id _extraIvar;\n"
17290 " }\n"
17291 "@end\n",
17292 WhitesmithsBraceStyle);
17293
17294 verifyFormat("#ifdef _DEBUG\n"
17295 "int foo(int i = 0)\n"
17296 "#else\n"
17297 "int foo(int i = 5)\n"
17298 "#endif\n"
17299 " {\n"
17300 " return i;\n"
17301 " }",
17302 WhitesmithsBraceStyle);
17303
17304 verifyFormat("void foo() {}\n"
17305 "void bar()\n"
17306 "#ifdef _DEBUG\n"
17307 " {\n"
17308 " foo();\n"
17309 " }\n"
17310 "#else\n"
17311 " {\n"
17312 " }\n"
17313 "#endif",
17314 WhitesmithsBraceStyle);
17315
17316 verifyFormat("void foobar()\n"
17317 " {\n"
17318 " int i = 5;\n"
17319 " }\n"
17320 "#ifdef _DEBUG\n"
17321 "void bar()\n"
17322 " {\n"
17323 " }\n"
17324 "#else\n"
17325 "void bar()\n"
17326 " {\n"
17327 " foobar();\n"
17328 " }\n"
17329 "#endif",
17330 WhitesmithsBraceStyle);
17331
17332 // This shouldn't affect ObjC blocks..
17333 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17334 " // ...\n"
17335 " int i;\n"
17336 "}];",
17337 WhitesmithsBraceStyle);
17338 verifyFormat("void (^block)(void) = ^{\n"
17339 " // ...\n"
17340 " int i;\n"
17341 "};",
17342 WhitesmithsBraceStyle);
17343 // .. or dict literals.
17344 verifyFormat("void f()\n"
17345 " {\n"
17346 " [object someMethod:@{@\"a\" : @\"b\"}];\n"
17347 " }",
17348 WhitesmithsBraceStyle);
17349
17350 verifyFormat("int f()\n"
17351 " { // comment\n"
17352 " return 42;\n"
17353 " }",
17354 WhitesmithsBraceStyle);
17355
17356 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
17357 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17358 FormatStyle::SIS_OnlyFirstIf;
17359 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17360 verifyFormat("void f(bool b)\n"
17361 " {\n"
17362 " if (b)\n"
17363 " {\n"
17364 " return;\n"
17365 " }\n"
17366 " }\n",
17367 BreakBeforeBraceShortIfs);
17368 verifyFormat("void f(bool b)\n"
17369 " {\n"
17370 " if (b) return;\n"
17371 " }\n",
17372 BreakBeforeBraceShortIfs);
17373 verifyFormat("void f(bool b)\n"
17374 " {\n"
17375 " while (b)\n"
17376 " {\n"
17377 " return;\n"
17378 " }\n"
17379 " }\n",
17380 BreakBeforeBraceShortIfs);
17381 }
17382
TEST_F(FormatTest,GNUBraceBreaking)17383 TEST_F(FormatTest, GNUBraceBreaking) {
17384 FormatStyle GNUBraceStyle = getLLVMStyle();
17385 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
17386 verifyFormat("namespace a\n"
17387 "{\n"
17388 "class A\n"
17389 "{\n"
17390 " void f()\n"
17391 " {\n"
17392 " int a;\n"
17393 " {\n"
17394 " int b;\n"
17395 " }\n"
17396 " if (true)\n"
17397 " {\n"
17398 " a();\n"
17399 " b();\n"
17400 " }\n"
17401 " }\n"
17402 " void g() { return; }\n"
17403 "}\n"
17404 "} // namespace a",
17405 GNUBraceStyle);
17406
17407 verifyFormat("void f()\n"
17408 "{\n"
17409 " if (true)\n"
17410 " {\n"
17411 " a();\n"
17412 " }\n"
17413 " else if (false)\n"
17414 " {\n"
17415 " b();\n"
17416 " }\n"
17417 " else\n"
17418 " {\n"
17419 " c();\n"
17420 " }\n"
17421 "}\n",
17422 GNUBraceStyle);
17423
17424 verifyFormat("void f()\n"
17425 "{\n"
17426 " for (int i = 0; i < 10; ++i)\n"
17427 " {\n"
17428 " a();\n"
17429 " }\n"
17430 " while (false)\n"
17431 " {\n"
17432 " b();\n"
17433 " }\n"
17434 " do\n"
17435 " {\n"
17436 " c();\n"
17437 " }\n"
17438 " while (false);\n"
17439 "}\n",
17440 GNUBraceStyle);
17441
17442 verifyFormat("void f(int a)\n"
17443 "{\n"
17444 " switch (a)\n"
17445 " {\n"
17446 " case 0:\n"
17447 " break;\n"
17448 " case 1:\n"
17449 " {\n"
17450 " break;\n"
17451 " }\n"
17452 " case 2:\n"
17453 " {\n"
17454 " }\n"
17455 " break;\n"
17456 " default:\n"
17457 " break;\n"
17458 " }\n"
17459 "}\n",
17460 GNUBraceStyle);
17461
17462 verifyFormat("enum X\n"
17463 "{\n"
17464 " Y = 0,\n"
17465 "}\n",
17466 GNUBraceStyle);
17467
17468 verifyFormat("@interface BSApplicationController ()\n"
17469 "{\n"
17470 "@private\n"
17471 " id _extraIvar;\n"
17472 "}\n"
17473 "@end\n",
17474 GNUBraceStyle);
17475
17476 verifyFormat("#ifdef _DEBUG\n"
17477 "int foo(int i = 0)\n"
17478 "#else\n"
17479 "int foo(int i = 5)\n"
17480 "#endif\n"
17481 "{\n"
17482 " return i;\n"
17483 "}",
17484 GNUBraceStyle);
17485
17486 verifyFormat("void foo() {}\n"
17487 "void bar()\n"
17488 "#ifdef _DEBUG\n"
17489 "{\n"
17490 " foo();\n"
17491 "}\n"
17492 "#else\n"
17493 "{\n"
17494 "}\n"
17495 "#endif",
17496 GNUBraceStyle);
17497
17498 verifyFormat("void foobar() { int i = 5; }\n"
17499 "#ifdef _DEBUG\n"
17500 "void bar() {}\n"
17501 "#else\n"
17502 "void bar() { foobar(); }\n"
17503 "#endif",
17504 GNUBraceStyle);
17505 }
17506
TEST_F(FormatTest,WebKitBraceBreaking)17507 TEST_F(FormatTest, WebKitBraceBreaking) {
17508 FormatStyle WebKitBraceStyle = getLLVMStyle();
17509 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
17510 WebKitBraceStyle.FixNamespaceComments = false;
17511 verifyFormat("namespace a {\n"
17512 "class A {\n"
17513 " void f()\n"
17514 " {\n"
17515 " if (true) {\n"
17516 " a();\n"
17517 " b();\n"
17518 " }\n"
17519 " }\n"
17520 " void g() { return; }\n"
17521 "};\n"
17522 "enum E {\n"
17523 " A,\n"
17524 " // foo\n"
17525 " B,\n"
17526 " C\n"
17527 "};\n"
17528 "struct B {\n"
17529 " int x;\n"
17530 "};\n"
17531 "}\n",
17532 WebKitBraceStyle);
17533 verifyFormat("struct S {\n"
17534 " int Type;\n"
17535 " union {\n"
17536 " int x;\n"
17537 " double y;\n"
17538 " } Value;\n"
17539 " class C {\n"
17540 " MyFavoriteType Value;\n"
17541 " } Class;\n"
17542 "};\n",
17543 WebKitBraceStyle);
17544 }
17545
TEST_F(FormatTest,CatchExceptionReferenceBinding)17546 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
17547 verifyFormat("void f() {\n"
17548 " try {\n"
17549 " } catch (const Exception &e) {\n"
17550 " }\n"
17551 "}\n",
17552 getLLVMStyle());
17553 }
17554
TEST_F(FormatTest,CatchAlignArrayOfStructuresRightAlignment)17555 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
17556 auto Style = getLLVMStyle();
17557 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17558 Style.AlignConsecutiveAssignments =
17559 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17560 Style.AlignConsecutiveDeclarations =
17561 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17562 verifyFormat("struct test demo[] = {\n"
17563 " {56, 23, \"hello\"},\n"
17564 " {-1, 93463, \"world\"},\n"
17565 " { 7, 5, \"!!\"}\n"
17566 "};\n",
17567 Style);
17568
17569 verifyFormat("struct test demo[] = {\n"
17570 " {56, 23, \"hello\"}, // first line\n"
17571 " {-1, 93463, \"world\"}, // second line\n"
17572 " { 7, 5, \"!!\"} // third line\n"
17573 "};\n",
17574 Style);
17575
17576 verifyFormat("struct test demo[4] = {\n"
17577 " { 56, 23, 21, \"oh\"}, // first line\n"
17578 " { -1, 93463, 22, \"my\"}, // second line\n"
17579 " { 7, 5, 1, \"goodness\"} // third line\n"
17580 " {234, 5, 1, \"gracious\"} // fourth line\n"
17581 "};\n",
17582 Style);
17583
17584 verifyFormat("struct test demo[3] = {\n"
17585 " {56, 23, \"hello\"},\n"
17586 " {-1, 93463, \"world\"},\n"
17587 " { 7, 5, \"!!\"}\n"
17588 "};\n",
17589 Style);
17590
17591 verifyFormat("struct test demo[3] = {\n"
17592 " {int{56}, 23, \"hello\"},\n"
17593 " {int{-1}, 93463, \"world\"},\n"
17594 " { int{7}, 5, \"!!\"}\n"
17595 "};\n",
17596 Style);
17597
17598 verifyFormat("struct test demo[] = {\n"
17599 " {56, 23, \"hello\"},\n"
17600 " {-1, 93463, \"world\"},\n"
17601 " { 7, 5, \"!!\"},\n"
17602 "};\n",
17603 Style);
17604
17605 verifyFormat("test demo[] = {\n"
17606 " {56, 23, \"hello\"},\n"
17607 " {-1, 93463, \"world\"},\n"
17608 " { 7, 5, \"!!\"},\n"
17609 "};\n",
17610 Style);
17611
17612 verifyFormat("demo = std::array<struct test, 3>{\n"
17613 " test{56, 23, \"hello\"},\n"
17614 " test{-1, 93463, \"world\"},\n"
17615 " test{ 7, 5, \"!!\"},\n"
17616 "};\n",
17617 Style);
17618
17619 verifyFormat("test demo[] = {\n"
17620 " {56, 23, \"hello\"},\n"
17621 "#if X\n"
17622 " {-1, 93463, \"world\"},\n"
17623 "#endif\n"
17624 " { 7, 5, \"!!\"}\n"
17625 "};\n",
17626 Style);
17627
17628 verifyFormat(
17629 "test demo[] = {\n"
17630 " { 7, 23,\n"
17631 " \"hello world i am a very long line that really, in any\"\n"
17632 " \"just world, ought to be split over multiple lines\"},\n"
17633 " {-1, 93463, \"world\"},\n"
17634 " {56, 5, \"!!\"}\n"
17635 "};\n",
17636 Style);
17637
17638 verifyFormat("return GradForUnaryCwise(g, {\n"
17639 " {{\"sign\"}, \"Sign\", "
17640 " {\"x\", \"dy\"}},\n"
17641 " { {\"dx\"}, \"Mul\", {\"dy\""
17642 ", \"sign\"}},\n"
17643 "});\n",
17644 Style);
17645
17646 Style.ColumnLimit = 0;
17647 EXPECT_EQ(
17648 "test demo[] = {\n"
17649 " {56, 23, \"hello world i am a very long line that really, "
17650 "in any just world, ought to be split over multiple lines\"},\n"
17651 " {-1, 93463, "
17652 " \"world\"},\n"
17653 " { 7, 5, "
17654 " \"!!\"},\n"
17655 "};",
17656 format("test demo[] = {{56, 23, \"hello world i am a very long line "
17657 "that really, in any just world, ought to be split over multiple "
17658 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17659 Style));
17660
17661 Style.ColumnLimit = 80;
17662 verifyFormat("test demo[] = {\n"
17663 " {56, 23, /* a comment */ \"hello\"},\n"
17664 " {-1, 93463, \"world\"},\n"
17665 " { 7, 5, \"!!\"}\n"
17666 "};\n",
17667 Style);
17668
17669 verifyFormat("test demo[] = {\n"
17670 " {56, 23, \"hello\"},\n"
17671 " {-1, 93463, \"world\" /* comment here */},\n"
17672 " { 7, 5, \"!!\"}\n"
17673 "};\n",
17674 Style);
17675
17676 verifyFormat("test demo[] = {\n"
17677 " {56, /* a comment */ 23, \"hello\"},\n"
17678 " {-1, 93463, \"world\"},\n"
17679 " { 7, 5, \"!!\"}\n"
17680 "};\n",
17681 Style);
17682
17683 Style.ColumnLimit = 20;
17684 EXPECT_EQ(
17685 "demo = std::array<\n"
17686 " struct test, 3>{\n"
17687 " test{\n"
17688 " 56, 23,\n"
17689 " \"hello \"\n"
17690 " \"world i \"\n"
17691 " \"am a very \"\n"
17692 " \"long line \"\n"
17693 " \"that \"\n"
17694 " \"really, \"\n"
17695 " \"in any \"\n"
17696 " \"just \"\n"
17697 " \"world, \"\n"
17698 " \"ought to \"\n"
17699 " \"be split \"\n"
17700 " \"over \"\n"
17701 " \"multiple \"\n"
17702 " \"lines\"},\n"
17703 " test{-1, 93463,\n"
17704 " \"world\"},\n"
17705 " test{ 7, 5,\n"
17706 " \"!!\" },\n"
17707 "};",
17708 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
17709 "i am a very long line that really, in any just world, ought "
17710 "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
17711 "test{7, 5, \"!!\"},};",
17712 Style));
17713 // This caused a core dump by enabling Alignment in the LLVMStyle globally
17714 Style = getLLVMStyleWithColumns(50);
17715 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17716 verifyFormat("static A x = {\n"
17717 " {{init1, init2, init3, init4},\n"
17718 " {init1, init2, init3, init4}}\n"
17719 "};",
17720 Style);
17721 Style.ColumnLimit = 100;
17722 EXPECT_EQ(
17723 "test demo[] = {\n"
17724 " {56, 23,\n"
17725 " \"hello world i am a very long line that really, in any just world"
17726 ", ought to be split over \"\n"
17727 " \"multiple lines\" },\n"
17728 " {-1, 93463, \"world\"},\n"
17729 " { 7, 5, \"!!\"},\n"
17730 "};",
17731 format("test demo[] = {{56, 23, \"hello world i am a very long line "
17732 "that really, in any just world, ought to be split over multiple "
17733 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17734 Style));
17735
17736 Style = getLLVMStyleWithColumns(50);
17737 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17738 Style.AlignConsecutiveAssignments =
17739 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17740 Style.AlignConsecutiveDeclarations =
17741 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17742 verifyFormat("struct test demo[] = {\n"
17743 " {56, 23, \"hello\"},\n"
17744 " {-1, 93463, \"world\"},\n"
17745 " { 7, 5, \"!!\"}\n"
17746 "};\n"
17747 "static A x = {\n"
17748 " {{init1, init2, init3, init4},\n"
17749 " {init1, init2, init3, init4}}\n"
17750 "};",
17751 Style);
17752 Style.ColumnLimit = 100;
17753 Style.AlignConsecutiveAssignments =
17754 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
17755 Style.AlignConsecutiveDeclarations =
17756 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
17757 verifyFormat("struct test demo[] = {\n"
17758 " {56, 23, \"hello\"},\n"
17759 " {-1, 93463, \"world\"},\n"
17760 " { 7, 5, \"!!\"}\n"
17761 "};\n"
17762 "struct test demo[4] = {\n"
17763 " { 56, 23, 21, \"oh\"}, // first line\n"
17764 " { -1, 93463, 22, \"my\"}, // second line\n"
17765 " { 7, 5, 1, \"goodness\"} // third line\n"
17766 " {234, 5, 1, \"gracious\"} // fourth line\n"
17767 "};\n",
17768 Style);
17769 EXPECT_EQ(
17770 "test demo[] = {\n"
17771 " {56,\n"
17772 " \"hello world i am a very long line that really, in any just world"
17773 ", ought to be split over \"\n"
17774 " \"multiple lines\", 23},\n"
17775 " {-1, \"world\", 93463},\n"
17776 " { 7, \"!!\", 5},\n"
17777 "};",
17778 format("test demo[] = {{56, \"hello world i am a very long line "
17779 "that really, in any just world, ought to be split over multiple "
17780 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
17781 Style));
17782 }
17783
TEST_F(FormatTest,CatchAlignArrayOfStructuresLeftAlignment)17784 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
17785 auto Style = getLLVMStyle();
17786 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
17787 /* FIXME: This case gets misformatted.
17788 verifyFormat("auto foo = Items{\n"
17789 " Section{0, bar(), },\n"
17790 " Section{1, boo() }\n"
17791 "};\n",
17792 Style);
17793 */
17794 verifyFormat("auto foo = Items{\n"
17795 " Section{\n"
17796 " 0, bar(),\n"
17797 " }\n"
17798 "};\n",
17799 Style);
17800 verifyFormat("struct test demo[] = {\n"
17801 " {56, 23, \"hello\"},\n"
17802 " {-1, 93463, \"world\"},\n"
17803 " {7, 5, \"!!\" }\n"
17804 "};\n",
17805 Style);
17806 verifyFormat("struct test demo[] = {\n"
17807 " {56, 23, \"hello\"}, // first line\n"
17808 " {-1, 93463, \"world\"}, // second line\n"
17809 " {7, 5, \"!!\" } // third line\n"
17810 "};\n",
17811 Style);
17812 verifyFormat("struct test demo[4] = {\n"
17813 " {56, 23, 21, \"oh\" }, // first line\n"
17814 " {-1, 93463, 22, \"my\" }, // second line\n"
17815 " {7, 5, 1, \"goodness\"} // third line\n"
17816 " {234, 5, 1, \"gracious\"} // fourth line\n"
17817 "};\n",
17818 Style);
17819 verifyFormat("struct test demo[3] = {\n"
17820 " {56, 23, \"hello\"},\n"
17821 " {-1, 93463, \"world\"},\n"
17822 " {7, 5, \"!!\" }\n"
17823 "};\n",
17824 Style);
17825
17826 verifyFormat("struct test demo[3] = {\n"
17827 " {int{56}, 23, \"hello\"},\n"
17828 " {int{-1}, 93463, \"world\"},\n"
17829 " {int{7}, 5, \"!!\" }\n"
17830 "};\n",
17831 Style);
17832 verifyFormat("struct test demo[] = {\n"
17833 " {56, 23, \"hello\"},\n"
17834 " {-1, 93463, \"world\"},\n"
17835 " {7, 5, \"!!\" },\n"
17836 "};\n",
17837 Style);
17838 verifyFormat("test demo[] = {\n"
17839 " {56, 23, \"hello\"},\n"
17840 " {-1, 93463, \"world\"},\n"
17841 " {7, 5, \"!!\" },\n"
17842 "};\n",
17843 Style);
17844 verifyFormat("demo = std::array<struct test, 3>{\n"
17845 " test{56, 23, \"hello\"},\n"
17846 " test{-1, 93463, \"world\"},\n"
17847 " test{7, 5, \"!!\" },\n"
17848 "};\n",
17849 Style);
17850 verifyFormat("test demo[] = {\n"
17851 " {56, 23, \"hello\"},\n"
17852 "#if X\n"
17853 " {-1, 93463, \"world\"},\n"
17854 "#endif\n"
17855 " {7, 5, \"!!\" }\n"
17856 "};\n",
17857 Style);
17858 verifyFormat(
17859 "test demo[] = {\n"
17860 " {7, 23,\n"
17861 " \"hello world i am a very long line that really, in any\"\n"
17862 " \"just world, ought to be split over multiple lines\"},\n"
17863 " {-1, 93463, \"world\" },\n"
17864 " {56, 5, \"!!\" }\n"
17865 "};\n",
17866 Style);
17867
17868 verifyFormat("return GradForUnaryCwise(g, {\n"
17869 " {{\"sign\"}, \"Sign\", {\"x\", "
17870 "\"dy\"} },\n"
17871 " {{\"dx\"}, \"Mul\", "
17872 "{\"dy\", \"sign\"}},\n"
17873 "});\n",
17874 Style);
17875
17876 Style.ColumnLimit = 0;
17877 EXPECT_EQ(
17878 "test demo[] = {\n"
17879 " {56, 23, \"hello world i am a very long line that really, in any "
17880 "just world, ought to be split over multiple lines\"},\n"
17881 " {-1, 93463, \"world\" "
17882 " },\n"
17883 " {7, 5, \"!!\" "
17884 " },\n"
17885 "};",
17886 format("test demo[] = {{56, 23, \"hello world i am a very long line "
17887 "that really, in any just world, ought to be split over multiple "
17888 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17889 Style));
17890
17891 Style.ColumnLimit = 80;
17892 verifyFormat("test demo[] = {\n"
17893 " {56, 23, /* a comment */ \"hello\"},\n"
17894 " {-1, 93463, \"world\" },\n"
17895 " {7, 5, \"!!\" }\n"
17896 "};\n",
17897 Style);
17898
17899 verifyFormat("test demo[] = {\n"
17900 " {56, 23, \"hello\" },\n"
17901 " {-1, 93463, \"world\" /* comment here */},\n"
17902 " {7, 5, \"!!\" }\n"
17903 "};\n",
17904 Style);
17905
17906 verifyFormat("test demo[] = {\n"
17907 " {56, /* a comment */ 23, \"hello\"},\n"
17908 " {-1, 93463, \"world\"},\n"
17909 " {7, 5, \"!!\" }\n"
17910 "};\n",
17911 Style);
17912
17913 Style.ColumnLimit = 20;
17914 EXPECT_EQ(
17915 "demo = std::array<\n"
17916 " struct test, 3>{\n"
17917 " test{\n"
17918 " 56, 23,\n"
17919 " \"hello \"\n"
17920 " \"world i \"\n"
17921 " \"am a very \"\n"
17922 " \"long line \"\n"
17923 " \"that \"\n"
17924 " \"really, \"\n"
17925 " \"in any \"\n"
17926 " \"just \"\n"
17927 " \"world, \"\n"
17928 " \"ought to \"\n"
17929 " \"be split \"\n"
17930 " \"over \"\n"
17931 " \"multiple \"\n"
17932 " \"lines\"},\n"
17933 " test{-1, 93463,\n"
17934 " \"world\"},\n"
17935 " test{7, 5,\n"
17936 " \"!!\" },\n"
17937 "};",
17938 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
17939 "i am a very long line that really, in any just world, ought "
17940 "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
17941 "test{7, 5, \"!!\"},};",
17942 Style));
17943
17944 // This caused a core dump by enabling Alignment in the LLVMStyle globally
17945 Style = getLLVMStyleWithColumns(50);
17946 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
17947 verifyFormat("static A x = {\n"
17948 " {{init1, init2, init3, init4},\n"
17949 " {init1, init2, init3, init4}}\n"
17950 "};",
17951 Style);
17952 Style.ColumnLimit = 100;
17953 EXPECT_EQ(
17954 "test demo[] = {\n"
17955 " {56, 23,\n"
17956 " \"hello world i am a very long line that really, in any just world"
17957 ", ought to be split over \"\n"
17958 " \"multiple lines\" },\n"
17959 " {-1, 93463, \"world\"},\n"
17960 " {7, 5, \"!!\" },\n"
17961 "};",
17962 format("test demo[] = {{56, 23, \"hello world i am a very long line "
17963 "that really, in any just world, ought to be split over multiple "
17964 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17965 Style));
17966 }
17967
TEST_F(FormatTest,UnderstandsPragmas)17968 TEST_F(FormatTest, UnderstandsPragmas) {
17969 verifyFormat("#pragma omp reduction(| : var)");
17970 verifyFormat("#pragma omp reduction(+ : var)");
17971
17972 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
17973 "(including parentheses).",
17974 format("#pragma mark Any non-hyphenated or hyphenated string "
17975 "(including parentheses)."));
17976 }
17977
TEST_F(FormatTest,UnderstandPragmaOption)17978 TEST_F(FormatTest, UnderstandPragmaOption) {
17979 verifyFormat("#pragma option -C -A");
17980
17981 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A"));
17982 }
17983
TEST_F(FormatTest,OptimizeBreakPenaltyVsExcess)17984 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
17985 FormatStyle Style = getLLVMStyle();
17986 Style.ColumnLimit = 20;
17987
17988 // See PR41213
17989 EXPECT_EQ("/*\n"
17990 " *\t9012345\n"
17991 " * /8901\n"
17992 " */",
17993 format("/*\n"
17994 " *\t9012345 /8901\n"
17995 " */",
17996 Style));
17997 EXPECT_EQ("/*\n"
17998 " *345678\n"
17999 " *\t/8901\n"
18000 " */",
18001 format("/*\n"
18002 " *345678\t/8901\n"
18003 " */",
18004 Style));
18005
18006 verifyFormat("int a; // the\n"
18007 " // comment",
18008 Style);
18009 EXPECT_EQ("int a; /* first line\n"
18010 " * second\n"
18011 " * line third\n"
18012 " * line\n"
18013 " */",
18014 format("int a; /* first line\n"
18015 " * second\n"
18016 " * line third\n"
18017 " * line\n"
18018 " */",
18019 Style));
18020 EXPECT_EQ("int a; // first line\n"
18021 " // second\n"
18022 " // line third\n"
18023 " // line",
18024 format("int a; // first line\n"
18025 " // second line\n"
18026 " // third line",
18027 Style));
18028
18029 Style.PenaltyExcessCharacter = 90;
18030 verifyFormat("int a; // the comment", Style);
18031 EXPECT_EQ("int a; // the comment\n"
18032 " // aaa",
18033 format("int a; // the comment aaa", Style));
18034 EXPECT_EQ("int a; /* first line\n"
18035 " * second line\n"
18036 " * third line\n"
18037 " */",
18038 format("int a; /* first line\n"
18039 " * second line\n"
18040 " * third line\n"
18041 " */",
18042 Style));
18043 EXPECT_EQ("int a; // first line\n"
18044 " // second line\n"
18045 " // third line",
18046 format("int a; // first line\n"
18047 " // second line\n"
18048 " // third line",
18049 Style));
18050 // FIXME: Investigate why this is not getting the same layout as the test
18051 // above.
18052 EXPECT_EQ("int a; /* first line\n"
18053 " * second line\n"
18054 " * third line\n"
18055 " */",
18056 format("int a; /* first line second line third line"
18057 "\n*/",
18058 Style));
18059
18060 EXPECT_EQ("// foo bar baz bazfoo\n"
18061 "// foo bar foo bar\n",
18062 format("// foo bar baz bazfoo\n"
18063 "// foo bar foo bar\n",
18064 Style));
18065 EXPECT_EQ("// foo bar baz bazfoo\n"
18066 "// foo bar foo bar\n",
18067 format("// foo bar baz bazfoo\n"
18068 "// foo bar foo bar\n",
18069 Style));
18070
18071 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18072 // next one.
18073 EXPECT_EQ("// foo bar baz bazfoo\n"
18074 "// bar foo bar\n",
18075 format("// foo bar baz bazfoo bar\n"
18076 "// foo bar\n",
18077 Style));
18078
18079 EXPECT_EQ("// foo bar baz bazfoo\n"
18080 "// foo bar baz bazfoo\n"
18081 "// bar foo bar\n",
18082 format("// foo bar baz bazfoo\n"
18083 "// foo bar baz bazfoo bar\n"
18084 "// foo bar\n",
18085 Style));
18086
18087 EXPECT_EQ("// foo bar baz bazfoo\n"
18088 "// foo bar baz bazfoo\n"
18089 "// bar foo bar\n",
18090 format("// foo bar baz bazfoo\n"
18091 "// foo bar baz bazfoo bar\n"
18092 "// foo bar\n",
18093 Style));
18094
18095 // Make sure we do not keep protruding characters if strict mode reflow is
18096 // cheaper than keeping protruding characters.
18097 Style.ColumnLimit = 21;
18098 EXPECT_EQ(
18099 "// foo foo foo foo\n"
18100 "// foo foo foo foo\n"
18101 "// foo foo foo foo\n",
18102 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18103
18104 EXPECT_EQ("int a = /* long block\n"
18105 " comment */\n"
18106 " 42;",
18107 format("int a = /* long block comment */ 42;", Style));
18108 }
18109
18110 #define EXPECT_ALL_STYLES_EQUAL(Styles) \
18111 for (size_t i = 1; i < Styles.size(); ++i) \
18112 EXPECT_EQ(Styles[0], Styles[i]) \
18113 << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18114
TEST_F(FormatTest,GetsPredefinedStyleByName)18115 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18116 SmallVector<FormatStyle, 3> Styles;
18117 Styles.resize(3);
18118
18119 Styles[0] = getLLVMStyle();
18120 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18121 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18122 EXPECT_ALL_STYLES_EQUAL(Styles);
18123
18124 Styles[0] = getGoogleStyle();
18125 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18126 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18127 EXPECT_ALL_STYLES_EQUAL(Styles);
18128
18129 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18130 EXPECT_TRUE(
18131 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18132 EXPECT_TRUE(
18133 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18134 EXPECT_ALL_STYLES_EQUAL(Styles);
18135
18136 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18137 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18138 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18139 EXPECT_ALL_STYLES_EQUAL(Styles);
18140
18141 Styles[0] = getMozillaStyle();
18142 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18143 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18144 EXPECT_ALL_STYLES_EQUAL(Styles);
18145
18146 Styles[0] = getWebKitStyle();
18147 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18148 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18149 EXPECT_ALL_STYLES_EQUAL(Styles);
18150
18151 Styles[0] = getGNUStyle();
18152 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18153 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18154 EXPECT_ALL_STYLES_EQUAL(Styles);
18155
18156 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18157 }
18158
TEST_F(FormatTest,GetsCorrectBasedOnStyle)18159 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18160 SmallVector<FormatStyle, 8> Styles;
18161 Styles.resize(2);
18162
18163 Styles[0] = getGoogleStyle();
18164 Styles[1] = getLLVMStyle();
18165 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18166 EXPECT_ALL_STYLES_EQUAL(Styles);
18167
18168 Styles.resize(5);
18169 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18170 Styles[1] = getLLVMStyle();
18171 Styles[1].Language = FormatStyle::LK_JavaScript;
18172 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18173
18174 Styles[2] = getLLVMStyle();
18175 Styles[2].Language = FormatStyle::LK_JavaScript;
18176 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18177 "BasedOnStyle: Google",
18178 &Styles[2])
18179 .value());
18180
18181 Styles[3] = getLLVMStyle();
18182 Styles[3].Language = FormatStyle::LK_JavaScript;
18183 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18184 "Language: JavaScript",
18185 &Styles[3])
18186 .value());
18187
18188 Styles[4] = getLLVMStyle();
18189 Styles[4].Language = FormatStyle::LK_JavaScript;
18190 EXPECT_EQ(0, parseConfiguration("---\n"
18191 "BasedOnStyle: LLVM\n"
18192 "IndentWidth: 123\n"
18193 "---\n"
18194 "BasedOnStyle: Google\n"
18195 "Language: JavaScript",
18196 &Styles[4])
18197 .value());
18198 EXPECT_ALL_STYLES_EQUAL(Styles);
18199 }
18200
18201 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \
18202 Style.FIELD = false; \
18203 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \
18204 EXPECT_TRUE(Style.FIELD); \
18205 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \
18206 EXPECT_FALSE(Style.FIELD);
18207
18208 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18209
18210 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \
18211 Style.STRUCT.FIELD = false; \
18212 EXPECT_EQ(0, \
18213 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \
18214 .value()); \
18215 EXPECT_TRUE(Style.STRUCT.FIELD); \
18216 EXPECT_EQ(0, \
18217 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \
18218 .value()); \
18219 EXPECT_FALSE(Style.STRUCT.FIELD);
18220
18221 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \
18222 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
18223
18224 #define CHECK_PARSE(TEXT, FIELD, VALUE) \
18225 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \
18226 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \
18227 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
18228
TEST_F(FormatTest,ParsesConfigurationBools)18229 TEST_F(FormatTest, ParsesConfigurationBools) {
18230 FormatStyle Style = {};
18231 Style.Language = FormatStyle::LK_Cpp;
18232 CHECK_PARSE_BOOL(AlignTrailingComments);
18233 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
18234 CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
18235 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
18236 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
18237 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
18238 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
18239 CHECK_PARSE_BOOL(BinPackArguments);
18240 CHECK_PARSE_BOOL(BinPackParameters);
18241 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
18242 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
18243 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
18244 CHECK_PARSE_BOOL(BreakStringLiterals);
18245 CHECK_PARSE_BOOL(CompactNamespaces);
18246 CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
18247 CHECK_PARSE_BOOL(DeriveLineEnding);
18248 CHECK_PARSE_BOOL(DerivePointerAlignment);
18249 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
18250 CHECK_PARSE_BOOL(DisableFormat);
18251 CHECK_PARSE_BOOL(IndentAccessModifiers);
18252 CHECK_PARSE_BOOL(IndentCaseLabels);
18253 CHECK_PARSE_BOOL(IndentCaseBlocks);
18254 CHECK_PARSE_BOOL(IndentGotoLabels);
18255 CHECK_PARSE_BOOL(IndentRequires);
18256 CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
18257 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
18258 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
18259 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
18260 CHECK_PARSE_BOOL(Cpp11BracedListStyle);
18261 CHECK_PARSE_BOOL(ReflowComments);
18262 CHECK_PARSE_BOOL(SortUsingDeclarations);
18263 CHECK_PARSE_BOOL(SpacesInParentheses);
18264 CHECK_PARSE_BOOL(SpacesInSquareBrackets);
18265 CHECK_PARSE_BOOL(SpacesInConditionalStatement);
18266 CHECK_PARSE_BOOL(SpaceInEmptyBlock);
18267 CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
18268 CHECK_PARSE_BOOL(SpacesInContainerLiterals);
18269 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
18270 CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
18271 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
18272 CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
18273 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
18274 CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
18275 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
18276 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
18277 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
18278 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
18279 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
18280 CHECK_PARSE_BOOL(UseCRLF);
18281
18282 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
18283 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
18284 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
18285 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
18286 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
18287 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
18288 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
18289 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
18290 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
18291 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
18292 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
18293 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
18294 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
18295 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
18296 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
18297 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
18298 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
18299 }
18300
18301 #undef CHECK_PARSE_BOOL
18302
TEST_F(FormatTest,ParsesConfiguration)18303 TEST_F(FormatTest, ParsesConfiguration) {
18304 FormatStyle Style = {};
18305 Style.Language = FormatStyle::LK_Cpp;
18306 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
18307 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
18308 ConstructorInitializerIndentWidth, 1234u);
18309 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
18310 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
18311 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
18312 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
18313 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
18314 PenaltyBreakBeforeFirstCallParameter, 1234u);
18315 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
18316 PenaltyBreakTemplateDeclaration, 1234u);
18317 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
18318 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
18319 PenaltyReturnTypeOnItsOwnLine, 1234u);
18320 CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
18321 SpacesBeforeTrailingComments, 1234u);
18322 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
18323 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
18324 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
18325
18326 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
18327 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
18328 FormatStyle::ACS_None);
18329 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
18330 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
18331 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
18332 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
18333 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
18334 AlignConsecutiveAssignments,
18335 FormatStyle::ACS_AcrossEmptyLinesAndComments);
18336 // For backwards compability, false / true should still parse
18337 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
18338 FormatStyle::ACS_None);
18339 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
18340 FormatStyle::ACS_Consecutive);
18341
18342 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
18343 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
18344 FormatStyle::ACS_None);
18345 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
18346 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
18347 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
18348 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
18349 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
18350 AlignConsecutiveBitFields,
18351 FormatStyle::ACS_AcrossEmptyLinesAndComments);
18352 // For backwards compability, false / true should still parse
18353 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
18354 FormatStyle::ACS_None);
18355 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
18356 FormatStyle::ACS_Consecutive);
18357
18358 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
18359 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
18360 FormatStyle::ACS_None);
18361 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
18362 FormatStyle::ACS_Consecutive);
18363 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
18364 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
18365 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
18366 AlignConsecutiveMacros,
18367 FormatStyle::ACS_AcrossEmptyLinesAndComments);
18368 // For backwards compability, false / true should still parse
18369 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
18370 FormatStyle::ACS_None);
18371 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
18372 FormatStyle::ACS_Consecutive);
18373
18374 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
18375 CHECK_PARSE("AlignConsecutiveDeclarations: None",
18376 AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18377 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
18378 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18379 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
18380 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
18381 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
18382 AlignConsecutiveDeclarations,
18383 FormatStyle::ACS_AcrossEmptyLinesAndComments);
18384 // For backwards compability, false / true should still parse
18385 CHECK_PARSE("AlignConsecutiveDeclarations: false",
18386 AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18387 CHECK_PARSE("AlignConsecutiveDeclarations: true",
18388 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18389
18390 Style.PointerAlignment = FormatStyle::PAS_Middle;
18391 CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
18392 FormatStyle::PAS_Left);
18393 CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
18394 FormatStyle::PAS_Right);
18395 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
18396 FormatStyle::PAS_Middle);
18397 Style.ReferenceAlignment = FormatStyle::RAS_Middle;
18398 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
18399 FormatStyle::RAS_Pointer);
18400 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
18401 FormatStyle::RAS_Left);
18402 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
18403 FormatStyle::RAS_Right);
18404 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
18405 FormatStyle::RAS_Middle);
18406 // For backward compatibility:
18407 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
18408 FormatStyle::PAS_Left);
18409 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
18410 FormatStyle::PAS_Right);
18411 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
18412 FormatStyle::PAS_Middle);
18413
18414 Style.Standard = FormatStyle::LS_Auto;
18415 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
18416 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
18417 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
18418 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
18419 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
18420 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
18421 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
18422 // Legacy aliases:
18423 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
18424 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
18425 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
18426 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
18427
18428 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
18429 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
18430 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
18431 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
18432 FormatStyle::BOS_None);
18433 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
18434 FormatStyle::BOS_All);
18435 // For backward compatibility:
18436 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
18437 FormatStyle::BOS_None);
18438 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
18439 FormatStyle::BOS_All);
18440
18441 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
18442 CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
18443 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18444 CHECK_PARSE("BreakConstructorInitializers: AfterColon",
18445 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
18446 CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
18447 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
18448 // For backward compatibility:
18449 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
18450 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18451
18452 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
18453 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
18454 FormatStyle::BILS_AfterComma);
18455 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
18456 FormatStyle::BILS_BeforeComma);
18457 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
18458 FormatStyle::BILS_AfterColon);
18459 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
18460 FormatStyle::BILS_BeforeColon);
18461 // For backward compatibility:
18462 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
18463 FormatStyle::BILS_BeforeComma);
18464
18465 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
18466 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
18467 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
18468 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
18469 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
18470 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
18471 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
18472 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
18473 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
18474
18475 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
18476 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
18477 FormatStyle::BAS_Align);
18478 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
18479 FormatStyle::BAS_DontAlign);
18480 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
18481 FormatStyle::BAS_AlwaysBreak);
18482 // For backward compatibility:
18483 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
18484 FormatStyle::BAS_DontAlign);
18485 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
18486 FormatStyle::BAS_Align);
18487
18488 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
18489 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
18490 FormatStyle::ENAS_DontAlign);
18491 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
18492 FormatStyle::ENAS_Left);
18493 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
18494 FormatStyle::ENAS_Right);
18495 // For backward compatibility:
18496 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
18497 FormatStyle::ENAS_Left);
18498 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
18499 FormatStyle::ENAS_Right);
18500
18501 Style.AlignOperands = FormatStyle::OAS_Align;
18502 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
18503 FormatStyle::OAS_DontAlign);
18504 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
18505 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
18506 FormatStyle::OAS_AlignAfterOperator);
18507 // For backward compatibility:
18508 CHECK_PARSE("AlignOperands: false", AlignOperands,
18509 FormatStyle::OAS_DontAlign);
18510 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
18511
18512 Style.UseTab = FormatStyle::UT_ForIndentation;
18513 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
18514 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
18515 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
18516 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
18517 FormatStyle::UT_ForContinuationAndIndentation);
18518 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
18519 FormatStyle::UT_AlignWithSpaces);
18520 // For backward compatibility:
18521 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
18522 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
18523
18524 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
18525 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
18526 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
18527 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
18528 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
18529 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
18530 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
18531 // For backward compatibility:
18532 CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
18533 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
18534 CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
18535 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
18536
18537 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
18538 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
18539 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
18540 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
18541 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
18542 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
18543 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
18544 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
18545 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
18546 // For backward compatibility:
18547 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
18548 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
18549 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
18550 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
18551
18552 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
18553 CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
18554 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
18555 CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
18556 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
18557 CHECK_PARSE("SpaceAroundPointerQualifiers: After",
18558 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
18559 CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
18560 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
18561
18562 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
18563 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
18564 FormatStyle::SBPO_Never);
18565 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
18566 FormatStyle::SBPO_Always);
18567 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
18568 FormatStyle::SBPO_ControlStatements);
18569 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
18570 SpaceBeforeParens,
18571 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
18572 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
18573 FormatStyle::SBPO_NonEmptyParentheses);
18574 // For backward compatibility:
18575 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
18576 FormatStyle::SBPO_Never);
18577 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
18578 FormatStyle::SBPO_ControlStatements);
18579 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
18580 SpaceBeforeParens,
18581 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
18582
18583 Style.ColumnLimit = 123;
18584 FormatStyle BaseStyle = getLLVMStyle();
18585 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
18586 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
18587
18588 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18589 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
18590 FormatStyle::BS_Attach);
18591 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
18592 FormatStyle::BS_Linux);
18593 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
18594 FormatStyle::BS_Mozilla);
18595 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
18596 FormatStyle::BS_Stroustrup);
18597 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
18598 FormatStyle::BS_Allman);
18599 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
18600 FormatStyle::BS_Whitesmiths);
18601 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
18602 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
18603 FormatStyle::BS_WebKit);
18604 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
18605 FormatStyle::BS_Custom);
18606
18607 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
18608 CHECK_PARSE("BraceWrapping:\n"
18609 " AfterControlStatement: MultiLine",
18610 BraceWrapping.AfterControlStatement,
18611 FormatStyle::BWACS_MultiLine);
18612 CHECK_PARSE("BraceWrapping:\n"
18613 " AfterControlStatement: Always",
18614 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
18615 CHECK_PARSE("BraceWrapping:\n"
18616 " AfterControlStatement: Never",
18617 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
18618 // For backward compatibility:
18619 CHECK_PARSE("BraceWrapping:\n"
18620 " AfterControlStatement: true",
18621 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
18622 CHECK_PARSE("BraceWrapping:\n"
18623 " AfterControlStatement: false",
18624 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
18625
18626 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
18627 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
18628 FormatStyle::RTBS_None);
18629 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
18630 FormatStyle::RTBS_All);
18631 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
18632 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
18633 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
18634 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
18635 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
18636 AlwaysBreakAfterReturnType,
18637 FormatStyle::RTBS_TopLevelDefinitions);
18638
18639 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
18640 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
18641 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
18642 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
18643 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
18644 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
18645 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
18646 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
18647 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
18648 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
18649 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
18650
18651 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
18652 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
18653 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
18654 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
18655 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
18656 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
18657 AlwaysBreakAfterDefinitionReturnType,
18658 FormatStyle::DRTBS_TopLevel);
18659
18660 Style.NamespaceIndentation = FormatStyle::NI_All;
18661 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
18662 FormatStyle::NI_None);
18663 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
18664 FormatStyle::NI_Inner);
18665 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
18666 FormatStyle::NI_All);
18667
18668 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
18669 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
18670 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
18671 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
18672 AllowShortIfStatementsOnASingleLine,
18673 FormatStyle::SIS_WithoutElse);
18674 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
18675 AllowShortIfStatementsOnASingleLine,
18676 FormatStyle::SIS_OnlyFirstIf);
18677 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
18678 AllowShortIfStatementsOnASingleLine,
18679 FormatStyle::SIS_AllIfsAndElse);
18680 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
18681 AllowShortIfStatementsOnASingleLine,
18682 FormatStyle::SIS_OnlyFirstIf);
18683 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
18684 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
18685 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
18686 AllowShortIfStatementsOnASingleLine,
18687 FormatStyle::SIS_WithoutElse);
18688
18689 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
18690 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
18691 FormatStyle::IEBS_AfterExternBlock);
18692 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
18693 FormatStyle::IEBS_Indent);
18694 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
18695 FormatStyle::IEBS_NoIndent);
18696 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
18697 FormatStyle::IEBS_Indent);
18698 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
18699 FormatStyle::IEBS_NoIndent);
18700
18701 Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
18702 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
18703 FormatStyle::BFCS_Both);
18704 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
18705 FormatStyle::BFCS_None);
18706 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
18707 FormatStyle::BFCS_Before);
18708 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
18709 FormatStyle::BFCS_After);
18710
18711 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
18712 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
18713 FormatStyle::SJSIO_After);
18714 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
18715 FormatStyle::SJSIO_Before);
18716
18717 // FIXME: This is required because parsing a configuration simply overwrites
18718 // the first N elements of the list instead of resetting it.
18719 Style.ForEachMacros.clear();
18720 std::vector<std::string> BoostForeach;
18721 BoostForeach.push_back("BOOST_FOREACH");
18722 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
18723 std::vector<std::string> BoostAndQForeach;
18724 BoostAndQForeach.push_back("BOOST_FOREACH");
18725 BoostAndQForeach.push_back("Q_FOREACH");
18726 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
18727 BoostAndQForeach);
18728
18729 Style.IfMacros.clear();
18730 std::vector<std::string> CustomIfs;
18731 CustomIfs.push_back("MYIF");
18732 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
18733
18734 Style.AttributeMacros.clear();
18735 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
18736 std::vector<std::string>{"__capability"});
18737 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
18738 std::vector<std::string>({"attr1", "attr2"}));
18739
18740 Style.StatementAttributeLikeMacros.clear();
18741 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
18742 StatementAttributeLikeMacros,
18743 std::vector<std::string>({"emit", "Q_EMIT"}));
18744
18745 Style.StatementMacros.clear();
18746 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
18747 std::vector<std::string>{"QUNUSED"});
18748 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
18749 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
18750
18751 Style.NamespaceMacros.clear();
18752 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
18753 std::vector<std::string>{"TESTSUITE"});
18754 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
18755 std::vector<std::string>({"TESTSUITE", "SUITE"}));
18756
18757 Style.WhitespaceSensitiveMacros.clear();
18758 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
18759 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
18760 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
18761 WhitespaceSensitiveMacros,
18762 std::vector<std::string>({"STRINGIZE", "ASSERT"}));
18763 Style.WhitespaceSensitiveMacros.clear();
18764 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
18765 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
18766 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
18767 WhitespaceSensitiveMacros,
18768 std::vector<std::string>({"STRINGIZE", "ASSERT"}));
18769
18770 Style.IncludeStyle.IncludeCategories.clear();
18771 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
18772 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
18773 CHECK_PARSE("IncludeCategories:\n"
18774 " - Regex: abc/.*\n"
18775 " Priority: 2\n"
18776 " - Regex: .*\n"
18777 " Priority: 1\n"
18778 " CaseSensitive: true\n",
18779 IncludeStyle.IncludeCategories, ExpectedCategories);
18780 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
18781 "abc$");
18782 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
18783 IncludeStyle.IncludeIsMainSourceRegex, "abc$");
18784
18785 Style.SortIncludes = FormatStyle::SI_Never;
18786 CHECK_PARSE("SortIncludes: true", SortIncludes,
18787 FormatStyle::SI_CaseSensitive);
18788 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
18789 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
18790 FormatStyle::SI_CaseInsensitive);
18791 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
18792 FormatStyle::SI_CaseSensitive);
18793 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
18794
18795 Style.RawStringFormats.clear();
18796 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
18797 {
18798 FormatStyle::LK_TextProto,
18799 {"pb", "proto"},
18800 {"PARSE_TEXT_PROTO"},
18801 /*CanonicalDelimiter=*/"",
18802 "llvm",
18803 },
18804 {
18805 FormatStyle::LK_Cpp,
18806 {"cc", "cpp"},
18807 {"C_CODEBLOCK", "CPPEVAL"},
18808 /*CanonicalDelimiter=*/"cc",
18809 /*BasedOnStyle=*/"",
18810 },
18811 };
18812
18813 CHECK_PARSE("RawStringFormats:\n"
18814 " - Language: TextProto\n"
18815 " Delimiters:\n"
18816 " - 'pb'\n"
18817 " - 'proto'\n"
18818 " EnclosingFunctions:\n"
18819 " - 'PARSE_TEXT_PROTO'\n"
18820 " BasedOnStyle: llvm\n"
18821 " - Language: Cpp\n"
18822 " Delimiters:\n"
18823 " - 'cc'\n"
18824 " - 'cpp'\n"
18825 " EnclosingFunctions:\n"
18826 " - 'C_CODEBLOCK'\n"
18827 " - 'CPPEVAL'\n"
18828 " CanonicalDelimiter: 'cc'",
18829 RawStringFormats, ExpectedRawStringFormats);
18830
18831 CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18832 " Minimum: 0\n"
18833 " Maximum: 0",
18834 SpacesInLineCommentPrefix.Minimum, 0u);
18835 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
18836 Style.SpacesInLineCommentPrefix.Minimum = 1;
18837 CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18838 " Minimum: 2",
18839 SpacesInLineCommentPrefix.Minimum, 0u);
18840 CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18841 " Maximum: -1",
18842 SpacesInLineCommentPrefix.Maximum, -1u);
18843 CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18844 " Minimum: 2",
18845 SpacesInLineCommentPrefix.Minimum, 2u);
18846 CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18847 " Maximum: 1",
18848 SpacesInLineCommentPrefix.Maximum, 1u);
18849 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
18850
18851 Style.SpacesInAngles = FormatStyle::SIAS_Always;
18852 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
18853 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
18854 FormatStyle::SIAS_Always);
18855 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
18856 // For backward compatibility:
18857 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
18858 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
18859 }
18860
TEST_F(FormatTest,ParsesConfigurationWithLanguages)18861 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
18862 FormatStyle Style = {};
18863 Style.Language = FormatStyle::LK_Cpp;
18864 CHECK_PARSE("Language: Cpp\n"
18865 "IndentWidth: 12",
18866 IndentWidth, 12u);
18867 EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
18868 "IndentWidth: 34",
18869 &Style),
18870 ParseError::Unsuitable);
18871 FormatStyle BinPackedTCS = {};
18872 BinPackedTCS.Language = FormatStyle::LK_JavaScript;
18873 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
18874 "InsertTrailingCommas: Wrapped",
18875 &BinPackedTCS),
18876 ParseError::BinPackTrailingCommaConflict);
18877 EXPECT_EQ(12u, Style.IndentWidth);
18878 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
18879 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
18880
18881 Style.Language = FormatStyle::LK_JavaScript;
18882 CHECK_PARSE("Language: JavaScript\n"
18883 "IndentWidth: 12",
18884 IndentWidth, 12u);
18885 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
18886 EXPECT_EQ(parseConfiguration("Language: Cpp\n"
18887 "IndentWidth: 34",
18888 &Style),
18889 ParseError::Unsuitable);
18890 EXPECT_EQ(23u, Style.IndentWidth);
18891 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
18892 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
18893
18894 CHECK_PARSE("BasedOnStyle: LLVM\n"
18895 "IndentWidth: 67",
18896 IndentWidth, 67u);
18897
18898 CHECK_PARSE("---\n"
18899 "Language: JavaScript\n"
18900 "IndentWidth: 12\n"
18901 "---\n"
18902 "Language: Cpp\n"
18903 "IndentWidth: 34\n"
18904 "...\n",
18905 IndentWidth, 12u);
18906
18907 Style.Language = FormatStyle::LK_Cpp;
18908 CHECK_PARSE("---\n"
18909 "Language: JavaScript\n"
18910 "IndentWidth: 12\n"
18911 "---\n"
18912 "Language: Cpp\n"
18913 "IndentWidth: 34\n"
18914 "...\n",
18915 IndentWidth, 34u);
18916 CHECK_PARSE("---\n"
18917 "IndentWidth: 78\n"
18918 "---\n"
18919 "Language: JavaScript\n"
18920 "IndentWidth: 56\n"
18921 "...\n",
18922 IndentWidth, 78u);
18923
18924 Style.ColumnLimit = 123;
18925 Style.IndentWidth = 234;
18926 Style.BreakBeforeBraces = FormatStyle::BS_Linux;
18927 Style.TabWidth = 345;
18928 EXPECT_FALSE(parseConfiguration("---\n"
18929 "IndentWidth: 456\n"
18930 "BreakBeforeBraces: Allman\n"
18931 "---\n"
18932 "Language: JavaScript\n"
18933 "IndentWidth: 111\n"
18934 "TabWidth: 111\n"
18935 "---\n"
18936 "Language: Cpp\n"
18937 "BreakBeforeBraces: Stroustrup\n"
18938 "TabWidth: 789\n"
18939 "...\n",
18940 &Style));
18941 EXPECT_EQ(123u, Style.ColumnLimit);
18942 EXPECT_EQ(456u, Style.IndentWidth);
18943 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
18944 EXPECT_EQ(789u, Style.TabWidth);
18945
18946 EXPECT_EQ(parseConfiguration("---\n"
18947 "Language: JavaScript\n"
18948 "IndentWidth: 56\n"
18949 "---\n"
18950 "IndentWidth: 78\n"
18951 "...\n",
18952 &Style),
18953 ParseError::Error);
18954 EXPECT_EQ(parseConfiguration("---\n"
18955 "Language: JavaScript\n"
18956 "IndentWidth: 56\n"
18957 "---\n"
18958 "Language: JavaScript\n"
18959 "IndentWidth: 78\n"
18960 "...\n",
18961 &Style),
18962 ParseError::Error);
18963
18964 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
18965 }
18966
18967 #undef CHECK_PARSE
18968
TEST_F(FormatTest,UsesLanguageForBasedOnStyle)18969 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
18970 FormatStyle Style = {};
18971 Style.Language = FormatStyle::LK_JavaScript;
18972 Style.BreakBeforeTernaryOperators = true;
18973 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
18974 EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
18975
18976 Style.BreakBeforeTernaryOperators = true;
18977 EXPECT_EQ(0, parseConfiguration("---\n"
18978 "BasedOnStyle: Google\n"
18979 "---\n"
18980 "Language: JavaScript\n"
18981 "IndentWidth: 76\n"
18982 "...\n",
18983 &Style)
18984 .value());
18985 EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
18986 EXPECT_EQ(76u, Style.IndentWidth);
18987 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
18988 }
18989
TEST_F(FormatTest,ConfigurationRoundTripTest)18990 TEST_F(FormatTest, ConfigurationRoundTripTest) {
18991 FormatStyle Style = getLLVMStyle();
18992 std::string YAML = configurationAsText(Style);
18993 FormatStyle ParsedStyle = {};
18994 ParsedStyle.Language = FormatStyle::LK_Cpp;
18995 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
18996 EXPECT_EQ(Style, ParsedStyle);
18997 }
18998
TEST_F(FormatTest,WorksFor8bitEncodings)18999 TEST_F(FormatTest, WorksFor8bitEncodings) {
19000 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19001 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19002 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19003 "\"\xef\xee\xf0\xf3...\"",
19004 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19005 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19006 "\xef\xee\xf0\xf3...\"",
19007 getLLVMStyleWithColumns(12)));
19008 }
19009
TEST_F(FormatTest,HandlesUTF8BOM)19010 TEST_F(FormatTest, HandlesUTF8BOM) {
19011 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19012 EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19013 format("\xef\xbb\xbf#include <iostream>"));
19014 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19015 format("\xef\xbb\xbf\n#include <iostream>"));
19016 }
19017
19018 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19019 #if !defined(_MSC_VER)
19020
TEST_F(FormatTest,CountsUTF8CharactersProperly)19021 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19022 verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19023 getLLVMStyleWithColumns(35));
19024 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19025 getLLVMStyleWithColumns(31));
19026 verifyFormat("// Однажды в студёную зимнюю пору...",
19027 getLLVMStyleWithColumns(36));
19028 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19029 verifyFormat("/* Однажды в студёную зимнюю пору... */",
19030 getLLVMStyleWithColumns(39));
19031 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19032 getLLVMStyleWithColumns(35));
19033 }
19034
TEST_F(FormatTest,SplitsUTF8Strings)19035 TEST_F(FormatTest, SplitsUTF8Strings) {
19036 // Non-printable characters' width is currently considered to be the length in
19037 // bytes in UTF8. The characters can be displayed in very different manner
19038 // (zero-width, single width with a substitution glyph, expanded to their code
19039 // (e.g. "<8d>"), so there's no single correct way to handle them.
19040 EXPECT_EQ("\"aaaaÄ\"\n"
19041 "\"\xc2\x8d\";",
19042 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19043 EXPECT_EQ("\"aaaaaaaÄ\"\n"
19044 "\"\xc2\x8d\";",
19045 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19046 EXPECT_EQ("\"Однажды, в \"\n"
19047 "\"студёную \"\n"
19048 "\"зимнюю \"\n"
19049 "\"пору,\"",
19050 format("\"Однажды, в студёную зимнюю пору,\"",
19051 getLLVMStyleWithColumns(13)));
19052 EXPECT_EQ(
19053 "\"一 二 三 \"\n"
19054 "\"四 五六 \"\n"
19055 "\"七 八 九 \"\n"
19056 "\"十\"",
19057 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19058 EXPECT_EQ("\"一\t\"\n"
19059 "\"二 \t\"\n"
19060 "\"三 四 \"\n"
19061 "\"五\t\"\n"
19062 "\"六 \t\"\n"
19063 "\"七 \"\n"
19064 "\"八九十\tqq\"",
19065 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19066 getLLVMStyleWithColumns(11)));
19067
19068 // UTF8 character in an escape sequence.
19069 EXPECT_EQ("\"aaaaaa\"\n"
19070 "\"\\\xC2\x8D\"",
19071 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19072 }
19073
TEST_F(FormatTest,HandlesDoubleWidthCharsInMultiLineStrings)19074 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19075 EXPECT_EQ("const char *sssss =\n"
19076 " \"一二三四五六七八\\\n"
19077 " 九 十\";",
19078 format("const char *sssss = \"一二三四五六七八\\\n"
19079 " 九 十\";",
19080 getLLVMStyleWithColumns(30)));
19081 }
19082
TEST_F(FormatTest,SplitsUTF8LineComments)19083 TEST_F(FormatTest, SplitsUTF8LineComments) {
19084 EXPECT_EQ("// aaaaÄ\xc2\x8d",
19085 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19086 EXPECT_EQ("// Я из лесу\n"
19087 "// вышел; был\n"
19088 "// сильный\n"
19089 "// мороз.",
19090 format("// Я из лесу вышел; был сильный мороз.",
19091 getLLVMStyleWithColumns(13)));
19092 EXPECT_EQ("// 一二三\n"
19093 "// 四五六七\n"
19094 "// 八 九\n"
19095 "// 十",
19096 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9)));
19097 }
19098
TEST_F(FormatTest,SplitsUTF8BlockComments)19099 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19100 EXPECT_EQ("/* Гляжу,\n"
19101 " * поднимается\n"
19102 " * медленно в\n"
19103 " * гору\n"
19104 " * Лошадка,\n"
19105 " * везущая\n"
19106 " * хворосту\n"
19107 " * воз. */",
19108 format("/* Гляжу, поднимается медленно в гору\n"
19109 " * Лошадка, везущая хворосту воз. */",
19110 getLLVMStyleWithColumns(13)));
19111 EXPECT_EQ(
19112 "/* 一二三\n"
19113 " * 四五六七\n"
19114 " * 八 九\n"
19115 " * 十 */",
19116 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9)));
19117 EXPECT_EQ("/* \n"
19118 " * \n"
19119 " * - */",
19120 format("/* - */", getLLVMStyleWithColumns(12)));
19121 }
19122
19123 #endif // _MSC_VER
19124
TEST_F(FormatTest,ConstructorInitializerIndentWidth)19125 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19126 FormatStyle Style = getLLVMStyle();
19127
19128 Style.ConstructorInitializerIndentWidth = 4;
19129 verifyFormat(
19130 "SomeClass::Constructor()\n"
19131 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19132 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19133 Style);
19134
19135 Style.ConstructorInitializerIndentWidth = 2;
19136 verifyFormat(
19137 "SomeClass::Constructor()\n"
19138 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19139 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19140 Style);
19141
19142 Style.ConstructorInitializerIndentWidth = 0;
19143 verifyFormat(
19144 "SomeClass::Constructor()\n"
19145 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19146 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19147 Style);
19148 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19149 verifyFormat(
19150 "SomeLongTemplateVariableName<\n"
19151 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19152 Style);
19153 verifyFormat("bool smaller = 1 < "
19154 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19155 " "
19156 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19157 Style);
19158
19159 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
19160 verifyFormat("SomeClass::Constructor() :\n"
19161 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
19162 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
19163 Style);
19164 }
19165
TEST_F(FormatTest,BreakConstructorInitializersBeforeComma)19166 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
19167 FormatStyle Style = getLLVMStyle();
19168 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19169 Style.ConstructorInitializerIndentWidth = 4;
19170 verifyFormat("SomeClass::Constructor()\n"
19171 " : a(a)\n"
19172 " , b(b)\n"
19173 " , c(c) {}",
19174 Style);
19175 verifyFormat("SomeClass::Constructor()\n"
19176 " : a(a) {}",
19177 Style);
19178
19179 Style.ColumnLimit = 0;
19180 verifyFormat("SomeClass::Constructor()\n"
19181 " : a(a) {}",
19182 Style);
19183 verifyFormat("SomeClass::Constructor() noexcept\n"
19184 " : a(a) {}",
19185 Style);
19186 verifyFormat("SomeClass::Constructor()\n"
19187 " : a(a)\n"
19188 " , b(b)\n"
19189 " , c(c) {}",
19190 Style);
19191 verifyFormat("SomeClass::Constructor()\n"
19192 " : a(a) {\n"
19193 " foo();\n"
19194 " bar();\n"
19195 "}",
19196 Style);
19197
19198 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19199 verifyFormat("SomeClass::Constructor()\n"
19200 " : a(a)\n"
19201 " , b(b)\n"
19202 " , c(c) {\n}",
19203 Style);
19204 verifyFormat("SomeClass::Constructor()\n"
19205 " : a(a) {\n}",
19206 Style);
19207
19208 Style.ColumnLimit = 80;
19209 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
19210 Style.ConstructorInitializerIndentWidth = 2;
19211 verifyFormat("SomeClass::Constructor()\n"
19212 " : a(a)\n"
19213 " , b(b)\n"
19214 " , c(c) {}",
19215 Style);
19216
19217 Style.ConstructorInitializerIndentWidth = 0;
19218 verifyFormat("SomeClass::Constructor()\n"
19219 ": a(a)\n"
19220 ", b(b)\n"
19221 ", c(c) {}",
19222 Style);
19223
19224 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
19225 Style.ConstructorInitializerIndentWidth = 4;
19226 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
19227 verifyFormat(
19228 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
19229 Style);
19230 verifyFormat(
19231 "SomeClass::Constructor()\n"
19232 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
19233 Style);
19234 Style.ConstructorInitializerIndentWidth = 4;
19235 Style.ColumnLimit = 60;
19236 verifyFormat("SomeClass::Constructor()\n"
19237 " : aaaaaaaa(aaaaaaaa)\n"
19238 " , aaaaaaaa(aaaaaaaa)\n"
19239 " , aaaaaaaa(aaaaaaaa) {}",
19240 Style);
19241 }
19242
TEST_F(FormatTest,Destructors)19243 TEST_F(FormatTest, Destructors) {
19244 verifyFormat("void F(int &i) { i.~int(); }");
19245 verifyFormat("void F(int &i) { i->~int(); }");
19246 }
19247
TEST_F(FormatTest,FormatsWithWebKitStyle)19248 TEST_F(FormatTest, FormatsWithWebKitStyle) {
19249 FormatStyle Style = getWebKitStyle();
19250
19251 // Don't indent in outer namespaces.
19252 verifyFormat("namespace outer {\n"
19253 "int i;\n"
19254 "namespace inner {\n"
19255 " int i;\n"
19256 "} // namespace inner\n"
19257 "} // namespace outer\n"
19258 "namespace other_outer {\n"
19259 "int i;\n"
19260 "}",
19261 Style);
19262
19263 // Don't indent case labels.
19264 verifyFormat("switch (variable) {\n"
19265 "case 1:\n"
19266 "case 2:\n"
19267 " doSomething();\n"
19268 " break;\n"
19269 "default:\n"
19270 " ++variable;\n"
19271 "}",
19272 Style);
19273
19274 // Wrap before binary operators.
19275 EXPECT_EQ("void f()\n"
19276 "{\n"
19277 " if (aaaaaaaaaaaaaaaa\n"
19278 " && bbbbbbbbbbbbbbbbbbbbbbbb\n"
19279 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19280 " return;\n"
19281 "}",
19282 format("void f() {\n"
19283 "if (aaaaaaaaaaaaaaaa\n"
19284 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
19285 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19286 "return;\n"
19287 "}",
19288 Style));
19289
19290 // Allow functions on a single line.
19291 verifyFormat("void f() { return; }", Style);
19292
19293 // Allow empty blocks on a single line and insert a space in empty blocks.
19294 EXPECT_EQ("void f() { }", format("void f() {}", Style));
19295 EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
19296 // However, don't merge non-empty short loops.
19297 EXPECT_EQ("while (true) {\n"
19298 " continue;\n"
19299 "}",
19300 format("while (true) { continue; }", Style));
19301
19302 // Constructor initializers are formatted one per line with the "," on the
19303 // new line.
19304 verifyFormat("Constructor()\n"
19305 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
19306 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
19307 " aaaaaaaaaaaaaa)\n"
19308 " , aaaaaaaaaaaaaaaaaaaaaaa()\n"
19309 "{\n"
19310 "}",
19311 Style);
19312 verifyFormat("SomeClass::Constructor()\n"
19313 " : a(a)\n"
19314 "{\n"
19315 "}",
19316 Style);
19317 EXPECT_EQ("SomeClass::Constructor()\n"
19318 " : a(a)\n"
19319 "{\n"
19320 "}",
19321 format("SomeClass::Constructor():a(a){}", Style));
19322 verifyFormat("SomeClass::Constructor()\n"
19323 " : a(a)\n"
19324 " , b(b)\n"
19325 " , c(c)\n"
19326 "{\n"
19327 "}",
19328 Style);
19329 verifyFormat("SomeClass::Constructor()\n"
19330 " : a(a)\n"
19331 "{\n"
19332 " foo();\n"
19333 " bar();\n"
19334 "}",
19335 Style);
19336
19337 // Access specifiers should be aligned left.
19338 verifyFormat("class C {\n"
19339 "public:\n"
19340 " int i;\n"
19341 "};",
19342 Style);
19343
19344 // Do not align comments.
19345 verifyFormat("int a; // Do not\n"
19346 "double b; // align comments.",
19347 Style);
19348
19349 // Do not align operands.
19350 EXPECT_EQ("ASSERT(aaaa\n"
19351 " || bbbb);",
19352 format("ASSERT ( aaaa\n||bbbb);", Style));
19353
19354 // Accept input's line breaks.
19355 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
19356 " || bbbbbbbbbbbbbbb) {\n"
19357 " i++;\n"
19358 "}",
19359 format("if (aaaaaaaaaaaaaaa\n"
19360 "|| bbbbbbbbbbbbbbb) { i++; }",
19361 Style));
19362 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
19363 " i++;\n"
19364 "}",
19365 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
19366
19367 // Don't automatically break all macro definitions (llvm.org/PR17842).
19368 verifyFormat("#define aNumber 10", Style);
19369 // However, generally keep the line breaks that the user authored.
19370 EXPECT_EQ("#define aNumber \\\n"
19371 " 10",
19372 format("#define aNumber \\\n"
19373 " 10",
19374 Style));
19375
19376 // Keep empty and one-element array literals on a single line.
19377 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
19378 " copyItems:YES];",
19379 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
19380 "copyItems:YES];",
19381 Style));
19382 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
19383 " copyItems:YES];",
19384 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
19385 " copyItems:YES];",
19386 Style));
19387 // FIXME: This does not seem right, there should be more indentation before
19388 // the array literal's entries. Nested blocks have the same problem.
19389 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19390 " @\"a\",\n"
19391 " @\"a\"\n"
19392 "]\n"
19393 " copyItems:YES];",
19394 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19395 " @\"a\",\n"
19396 " @\"a\"\n"
19397 " ]\n"
19398 " copyItems:YES];",
19399 Style));
19400 EXPECT_EQ(
19401 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19402 " copyItems:YES];",
19403 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19404 " copyItems:YES];",
19405 Style));
19406
19407 verifyFormat("[self.a b:c c:d];", Style);
19408 EXPECT_EQ("[self.a b:c\n"
19409 " c:d];",
19410 format("[self.a b:c\n"
19411 "c:d];",
19412 Style));
19413 }
19414
TEST_F(FormatTest,FormatsLambdas)19415 TEST_F(FormatTest, FormatsLambdas) {
19416 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
19417 verifyFormat(
19418 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
19419 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
19420 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
19421 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
19422 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
19423 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
19424 verifyFormat("auto c = [a = [b = 42] {}] {};\n");
19425 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
19426 verifyFormat("int x = f(*+[] {});");
19427 verifyFormat("void f() {\n"
19428 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
19429 "}\n");
19430 verifyFormat("void f() {\n"
19431 " other(x.begin(), //\n"
19432 " x.end(), //\n"
19433 " [&](int, int) { return 1; });\n"
19434 "}\n");
19435 verifyFormat("void f() {\n"
19436 " other.other.other.other.other(\n"
19437 " x.begin(), x.end(),\n"
19438 " [something, rather](int, int, int, int, int, int, int) { "
19439 "return 1; });\n"
19440 "}\n");
19441 verifyFormat(
19442 "void f() {\n"
19443 " other.other.other.other.other(\n"
19444 " x.begin(), x.end(),\n"
19445 " [something, rather](int, int, int, int, int, int, int) {\n"
19446 " //\n"
19447 " });\n"
19448 "}\n");
19449 verifyFormat("SomeFunction([]() { // A cool function...\n"
19450 " return 43;\n"
19451 "});");
19452 EXPECT_EQ("SomeFunction([]() {\n"
19453 "#define A a\n"
19454 " return 43;\n"
19455 "});",
19456 format("SomeFunction([](){\n"
19457 "#define A a\n"
19458 "return 43;\n"
19459 "});"));
19460 verifyFormat("void f() {\n"
19461 " SomeFunction([](decltype(x), A *a) {});\n"
19462 " SomeFunction([](typeof(x), A *a) {});\n"
19463 " SomeFunction([](_Atomic(x), A *a) {});\n"
19464 " SomeFunction([](__underlying_type(x), A *a) {});\n"
19465 "}");
19466 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19467 " [](const aaaaaaaaaa &a) { return a; });");
19468 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
19469 " SomeOtherFunctioooooooooooooooooooooooooon();\n"
19470 "});");
19471 verifyFormat("Constructor()\n"
19472 " : Field([] { // comment\n"
19473 " int i;\n"
19474 " }) {}");
19475 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
19476 " return some_parameter.size();\n"
19477 "};");
19478 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
19479 " [](const string &s) { return s; };");
19480 verifyFormat("int i = aaaaaa ? 1 //\n"
19481 " : [] {\n"
19482 " return 2; //\n"
19483 " }();");
19484 verifyFormat("llvm::errs() << \"number of twos is \"\n"
19485 " << std::count_if(v.begin(), v.end(), [](int x) {\n"
19486 " return x == 2; // force break\n"
19487 " });");
19488 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19489 " [=](int iiiiiiiiiiii) {\n"
19490 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
19491 " aaaaaaaaaaaaaaaaaaaaaaa;\n"
19492 " });",
19493 getLLVMStyleWithColumns(60));
19494
19495 verifyFormat("SomeFunction({[&] {\n"
19496 " // comment\n"
19497 " },\n"
19498 " [&] {\n"
19499 " // comment\n"
19500 " }});");
19501 verifyFormat("SomeFunction({[&] {\n"
19502 " // comment\n"
19503 "}});");
19504 verifyFormat(
19505 "virtual aaaaaaaaaaaaaaaa(\n"
19506 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
19507 " aaaaa aaaaaaaaa);");
19508
19509 // Lambdas with return types.
19510 verifyFormat("int c = []() -> int { return 2; }();\n");
19511 verifyFormat("int c = []() -> int * { return 2; }();\n");
19512 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
19513 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
19514 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
19515 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
19516 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
19517 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
19518 verifyFormat("[a, a]() -> a<1> {};");
19519 verifyFormat("[]() -> foo<5 + 2> { return {}; };");
19520 verifyFormat("[]() -> foo<5 - 2> { return {}; };");
19521 verifyFormat("[]() -> foo<5 / 2> { return {}; };");
19522 verifyFormat("[]() -> foo<5 * 2> { return {}; };");
19523 verifyFormat("[]() -> foo<5 % 2> { return {}; };");
19524 verifyFormat("[]() -> foo<5 << 2> { return {}; };");
19525 verifyFormat("[]() -> foo<!5> { return {}; };");
19526 verifyFormat("[]() -> foo<~5> { return {}; };");
19527 verifyFormat("[]() -> foo<5 | 2> { return {}; };");
19528 verifyFormat("[]() -> foo<5 || 2> { return {}; };");
19529 verifyFormat("[]() -> foo<5 & 2> { return {}; };");
19530 verifyFormat("[]() -> foo<5 && 2> { return {}; };");
19531 verifyFormat("[]() -> foo<5 == 2> { return {}; };");
19532 verifyFormat("[]() -> foo<5 != 2> { return {}; };");
19533 verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
19534 verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
19535 verifyFormat("[]() -> foo<5 < 2> { return {}; };");
19536 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
19537 verifyFormat("namespace bar {\n"
19538 "// broken:\n"
19539 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
19540 "} // namespace bar");
19541 verifyFormat("namespace bar {\n"
19542 "// broken:\n"
19543 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
19544 "} // namespace bar");
19545 verifyFormat("namespace bar {\n"
19546 "// broken:\n"
19547 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
19548 "} // namespace bar");
19549 verifyFormat("namespace bar {\n"
19550 "// broken:\n"
19551 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
19552 "} // namespace bar");
19553 verifyFormat("namespace bar {\n"
19554 "// broken:\n"
19555 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
19556 "} // namespace bar");
19557 verifyFormat("namespace bar {\n"
19558 "// broken:\n"
19559 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
19560 "} // namespace bar");
19561 verifyFormat("namespace bar {\n"
19562 "// broken:\n"
19563 "auto foo{[]() -> foo<!5> { return {}; }};\n"
19564 "} // namespace bar");
19565 verifyFormat("namespace bar {\n"
19566 "// broken:\n"
19567 "auto foo{[]() -> foo<~5> { return {}; }};\n"
19568 "} // namespace bar");
19569 verifyFormat("namespace bar {\n"
19570 "// broken:\n"
19571 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
19572 "} // namespace bar");
19573 verifyFormat("namespace bar {\n"
19574 "// broken:\n"
19575 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
19576 "} // namespace bar");
19577 verifyFormat("namespace bar {\n"
19578 "// broken:\n"
19579 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
19580 "} // namespace bar");
19581 verifyFormat("namespace bar {\n"
19582 "// broken:\n"
19583 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
19584 "} // namespace bar");
19585 verifyFormat("namespace bar {\n"
19586 "// broken:\n"
19587 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
19588 "} // namespace bar");
19589 verifyFormat("namespace bar {\n"
19590 "// broken:\n"
19591 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
19592 "} // namespace bar");
19593 verifyFormat("namespace bar {\n"
19594 "// broken:\n"
19595 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
19596 "} // namespace bar");
19597 verifyFormat("namespace bar {\n"
19598 "// broken:\n"
19599 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
19600 "} // namespace bar");
19601 verifyFormat("namespace bar {\n"
19602 "// broken:\n"
19603 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
19604 "} // namespace bar");
19605 verifyFormat("namespace bar {\n"
19606 "// broken:\n"
19607 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
19608 "} // namespace bar");
19609 verifyFormat("[]() -> a<1> {};");
19610 verifyFormat("[]() -> a<1> { ; };");
19611 verifyFormat("[]() -> a<1> { ; }();");
19612 verifyFormat("[a, a]() -> a<true> {};");
19613 verifyFormat("[]() -> a<true> {};");
19614 verifyFormat("[]() -> a<true> { ; };");
19615 verifyFormat("[]() -> a<true> { ; }();");
19616 verifyFormat("[a, a]() -> a<false> {};");
19617 verifyFormat("[]() -> a<false> {};");
19618 verifyFormat("[]() -> a<false> { ; };");
19619 verifyFormat("[]() -> a<false> { ; }();");
19620 verifyFormat("auto foo{[]() -> foo<false> { ; }};");
19621 verifyFormat("namespace bar {\n"
19622 "auto foo{[]() -> foo<false> { ; }};\n"
19623 "} // namespace bar");
19624 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
19625 " int j) -> int {\n"
19626 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
19627 "};");
19628 verifyFormat(
19629 "aaaaaaaaaaaaaaaaaaaaaa(\n"
19630 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
19631 " return aaaaaaaaaaaaaaaaa;\n"
19632 " });",
19633 getLLVMStyleWithColumns(70));
19634 verifyFormat("[]() //\n"
19635 " -> int {\n"
19636 " return 1; //\n"
19637 "};");
19638 verifyFormat("[]() -> Void<T...> {};");
19639 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
19640
19641 // Lambdas with explicit template argument lists.
19642 verifyFormat(
19643 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
19644
19645 // Multiple lambdas in the same parentheses change indentation rules. These
19646 // lambdas are forced to start on new lines.
19647 verifyFormat("SomeFunction(\n"
19648 " []() {\n"
19649 " //\n"
19650 " },\n"
19651 " []() {\n"
19652 " //\n"
19653 " });");
19654
19655 // A lambda passed as arg0 is always pushed to the next line.
19656 verifyFormat("SomeFunction(\n"
19657 " [this] {\n"
19658 " //\n"
19659 " },\n"
19660 " 1);\n");
19661
19662 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
19663 // the arg0 case above.
19664 auto Style = getGoogleStyle();
19665 Style.BinPackArguments = false;
19666 verifyFormat("SomeFunction(\n"
19667 " a,\n"
19668 " [this] {\n"
19669 " //\n"
19670 " },\n"
19671 " b);\n",
19672 Style);
19673 verifyFormat("SomeFunction(\n"
19674 " a,\n"
19675 " [this] {\n"
19676 " //\n"
19677 " },\n"
19678 " b);\n");
19679
19680 // A lambda with a very long line forces arg0 to be pushed out irrespective of
19681 // the BinPackArguments value (as long as the code is wide enough).
19682 verifyFormat(
19683 "something->SomeFunction(\n"
19684 " a,\n"
19685 " [this] {\n"
19686 " "
19687 "D0000000000000000000000000000000000000000000000000000000000001();\n"
19688 " },\n"
19689 " b);\n");
19690
19691 // A multi-line lambda is pulled up as long as the introducer fits on the
19692 // previous line and there are no further args.
19693 verifyFormat("function(1, [this, that] {\n"
19694 " //\n"
19695 "});\n");
19696 verifyFormat("function([this, that] {\n"
19697 " //\n"
19698 "});\n");
19699 // FIXME: this format is not ideal and we should consider forcing the first
19700 // arg onto its own line.
19701 verifyFormat("function(a, b, c, //\n"
19702 " d, [this, that] {\n"
19703 " //\n"
19704 " });\n");
19705
19706 // Multiple lambdas are treated correctly even when there is a short arg0.
19707 verifyFormat("SomeFunction(\n"
19708 " 1,\n"
19709 " [this] {\n"
19710 " //\n"
19711 " },\n"
19712 " [this] {\n"
19713 " //\n"
19714 " },\n"
19715 " 1);\n");
19716
19717 // More complex introducers.
19718 verifyFormat("return [i, args...] {};");
19719
19720 // Not lambdas.
19721 verifyFormat("constexpr char hello[]{\"hello\"};");
19722 verifyFormat("double &operator[](int i) { return 0; }\n"
19723 "int i;");
19724 verifyFormat("std::unique_ptr<int[]> foo() {}");
19725 verifyFormat("int i = a[a][a]->f();");
19726 verifyFormat("int i = (*b)[a]->f();");
19727
19728 // Other corner cases.
19729 verifyFormat("void f() {\n"
19730 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
19731 " );\n"
19732 "}");
19733
19734 // Lambdas created through weird macros.
19735 verifyFormat("void f() {\n"
19736 " MACRO((const AA &a) { return 1; });\n"
19737 " MACRO((AA &a) { return 1; });\n"
19738 "}");
19739
19740 verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
19741 " doo_dah();\n"
19742 " doo_dah();\n"
19743 " })) {\n"
19744 "}");
19745 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
19746 " doo_dah();\n"
19747 " doo_dah();\n"
19748 " })) {\n"
19749 "}");
19750 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
19751 " doo_dah();\n"
19752 " doo_dah();\n"
19753 " })) {\n"
19754 "}");
19755 verifyFormat("auto lambda = []() {\n"
19756 " int a = 2\n"
19757 "#if A\n"
19758 " + 2\n"
19759 "#endif\n"
19760 " ;\n"
19761 "};");
19762
19763 // Lambdas with complex multiline introducers.
19764 verifyFormat(
19765 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19766 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
19767 " -> ::std::unordered_set<\n"
19768 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
19769 " //\n"
19770 " });");
19771
19772 FormatStyle DoNotMerge = getLLVMStyle();
19773 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
19774 verifyFormat("auto c = []() {\n"
19775 " return b;\n"
19776 "};",
19777 "auto c = []() { return b; };", DoNotMerge);
19778 verifyFormat("auto c = []() {\n"
19779 "};",
19780 " auto c = []() {};", DoNotMerge);
19781
19782 FormatStyle MergeEmptyOnly = getLLVMStyle();
19783 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
19784 verifyFormat("auto c = []() {\n"
19785 " return b;\n"
19786 "};",
19787 "auto c = []() {\n"
19788 " return b;\n"
19789 " };",
19790 MergeEmptyOnly);
19791 verifyFormat("auto c = []() {};",
19792 "auto c = []() {\n"
19793 "};",
19794 MergeEmptyOnly);
19795
19796 FormatStyle MergeInline = getLLVMStyle();
19797 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
19798 verifyFormat("auto c = []() {\n"
19799 " return b;\n"
19800 "};",
19801 "auto c = []() { return b; };", MergeInline);
19802 verifyFormat("function([]() { return b; })", "function([]() { return b; })",
19803 MergeInline);
19804 verifyFormat("function([]() { return b; }, a)",
19805 "function([]() { return b; }, a)", MergeInline);
19806 verifyFormat("function(a, []() { return b; })",
19807 "function(a, []() { return b; })", MergeInline);
19808
19809 // Check option "BraceWrapping.BeforeLambdaBody" and different state of
19810 // AllowShortLambdasOnASingleLine
19811 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
19812 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
19813 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
19814 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19815 FormatStyle::ShortLambdaStyle::SLS_None;
19816 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
19817 " []()\n"
19818 " {\n"
19819 " return 17;\n"
19820 " });",
19821 LLVMWithBeforeLambdaBody);
19822 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
19823 " []()\n"
19824 " {\n"
19825 " });",
19826 LLVMWithBeforeLambdaBody);
19827 verifyFormat("auto fct_SLS_None = []()\n"
19828 "{\n"
19829 " return 17;\n"
19830 "};",
19831 LLVMWithBeforeLambdaBody);
19832 verifyFormat("TwoNestedLambdas_SLS_None(\n"
19833 " []()\n"
19834 " {\n"
19835 " return Call(\n"
19836 " []()\n"
19837 " {\n"
19838 " return 17;\n"
19839 " });\n"
19840 " });",
19841 LLVMWithBeforeLambdaBody);
19842 verifyFormat("void Fct() {\n"
19843 " return {[]()\n"
19844 " {\n"
19845 " return 17;\n"
19846 " }};\n"
19847 "}",
19848 LLVMWithBeforeLambdaBody);
19849
19850 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19851 FormatStyle::ShortLambdaStyle::SLS_Empty;
19852 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
19853 " []()\n"
19854 " {\n"
19855 " return 17;\n"
19856 " });",
19857 LLVMWithBeforeLambdaBody);
19858 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
19859 LLVMWithBeforeLambdaBody);
19860 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
19861 "ongFunctionName_SLS_Empty(\n"
19862 " []() {});",
19863 LLVMWithBeforeLambdaBody);
19864 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
19865 " []()\n"
19866 " {\n"
19867 " return 17;\n"
19868 " });",
19869 LLVMWithBeforeLambdaBody);
19870 verifyFormat("auto fct_SLS_Empty = []()\n"
19871 "{\n"
19872 " return 17;\n"
19873 "};",
19874 LLVMWithBeforeLambdaBody);
19875 verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
19876 " []()\n"
19877 " {\n"
19878 " return Call([]() {});\n"
19879 " });",
19880 LLVMWithBeforeLambdaBody);
19881 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
19882 " []()\n"
19883 " {\n"
19884 " return Call([]() {});\n"
19885 " });",
19886 LLVMWithBeforeLambdaBody);
19887 verifyFormat(
19888 "FctWithLongLineInLambda_SLS_Empty(\n"
19889 " []()\n"
19890 " {\n"
19891 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
19892 " AndShouldNotBeConsiderAsInline,\n"
19893 " LambdaBodyMustBeBreak);\n"
19894 " });",
19895 LLVMWithBeforeLambdaBody);
19896
19897 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19898 FormatStyle::ShortLambdaStyle::SLS_Inline;
19899 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
19900 LLVMWithBeforeLambdaBody);
19901 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
19902 LLVMWithBeforeLambdaBody);
19903 verifyFormat("auto fct_SLS_Inline = []()\n"
19904 "{\n"
19905 " return 17;\n"
19906 "};",
19907 LLVMWithBeforeLambdaBody);
19908 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
19909 "17; }); });",
19910 LLVMWithBeforeLambdaBody);
19911 verifyFormat(
19912 "FctWithLongLineInLambda_SLS_Inline(\n"
19913 " []()\n"
19914 " {\n"
19915 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
19916 " AndShouldNotBeConsiderAsInline,\n"
19917 " LambdaBodyMustBeBreak);\n"
19918 " });",
19919 LLVMWithBeforeLambdaBody);
19920 verifyFormat("FctWithMultipleParams_SLS_Inline("
19921 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
19922 " []() { return 17; });",
19923 LLVMWithBeforeLambdaBody);
19924 verifyFormat(
19925 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
19926 LLVMWithBeforeLambdaBody);
19927
19928 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19929 FormatStyle::ShortLambdaStyle::SLS_All;
19930 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
19931 LLVMWithBeforeLambdaBody);
19932 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
19933 LLVMWithBeforeLambdaBody);
19934 verifyFormat("auto fct_SLS_All = []() { return 17; };",
19935 LLVMWithBeforeLambdaBody);
19936 verifyFormat("FctWithOneParam_SLS_All(\n"
19937 " []()\n"
19938 " {\n"
19939 " // A cool function...\n"
19940 " return 43;\n"
19941 " });",
19942 LLVMWithBeforeLambdaBody);
19943 verifyFormat("FctWithMultipleParams_SLS_All("
19944 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
19945 " []() { return 17; });",
19946 LLVMWithBeforeLambdaBody);
19947 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
19948 LLVMWithBeforeLambdaBody);
19949 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
19950 LLVMWithBeforeLambdaBody);
19951 verifyFormat(
19952 "FctWithLongLineInLambda_SLS_All(\n"
19953 " []()\n"
19954 " {\n"
19955 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
19956 " AndShouldNotBeConsiderAsInline,\n"
19957 " LambdaBodyMustBeBreak);\n"
19958 " });",
19959 LLVMWithBeforeLambdaBody);
19960 verifyFormat(
19961 "auto fct_SLS_All = []()\n"
19962 "{\n"
19963 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
19964 " AndShouldNotBeConsiderAsInline,\n"
19965 " LambdaBodyMustBeBreak);\n"
19966 "};",
19967 LLVMWithBeforeLambdaBody);
19968 LLVMWithBeforeLambdaBody.BinPackParameters = false;
19969 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
19970 LLVMWithBeforeLambdaBody);
19971 verifyFormat(
19972 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
19973 " FirstParam,\n"
19974 " SecondParam,\n"
19975 " ThirdParam,\n"
19976 " FourthParam);",
19977 LLVMWithBeforeLambdaBody);
19978 verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
19979 " []() { return "
19980 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
19981 " FirstParam,\n"
19982 " SecondParam,\n"
19983 " ThirdParam,\n"
19984 " FourthParam);",
19985 LLVMWithBeforeLambdaBody);
19986 verifyFormat(
19987 "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
19988 " SecondParam,\n"
19989 " ThirdParam,\n"
19990 " FourthParam,\n"
19991 " []() { return SomeValueNotSoLong; });",
19992 LLVMWithBeforeLambdaBody);
19993 verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
19994 " []()\n"
19995 " {\n"
19996 " return "
19997 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
19998 "eConsiderAsInline;\n"
19999 " });",
20000 LLVMWithBeforeLambdaBody);
20001 verifyFormat(
20002 "FctWithLongLineInLambda_SLS_All(\n"
20003 " []()\n"
20004 " {\n"
20005 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20006 " AndShouldNotBeConsiderAsInline,\n"
20007 " LambdaBodyMustBeBreak);\n"
20008 " });",
20009 LLVMWithBeforeLambdaBody);
20010 verifyFormat("FctWithTwoParams_SLS_All(\n"
20011 " []()\n"
20012 " {\n"
20013 " // A cool function...\n"
20014 " return 43;\n"
20015 " },\n"
20016 " 87);",
20017 LLVMWithBeforeLambdaBody);
20018 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20019 LLVMWithBeforeLambdaBody);
20020 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20021 LLVMWithBeforeLambdaBody);
20022 verifyFormat(
20023 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20024 LLVMWithBeforeLambdaBody);
20025 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20026 "}); }, x);",
20027 LLVMWithBeforeLambdaBody);
20028 verifyFormat("TwoNestedLambdas_SLS_All(\n"
20029 " []()\n"
20030 " {\n"
20031 " // A cool function...\n"
20032 " return Call([]() { return 17; });\n"
20033 " });",
20034 LLVMWithBeforeLambdaBody);
20035 verifyFormat("TwoNestedLambdas_SLS_All(\n"
20036 " []()\n"
20037 " {\n"
20038 " return Call(\n"
20039 " []()\n"
20040 " {\n"
20041 " // A cool function...\n"
20042 " return 17;\n"
20043 " });\n"
20044 " });",
20045 LLVMWithBeforeLambdaBody);
20046
20047 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20048 FormatStyle::ShortLambdaStyle::SLS_None;
20049
20050 verifyFormat("auto select = [this]() -> const Library::Object *\n"
20051 "{\n"
20052 " return MyAssignment::SelectFromList(this);\n"
20053 "};\n",
20054 LLVMWithBeforeLambdaBody);
20055
20056 verifyFormat("auto select = [this]() -> const Library::Object &\n"
20057 "{\n"
20058 " return MyAssignment::SelectFromList(this);\n"
20059 "};\n",
20060 LLVMWithBeforeLambdaBody);
20061
20062 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
20063 "{\n"
20064 " return MyAssignment::SelectFromList(this);\n"
20065 "};\n",
20066 LLVMWithBeforeLambdaBody);
20067
20068 verifyFormat("namespace test {\n"
20069 "class Test {\n"
20070 "public:\n"
20071 " Test() = default;\n"
20072 "};\n"
20073 "} // namespace test",
20074 LLVMWithBeforeLambdaBody);
20075
20076 // Lambdas with different indentation styles.
20077 Style = getLLVMStyleWithColumns(100);
20078 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20079 " return promise.then(\n"
20080 " [this, &someVariable, someObject = "
20081 "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20082 " return someObject.startAsyncAction().then(\n"
20083 " [this, &someVariable](AsyncActionResult result) "
20084 "mutable { result.processMore(); });\n"
20085 " });\n"
20086 "}\n",
20087 format("SomeResult doSomething(SomeObject promise) {\n"
20088 " return promise.then([this, &someVariable, someObject = "
20089 "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20090 " return someObject.startAsyncAction().then([this, "
20091 "&someVariable](AsyncActionResult result) mutable {\n"
20092 " result.processMore();\n"
20093 " });\n"
20094 " });\n"
20095 "}\n",
20096 Style));
20097 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20098 verifyFormat("test() {\n"
20099 " ([]() -> {\n"
20100 " int b = 32;\n"
20101 " return 3;\n"
20102 " }).foo();\n"
20103 "}",
20104 Style);
20105 verifyFormat("test() {\n"
20106 " []() -> {\n"
20107 " int b = 32;\n"
20108 " return 3;\n"
20109 " }\n"
20110 "}",
20111 Style);
20112 verifyFormat("std::sort(v.begin(), v.end(),\n"
20113 " [](const auto &someLongArgumentName, const auto "
20114 "&someOtherLongArgumentName) {\n"
20115 " return someLongArgumentName.someMemberVariable < "
20116 "someOtherLongArgumentName.someMemberVariable;\n"
20117 "});",
20118 Style);
20119 verifyFormat("test() {\n"
20120 " (\n"
20121 " []() -> {\n"
20122 " int b = 32;\n"
20123 " return 3;\n"
20124 " },\n"
20125 " foo, bar)\n"
20126 " .foo();\n"
20127 "}",
20128 Style);
20129 verifyFormat("test() {\n"
20130 " ([]() -> {\n"
20131 " int b = 32;\n"
20132 " return 3;\n"
20133 " })\n"
20134 " .foo()\n"
20135 " .bar();\n"
20136 "}",
20137 Style);
20138 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20139 " return promise.then(\n"
20140 " [this, &someVariable, someObject = "
20141 "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20142 " return someObject.startAsyncAction().then(\n"
20143 " [this, &someVariable](AsyncActionResult result) mutable { "
20144 "result.processMore(); });\n"
20145 " });\n"
20146 "}\n",
20147 format("SomeResult doSomething(SomeObject promise) {\n"
20148 " return promise.then([this, &someVariable, someObject = "
20149 "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20150 " return someObject.startAsyncAction().then([this, "
20151 "&someVariable](AsyncActionResult result) mutable {\n"
20152 " result.processMore();\n"
20153 " });\n"
20154 " });\n"
20155 "}\n",
20156 Style));
20157 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20158 " return promise.then([this, &someVariable] {\n"
20159 " return someObject.startAsyncAction().then(\n"
20160 " [this, &someVariable](AsyncActionResult result) mutable { "
20161 "result.processMore(); });\n"
20162 " });\n"
20163 "}\n",
20164 format("SomeResult doSomething(SomeObject promise) {\n"
20165 " return promise.then([this, &someVariable] {\n"
20166 " return someObject.startAsyncAction().then([this, "
20167 "&someVariable](AsyncActionResult result) mutable {\n"
20168 " result.processMore();\n"
20169 " });\n"
20170 " });\n"
20171 "}\n",
20172 Style));
20173 Style = getGoogleStyle();
20174 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20175 EXPECT_EQ("#define A \\\n"
20176 " [] { \\\n"
20177 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
20178 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
20179 " }",
20180 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
20181 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
20182 Style));
20183 // TODO: The current formatting has a minor issue that's not worth fixing
20184 // right now whereby the closing brace is indented relative to the signature
20185 // instead of being aligned. This only happens with macros.
20186 }
20187
TEST_F(FormatTest,LambdaWithLineComments)20188 TEST_F(FormatTest, LambdaWithLineComments) {
20189 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20190 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20191 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20192 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20193 FormatStyle::ShortLambdaStyle::SLS_All;
20194
20195 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
20196 verifyFormat("auto k = []() // comment\n"
20197 "{ return; }",
20198 LLVMWithBeforeLambdaBody);
20199 verifyFormat("auto k = []() /* comment */ { return; }",
20200 LLVMWithBeforeLambdaBody);
20201 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
20202 LLVMWithBeforeLambdaBody);
20203 verifyFormat("auto k = []() // X\n"
20204 "{ return; }",
20205 LLVMWithBeforeLambdaBody);
20206 verifyFormat(
20207 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
20208 "{ return; }",
20209 LLVMWithBeforeLambdaBody);
20210 }
20211
TEST_F(FormatTest,EmptyLinesInLambdas)20212 TEST_F(FormatTest, EmptyLinesInLambdas) {
20213 verifyFormat("auto lambda = []() {\n"
20214 " x(); //\n"
20215 "};",
20216 "auto lambda = []() {\n"
20217 "\n"
20218 " x(); //\n"
20219 "\n"
20220 "};");
20221 }
20222
TEST_F(FormatTest,FormatsBlocks)20223 TEST_F(FormatTest, FormatsBlocks) {
20224 FormatStyle ShortBlocks = getLLVMStyle();
20225 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20226 verifyFormat("int (^Block)(int, int);", ShortBlocks);
20227 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
20228 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
20229 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
20230 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
20231 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
20232
20233 verifyFormat("foo(^{ bar(); });", ShortBlocks);
20234 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
20235 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
20236
20237 verifyFormat("[operation setCompletionBlock:^{\n"
20238 " [self onOperationDone];\n"
20239 "}];");
20240 verifyFormat("int i = {[operation setCompletionBlock:^{\n"
20241 " [self onOperationDone];\n"
20242 "}]};");
20243 verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
20244 " f();\n"
20245 "}];");
20246 verifyFormat("int a = [operation block:^int(int *i) {\n"
20247 " return 1;\n"
20248 "}];");
20249 verifyFormat("[myObject doSomethingWith:arg1\n"
20250 " aaa:^int(int *a) {\n"
20251 " return 1;\n"
20252 " }\n"
20253 " bbb:f(a * bbbbbbbb)];");
20254
20255 verifyFormat("[operation setCompletionBlock:^{\n"
20256 " [self.delegate newDataAvailable];\n"
20257 "}];",
20258 getLLVMStyleWithColumns(60));
20259 verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
20260 " NSString *path = [self sessionFilePath];\n"
20261 " if (path) {\n"
20262 " // ...\n"
20263 " }\n"
20264 "});");
20265 verifyFormat("[[SessionService sharedService]\n"
20266 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20267 " if (window) {\n"
20268 " [self windowDidLoad:window];\n"
20269 " } else {\n"
20270 " [self errorLoadingWindow];\n"
20271 " }\n"
20272 " }];");
20273 verifyFormat("void (^largeBlock)(void) = ^{\n"
20274 " // ...\n"
20275 "};\n",
20276 getLLVMStyleWithColumns(40));
20277 verifyFormat("[[SessionService sharedService]\n"
20278 " loadWindowWithCompletionBlock: //\n"
20279 " ^(SessionWindow *window) {\n"
20280 " if (window) {\n"
20281 " [self windowDidLoad:window];\n"
20282 " } else {\n"
20283 " [self errorLoadingWindow];\n"
20284 " }\n"
20285 " }];",
20286 getLLVMStyleWithColumns(60));
20287 verifyFormat("[myObject doSomethingWith:arg1\n"
20288 " firstBlock:^(Foo *a) {\n"
20289 " // ...\n"
20290 " int i;\n"
20291 " }\n"
20292 " secondBlock:^(Bar *b) {\n"
20293 " // ...\n"
20294 " int i;\n"
20295 " }\n"
20296 " thirdBlock:^Foo(Bar *b) {\n"
20297 " // ...\n"
20298 " int i;\n"
20299 " }];");
20300 verifyFormat("[myObject doSomethingWith:arg1\n"
20301 " firstBlock:-1\n"
20302 " secondBlock:^(Bar *b) {\n"
20303 " // ...\n"
20304 " int i;\n"
20305 " }];");
20306
20307 verifyFormat("f(^{\n"
20308 " @autoreleasepool {\n"
20309 " if (a) {\n"
20310 " g();\n"
20311 " }\n"
20312 " }\n"
20313 "});");
20314 verifyFormat("Block b = ^int *(A *a, B *b) {}");
20315 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
20316 "};");
20317
20318 FormatStyle FourIndent = getLLVMStyle();
20319 FourIndent.ObjCBlockIndentWidth = 4;
20320 verifyFormat("[operation setCompletionBlock:^{\n"
20321 " [self onOperationDone];\n"
20322 "}];",
20323 FourIndent);
20324 }
20325
TEST_F(FormatTest,FormatsBlocksWithZeroColumnWidth)20326 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
20327 FormatStyle ZeroColumn = getLLVMStyle();
20328 ZeroColumn.ColumnLimit = 0;
20329
20330 verifyFormat("[[SessionService sharedService] "
20331 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20332 " if (window) {\n"
20333 " [self windowDidLoad:window];\n"
20334 " } else {\n"
20335 " [self errorLoadingWindow];\n"
20336 " }\n"
20337 "}];",
20338 ZeroColumn);
20339 EXPECT_EQ("[[SessionService sharedService]\n"
20340 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20341 " if (window) {\n"
20342 " [self windowDidLoad:window];\n"
20343 " } else {\n"
20344 " [self errorLoadingWindow];\n"
20345 " }\n"
20346 " }];",
20347 format("[[SessionService sharedService]\n"
20348 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20349 " if (window) {\n"
20350 " [self windowDidLoad:window];\n"
20351 " } else {\n"
20352 " [self errorLoadingWindow];\n"
20353 " }\n"
20354 "}];",
20355 ZeroColumn));
20356 verifyFormat("[myObject doSomethingWith:arg1\n"
20357 " firstBlock:^(Foo *a) {\n"
20358 " // ...\n"
20359 " int i;\n"
20360 " }\n"
20361 " secondBlock:^(Bar *b) {\n"
20362 " // ...\n"
20363 " int i;\n"
20364 " }\n"
20365 " thirdBlock:^Foo(Bar *b) {\n"
20366 " // ...\n"
20367 " int i;\n"
20368 " }];",
20369 ZeroColumn);
20370 verifyFormat("f(^{\n"
20371 " @autoreleasepool {\n"
20372 " if (a) {\n"
20373 " g();\n"
20374 " }\n"
20375 " }\n"
20376 "});",
20377 ZeroColumn);
20378 verifyFormat("void (^largeBlock)(void) = ^{\n"
20379 " // ...\n"
20380 "};",
20381 ZeroColumn);
20382
20383 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20384 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
20385 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn));
20386 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
20387 EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
20388 " int i;\n"
20389 "};",
20390 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn));
20391 }
20392
TEST_F(FormatTest,SupportsCRLF)20393 TEST_F(FormatTest, SupportsCRLF) {
20394 EXPECT_EQ("int a;\r\n"
20395 "int b;\r\n"
20396 "int c;\r\n",
20397 format("int a;\r\n"
20398 " int b;\r\n"
20399 " int c;\r\n",
20400 getLLVMStyle()));
20401 EXPECT_EQ("int a;\r\n"
20402 "int b;\r\n"
20403 "int c;\r\n",
20404 format("int a;\r\n"
20405 " int b;\n"
20406 " int c;\r\n",
20407 getLLVMStyle()));
20408 EXPECT_EQ("int a;\n"
20409 "int b;\n"
20410 "int c;\n",
20411 format("int a;\r\n"
20412 " int b;\n"
20413 " int c;\n",
20414 getLLVMStyle()));
20415 EXPECT_EQ("\"aaaaaaa \"\r\n"
20416 "\"bbbbbbb\";\r\n",
20417 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
20418 EXPECT_EQ("#define A \\\r\n"
20419 " b; \\\r\n"
20420 " c; \\\r\n"
20421 " d;\r\n",
20422 format("#define A \\\r\n"
20423 " b; \\\r\n"
20424 " c; d; \r\n",
20425 getGoogleStyle()));
20426
20427 EXPECT_EQ("/*\r\n"
20428 "multi line block comments\r\n"
20429 "should not introduce\r\n"
20430 "an extra carriage return\r\n"
20431 "*/\r\n",
20432 format("/*\r\n"
20433 "multi line block comments\r\n"
20434 "should not introduce\r\n"
20435 "an extra carriage return\r\n"
20436 "*/\r\n"));
20437 EXPECT_EQ("/*\r\n"
20438 "\r\n"
20439 "*/",
20440 format("/*\r\n"
20441 " \r\r\r\n"
20442 "*/"));
20443
20444 FormatStyle style = getLLVMStyle();
20445
20446 style.DeriveLineEnding = true;
20447 style.UseCRLF = false;
20448 EXPECT_EQ("union FooBarBazQux {\n"
20449 " int foo;\n"
20450 " int bar;\n"
20451 " int baz;\n"
20452 "};",
20453 format("union FooBarBazQux {\r\n"
20454 " int foo;\n"
20455 " int bar;\r\n"
20456 " int baz;\n"
20457 "};",
20458 style));
20459 style.UseCRLF = true;
20460 EXPECT_EQ("union FooBarBazQux {\r\n"
20461 " int foo;\r\n"
20462 " int bar;\r\n"
20463 " int baz;\r\n"
20464 "};",
20465 format("union FooBarBazQux {\r\n"
20466 " int foo;\n"
20467 " int bar;\r\n"
20468 " int baz;\n"
20469 "};",
20470 style));
20471
20472 style.DeriveLineEnding = false;
20473 style.UseCRLF = false;
20474 EXPECT_EQ("union FooBarBazQux {\n"
20475 " int foo;\n"
20476 " int bar;\n"
20477 " int baz;\n"
20478 " int qux;\n"
20479 "};",
20480 format("union FooBarBazQux {\r\n"
20481 " int foo;\n"
20482 " int bar;\r\n"
20483 " int baz;\n"
20484 " int qux;\r\n"
20485 "};",
20486 style));
20487 style.UseCRLF = true;
20488 EXPECT_EQ("union FooBarBazQux {\r\n"
20489 " int foo;\r\n"
20490 " int bar;\r\n"
20491 " int baz;\r\n"
20492 " int qux;\r\n"
20493 "};",
20494 format("union FooBarBazQux {\r\n"
20495 " int foo;\n"
20496 " int bar;\r\n"
20497 " int baz;\n"
20498 " int qux;\n"
20499 "};",
20500 style));
20501
20502 style.DeriveLineEnding = true;
20503 style.UseCRLF = false;
20504 EXPECT_EQ("union FooBarBazQux {\r\n"
20505 " int foo;\r\n"
20506 " int bar;\r\n"
20507 " int baz;\r\n"
20508 " int qux;\r\n"
20509 "};",
20510 format("union FooBarBazQux {\r\n"
20511 " int foo;\n"
20512 " int bar;\r\n"
20513 " int baz;\n"
20514 " int qux;\r\n"
20515 "};",
20516 style));
20517 style.UseCRLF = true;
20518 EXPECT_EQ("union FooBarBazQux {\n"
20519 " int foo;\n"
20520 " int bar;\n"
20521 " int baz;\n"
20522 " int qux;\n"
20523 "};",
20524 format("union FooBarBazQux {\r\n"
20525 " int foo;\n"
20526 " int bar;\r\n"
20527 " int baz;\n"
20528 " int qux;\n"
20529 "};",
20530 style));
20531 }
20532
TEST_F(FormatTest,MunchSemicolonAfterBlocks)20533 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
20534 verifyFormat("MY_CLASS(C) {\n"
20535 " int i;\n"
20536 " int j;\n"
20537 "};");
20538 }
20539
TEST_F(FormatTest,ConfigurableContinuationIndentWidth)20540 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
20541 FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
20542 TwoIndent.ContinuationIndentWidth = 2;
20543
20544 EXPECT_EQ("int i =\n"
20545 " longFunction(\n"
20546 " arg);",
20547 format("int i = longFunction(arg);", TwoIndent));
20548
20549 FormatStyle SixIndent = getLLVMStyleWithColumns(20);
20550 SixIndent.ContinuationIndentWidth = 6;
20551
20552 EXPECT_EQ("int i =\n"
20553 " longFunction(\n"
20554 " arg);",
20555 format("int i = longFunction(arg);", SixIndent));
20556 }
20557
TEST_F(FormatTest,WrappedClosingParenthesisIndent)20558 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
20559 FormatStyle Style = getLLVMStyle();
20560 verifyFormat("int Foo::getter(\n"
20561 " //\n"
20562 ") const {\n"
20563 " return foo;\n"
20564 "}",
20565 Style);
20566 verifyFormat("void Foo::setter(\n"
20567 " //\n"
20568 ") {\n"
20569 " foo = 1;\n"
20570 "}",
20571 Style);
20572 }
20573
TEST_F(FormatTest,SpacesInAngles)20574 TEST_F(FormatTest, SpacesInAngles) {
20575 FormatStyle Spaces = getLLVMStyle();
20576 Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20577
20578 verifyFormat("vector< ::std::string > x1;", Spaces);
20579 verifyFormat("Foo< int, Bar > x2;", Spaces);
20580 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
20581
20582 verifyFormat("static_cast< int >(arg);", Spaces);
20583 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
20584 verifyFormat("f< int, float >();", Spaces);
20585 verifyFormat("template <> g() {}", Spaces);
20586 verifyFormat("template < std::vector< int > > f() {}", Spaces);
20587 verifyFormat("std::function< void(int, int) > fct;", Spaces);
20588 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
20589 Spaces);
20590
20591 Spaces.Standard = FormatStyle::LS_Cpp03;
20592 Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20593 verifyFormat("A< A< int > >();", Spaces);
20594
20595 Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
20596 verifyFormat("A<A<int> >();", Spaces);
20597
20598 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
20599 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
20600 Spaces);
20601 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
20602 Spaces);
20603
20604 verifyFormat("A<A<int> >();", Spaces);
20605 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
20606 verifyFormat("A< A< int > >();", Spaces);
20607
20608 Spaces.Standard = FormatStyle::LS_Cpp11;
20609 Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20610 verifyFormat("A< A< int > >();", Spaces);
20611
20612 Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
20613 verifyFormat("vector<::std::string> x4;", Spaces);
20614 verifyFormat("vector<int> x5;", Spaces);
20615 verifyFormat("Foo<int, Bar> x6;", Spaces);
20616 verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
20617
20618 verifyFormat("A<A<int>>();", Spaces);
20619
20620 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
20621 verifyFormat("vector<::std::string> x4;", Spaces);
20622 verifyFormat("vector< ::std::string > x4;", Spaces);
20623 verifyFormat("vector<int> x5;", Spaces);
20624 verifyFormat("vector< int > x5;", Spaces);
20625 verifyFormat("Foo<int, Bar> x6;", Spaces);
20626 verifyFormat("Foo< int, Bar > x6;", Spaces);
20627 verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
20628 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
20629
20630 verifyFormat("A<A<int>>();", Spaces);
20631 verifyFormat("A< A< int > >();", Spaces);
20632 verifyFormat("A<A<int > >();", Spaces);
20633 verifyFormat("A< A< int>>();", Spaces);
20634 }
20635
TEST_F(FormatTest,SpaceAfterTemplateKeyword)20636 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
20637 FormatStyle Style = getLLVMStyle();
20638 Style.SpaceAfterTemplateKeyword = false;
20639 verifyFormat("template<int> void foo();", Style);
20640 }
20641
TEST_F(FormatTest,TripleAngleBrackets)20642 TEST_F(FormatTest, TripleAngleBrackets) {
20643 verifyFormat("f<<<1, 1>>>();");
20644 verifyFormat("f<<<1, 1, 1, s>>>();");
20645 verifyFormat("f<<<a, b, c, d>>>();");
20646 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
20647 verifyFormat("f<param><<<1, 1>>>();");
20648 verifyFormat("f<1><<<1, 1>>>();");
20649 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
20650 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20651 "aaaaaaaaaaa<<<\n 1, 1>>>();");
20652 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
20653 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
20654 }
20655
TEST_F(FormatTest,MergeLessLessAtEnd)20656 TEST_F(FormatTest, MergeLessLessAtEnd) {
20657 verifyFormat("<<");
20658 EXPECT_EQ("< < <", format("\\\n<<<"));
20659 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20660 "aaallvm::outs() <<");
20661 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20662 "aaaallvm::outs()\n <<");
20663 }
20664
TEST_F(FormatTest,HandleUnbalancedImplicitBracesAcrossPPBranches)20665 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
20666 std::string code = "#if A\n"
20667 "#if B\n"
20668 "a.\n"
20669 "#endif\n"
20670 " a = 1;\n"
20671 "#else\n"
20672 "#endif\n"
20673 "#if C\n"
20674 "#else\n"
20675 "#endif\n";
20676 EXPECT_EQ(code, format(code));
20677 }
20678
TEST_F(FormatTest,HandleConflictMarkers)20679 TEST_F(FormatTest, HandleConflictMarkers) {
20680 // Git/SVN conflict markers.
20681 EXPECT_EQ("int a;\n"
20682 "void f() {\n"
20683 " callme(some(parameter1,\n"
20684 "<<<<<<< text by the vcs\n"
20685 " parameter2),\n"
20686 "||||||| text by the vcs\n"
20687 " parameter2),\n"
20688 " parameter3,\n"
20689 "======= text by the vcs\n"
20690 " parameter2, parameter3),\n"
20691 ">>>>>>> text by the vcs\n"
20692 " otherparameter);\n",
20693 format("int a;\n"
20694 "void f() {\n"
20695 " callme(some(parameter1,\n"
20696 "<<<<<<< text by the vcs\n"
20697 " parameter2),\n"
20698 "||||||| text by the vcs\n"
20699 " parameter2),\n"
20700 " parameter3,\n"
20701 "======= text by the vcs\n"
20702 " parameter2,\n"
20703 " parameter3),\n"
20704 ">>>>>>> text by the vcs\n"
20705 " otherparameter);\n"));
20706
20707 // Perforce markers.
20708 EXPECT_EQ("void f() {\n"
20709 " function(\n"
20710 ">>>> text by the vcs\n"
20711 " parameter,\n"
20712 "==== text by the vcs\n"
20713 " parameter,\n"
20714 "==== text by the vcs\n"
20715 " parameter,\n"
20716 "<<<< text by the vcs\n"
20717 " parameter);\n",
20718 format("void f() {\n"
20719 " function(\n"
20720 ">>>> text by the vcs\n"
20721 " parameter,\n"
20722 "==== text by the vcs\n"
20723 " parameter,\n"
20724 "==== text by the vcs\n"
20725 " parameter,\n"
20726 "<<<< text by the vcs\n"
20727 " parameter);\n"));
20728
20729 EXPECT_EQ("<<<<<<<\n"
20730 "|||||||\n"
20731 "=======\n"
20732 ">>>>>>>",
20733 format("<<<<<<<\n"
20734 "|||||||\n"
20735 "=======\n"
20736 ">>>>>>>"));
20737
20738 EXPECT_EQ("<<<<<<<\n"
20739 "|||||||\n"
20740 "int i;\n"
20741 "=======\n"
20742 ">>>>>>>",
20743 format("<<<<<<<\n"
20744 "|||||||\n"
20745 "int i;\n"
20746 "=======\n"
20747 ">>>>>>>"));
20748
20749 // FIXME: Handle parsing of macros around conflict markers correctly:
20750 EXPECT_EQ("#define Macro \\\n"
20751 "<<<<<<<\n"
20752 "Something \\\n"
20753 "|||||||\n"
20754 "Else \\\n"
20755 "=======\n"
20756 "Other \\\n"
20757 ">>>>>>>\n"
20758 " End int i;\n",
20759 format("#define Macro \\\n"
20760 "<<<<<<<\n"
20761 " Something \\\n"
20762 "|||||||\n"
20763 " Else \\\n"
20764 "=======\n"
20765 " Other \\\n"
20766 ">>>>>>>\n"
20767 " End\n"
20768 "int i;\n"));
20769 }
20770
TEST_F(FormatTest,DisableRegions)20771 TEST_F(FormatTest, DisableRegions) {
20772 EXPECT_EQ("int i;\n"
20773 "// clang-format off\n"
20774 " int j;\n"
20775 "// clang-format on\n"
20776 "int k;",
20777 format(" int i;\n"
20778 " // clang-format off\n"
20779 " int j;\n"
20780 " // clang-format on\n"
20781 " int k;"));
20782 EXPECT_EQ("int i;\n"
20783 "/* clang-format off */\n"
20784 " int j;\n"
20785 "/* clang-format on */\n"
20786 "int k;",
20787 format(" int i;\n"
20788 " /* clang-format off */\n"
20789 " int j;\n"
20790 " /* clang-format on */\n"
20791 " int k;"));
20792
20793 // Don't reflow comments within disabled regions.
20794 EXPECT_EQ("// clang-format off\n"
20795 "// long long long long long long line\n"
20796 "/* clang-format on */\n"
20797 "/* long long long\n"
20798 " * long long long\n"
20799 " * line */\n"
20800 "int i;\n"
20801 "/* clang-format off */\n"
20802 "/* long long long long long long line */\n",
20803 format("// clang-format off\n"
20804 "// long long long long long long line\n"
20805 "/* clang-format on */\n"
20806 "/* long long long long long long line */\n"
20807 "int i;\n"
20808 "/* clang-format off */\n"
20809 "/* long long long long long long line */\n",
20810 getLLVMStyleWithColumns(20)));
20811 }
20812
TEST_F(FormatTest,DoNotCrashOnInvalidInput)20813 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
20814 format("? ) =");
20815 verifyNoCrash("#define a\\\n /**/}");
20816 }
20817
TEST_F(FormatTest,FormatsTableGenCode)20818 TEST_F(FormatTest, FormatsTableGenCode) {
20819 FormatStyle Style = getLLVMStyle();
20820 Style.Language = FormatStyle::LK_TableGen;
20821 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
20822 }
20823
TEST_F(FormatTest,ArrayOfTemplates)20824 TEST_F(FormatTest, ArrayOfTemplates) {
20825 EXPECT_EQ("auto a = new unique_ptr<int>[10];",
20826 format("auto a = new unique_ptr<int > [ 10];"));
20827
20828 FormatStyle Spaces = getLLVMStyle();
20829 Spaces.SpacesInSquareBrackets = true;
20830 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
20831 format("auto a = new unique_ptr<int > [10];", Spaces));
20832 }
20833
TEST_F(FormatTest,ArrayAsTemplateType)20834 TEST_F(FormatTest, ArrayAsTemplateType) {
20835 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
20836 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
20837
20838 FormatStyle Spaces = getLLVMStyle();
20839 Spaces.SpacesInSquareBrackets = true;
20840 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
20841 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
20842 }
20843
TEST_F(FormatTest,NoSpaceAfterSuper)20844 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
20845
TEST(FormatStyle,GetStyleWithEmptyFileName)20846 TEST(FormatStyle, GetStyleWithEmptyFileName) {
20847 llvm::vfs::InMemoryFileSystem FS;
20848 auto Style1 = getStyle("file", "", "Google", "", &FS);
20849 ASSERT_TRUE((bool)Style1);
20850 ASSERT_EQ(*Style1, getGoogleStyle());
20851 }
20852
TEST(FormatStyle,GetStyleOfFile)20853 TEST(FormatStyle, GetStyleOfFile) {
20854 llvm::vfs::InMemoryFileSystem FS;
20855 // Test 1: format file in the same directory.
20856 ASSERT_TRUE(
20857 FS.addFile("/a/.clang-format", 0,
20858 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
20859 ASSERT_TRUE(
20860 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20861 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
20862 ASSERT_TRUE((bool)Style1);
20863 ASSERT_EQ(*Style1, getLLVMStyle());
20864
20865 // Test 2.1: fallback to default.
20866 ASSERT_TRUE(
20867 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20868 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
20869 ASSERT_TRUE((bool)Style2);
20870 ASSERT_EQ(*Style2, getMozillaStyle());
20871
20872 // Test 2.2: no format on 'none' fallback style.
20873 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
20874 ASSERT_TRUE((bool)Style2);
20875 ASSERT_EQ(*Style2, getNoStyle());
20876
20877 // Test 2.3: format if config is found with no based style while fallback is
20878 // 'none'.
20879 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
20880 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
20881 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
20882 ASSERT_TRUE((bool)Style2);
20883 ASSERT_EQ(*Style2, getLLVMStyle());
20884
20885 // Test 2.4: format if yaml with no based style, while fallback is 'none'.
20886 Style2 = getStyle("{}", "a.h", "none", "", &FS);
20887 ASSERT_TRUE((bool)Style2);
20888 ASSERT_EQ(*Style2, getLLVMStyle());
20889
20890 // Test 3: format file in parent directory.
20891 ASSERT_TRUE(
20892 FS.addFile("/c/.clang-format", 0,
20893 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
20894 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
20895 llvm::MemoryBuffer::getMemBuffer("int i;")));
20896 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
20897 ASSERT_TRUE((bool)Style3);
20898 ASSERT_EQ(*Style3, getGoogleStyle());
20899
20900 // Test 4: error on invalid fallback style
20901 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
20902 ASSERT_FALSE((bool)Style4);
20903 llvm::consumeError(Style4.takeError());
20904
20905 // Test 5: error on invalid yaml on command line
20906 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
20907 ASSERT_FALSE((bool)Style5);
20908 llvm::consumeError(Style5.takeError());
20909
20910 // Test 6: error on invalid style
20911 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
20912 ASSERT_FALSE((bool)Style6);
20913 llvm::consumeError(Style6.takeError());
20914
20915 // Test 7: found config file, error on parsing it
20916 ASSERT_TRUE(
20917 FS.addFile("/d/.clang-format", 0,
20918 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
20919 "InvalidKey: InvalidValue")));
20920 ASSERT_TRUE(
20921 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20922 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
20923 ASSERT_FALSE((bool)Style7a);
20924 llvm::consumeError(Style7a.takeError());
20925
20926 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
20927 ASSERT_TRUE((bool)Style7b);
20928
20929 // Test 8: inferred per-language defaults apply.
20930 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
20931 ASSERT_TRUE((bool)StyleTd);
20932 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
20933
20934 // Test 9.1: overwriting a file style, when parent no file exists with no
20935 // fallback style
20936 ASSERT_TRUE(FS.addFile(
20937 "/e/sub/.clang-format", 0,
20938 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
20939 "ColumnLimit: 20")));
20940 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
20941 llvm::MemoryBuffer::getMemBuffer("int i;")));
20942 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
20943 ASSERT_TRUE(static_cast<bool>(Style9));
20944 ASSERT_EQ(*Style9, [] {
20945 auto Style = getNoStyle();
20946 Style.ColumnLimit = 20;
20947 return Style;
20948 }());
20949
20950 // Test 9.2: with LLVM fallback style
20951 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
20952 ASSERT_TRUE(static_cast<bool>(Style9));
20953 ASSERT_EQ(*Style9, [] {
20954 auto Style = getLLVMStyle();
20955 Style.ColumnLimit = 20;
20956 return Style;
20957 }());
20958
20959 // Test 9.3: with a parent file
20960 ASSERT_TRUE(
20961 FS.addFile("/e/.clang-format", 0,
20962 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
20963 "UseTab: Always")));
20964 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
20965 ASSERT_TRUE(static_cast<bool>(Style9));
20966 ASSERT_EQ(*Style9, [] {
20967 auto Style = getGoogleStyle();
20968 Style.ColumnLimit = 20;
20969 Style.UseTab = FormatStyle::UT_Always;
20970 return Style;
20971 }());
20972
20973 // Test 9.4: propagate more than one level
20974 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
20975 llvm::MemoryBuffer::getMemBuffer("int i;")));
20976 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
20977 llvm::MemoryBuffer::getMemBuffer(
20978 "BasedOnStyle: InheritParentConfig\n"
20979 "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
20980 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
20981
20982 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
20983 auto Style = getGoogleStyle();
20984 Style.ColumnLimit = 20;
20985 Style.UseTab = FormatStyle::UT_Always;
20986 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
20987 return Style;
20988 }();
20989
20990 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
20991 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
20992 ASSERT_TRUE(static_cast<bool>(Style9));
20993 ASSERT_EQ(*Style9, SubSubStyle);
20994
20995 // Test 9.5: use InheritParentConfig as style name
20996 Style9 =
20997 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
20998 ASSERT_TRUE(static_cast<bool>(Style9));
20999 ASSERT_EQ(*Style9, SubSubStyle);
21000
21001 // Test 9.6: use command line style with inheritance
21002 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21003 "none", "", &FS);
21004 ASSERT_TRUE(static_cast<bool>(Style9));
21005 ASSERT_EQ(*Style9, SubSubStyle);
21006
21007 // Test 9.7: use command line style with inheritance and own config
21008 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21009 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21010 "/e/sub/code.cpp", "none", "", &FS);
21011 ASSERT_TRUE(static_cast<bool>(Style9));
21012 ASSERT_EQ(*Style9, SubSubStyle);
21013
21014 // Test 9.8: use inheritance from a file without BasedOnStyle
21015 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21016 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21017 ASSERT_TRUE(
21018 FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21019 llvm::MemoryBuffer::getMemBuffer(
21020 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21021 // Make sure we do not use the fallback style
21022 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
21023 ASSERT_TRUE(static_cast<bool>(Style9));
21024 ASSERT_EQ(*Style9, [] {
21025 auto Style = getLLVMStyle();
21026 Style.ColumnLimit = 123;
21027 return Style;
21028 }());
21029
21030 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
21031 ASSERT_TRUE(static_cast<bool>(Style9));
21032 ASSERT_EQ(*Style9, [] {
21033 auto Style = getLLVMStyle();
21034 Style.ColumnLimit = 123;
21035 Style.IndentWidth = 7;
21036 return Style;
21037 }());
21038 }
21039
TEST_F(ReplacementTest,FormatCodeAfterReplacements)21040 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
21041 // Column limit is 20.
21042 std::string Code = "Type *a =\n"
21043 " new Type();\n"
21044 "g(iiiii, 0, jjjjj,\n"
21045 " 0, kkkkk, 0, mm);\n"
21046 "int bad = format ;";
21047 std::string Expected = "auto a = new Type();\n"
21048 "g(iiiii, nullptr,\n"
21049 " jjjjj, nullptr,\n"
21050 " kkkkk, nullptr,\n"
21051 " mm);\n"
21052 "int bad = format ;";
21053 FileID ID = Context.createInMemoryFile("format.cpp", Code);
21054 tooling::Replacements Replaces = toReplacements(
21055 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
21056 "auto "),
21057 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
21058 "nullptr"),
21059 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
21060 "nullptr"),
21061 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
21062 "nullptr")});
21063
21064 format::FormatStyle Style = format::getLLVMStyle();
21065 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
21066 auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21067 EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21068 << llvm::toString(FormattedReplaces.takeError()) << "\n";
21069 auto Result = applyAllReplacements(Code, *FormattedReplaces);
21070 EXPECT_TRUE(static_cast<bool>(Result));
21071 EXPECT_EQ(Expected, *Result);
21072 }
21073
TEST_F(ReplacementTest,SortIncludesAfterReplacement)21074 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
21075 std::string Code = "#include \"a.h\"\n"
21076 "#include \"c.h\"\n"
21077 "\n"
21078 "int main() {\n"
21079 " return 0;\n"
21080 "}";
21081 std::string Expected = "#include \"a.h\"\n"
21082 "#include \"b.h\"\n"
21083 "#include \"c.h\"\n"
21084 "\n"
21085 "int main() {\n"
21086 " return 0;\n"
21087 "}";
21088 FileID ID = Context.createInMemoryFile("fix.cpp", Code);
21089 tooling::Replacements Replaces = toReplacements(
21090 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
21091 "#include \"b.h\"\n")});
21092
21093 format::FormatStyle Style = format::getLLVMStyle();
21094 Style.SortIncludes = FormatStyle::SI_CaseSensitive;
21095 auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21096 EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21097 << llvm::toString(FormattedReplaces.takeError()) << "\n";
21098 auto Result = applyAllReplacements(Code, *FormattedReplaces);
21099 EXPECT_TRUE(static_cast<bool>(Result));
21100 EXPECT_EQ(Expected, *Result);
21101 }
21102
TEST_F(FormatTest,FormatSortsUsingDeclarations)21103 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
21104 EXPECT_EQ("using std::cin;\n"
21105 "using std::cout;",
21106 format("using std::cout;\n"
21107 "using std::cin;",
21108 getGoogleStyle()));
21109 }
21110
TEST_F(FormatTest,UTF8CharacterLiteralCpp03)21111 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
21112 format::FormatStyle Style = format::getLLVMStyle();
21113 Style.Standard = FormatStyle::LS_Cpp03;
21114 // cpp03 recognize this string as identifier u8 and literal character 'a'
21115 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
21116 }
21117
TEST_F(FormatTest,UTF8CharacterLiteralCpp11)21118 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
21119 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
21120 // all modes, including C++11, C++14 and C++17
21121 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
21122 }
21123
TEST_F(FormatTest,DoNotFormatLikelyXml)21124 TEST_F(FormatTest, DoNotFormatLikelyXml) {
21125 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
21126 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
21127 }
21128
TEST_F(FormatTest,StructuredBindings)21129 TEST_F(FormatTest, StructuredBindings) {
21130 // Structured bindings is a C++17 feature.
21131 // all modes, including C++11, C++14 and C++17
21132 verifyFormat("auto [a, b] = f();");
21133 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
21134 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();"));
21135 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();"));
21136 EXPECT_EQ("auto const volatile [a, b] = f();",
21137 format("auto const volatile[a, b] = f();"));
21138 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();"));
21139 EXPECT_EQ("auto &[a, b, c] = f();",
21140 format("auto &[ a , b,c ] = f();"));
21141 EXPECT_EQ("auto &&[a, b, c] = f();",
21142 format("auto &&[ a , b,c ] = f();"));
21143 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();"));
21144 EXPECT_EQ("auto const volatile &&[a, b] = f();",
21145 format("auto const volatile &&[a, b] = f();"));
21146 EXPECT_EQ("auto const &&[a, b] = f();",
21147 format("auto const && [a, b] = f();"));
21148 EXPECT_EQ("const auto &[a, b] = f();",
21149 format("const auto & [a, b] = f();"));
21150 EXPECT_EQ("const auto volatile &&[a, b] = f();",
21151 format("const auto volatile &&[a, b] = f();"));
21152 EXPECT_EQ("volatile const auto &&[a, b] = f();",
21153 format("volatile const auto &&[a, b] = f();"));
21154 EXPECT_EQ("const auto &&[a, b] = f();",
21155 format("const auto && [a, b] = f();"));
21156
21157 // Make sure we don't mistake structured bindings for lambdas.
21158 FormatStyle PointerMiddle = getLLVMStyle();
21159 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
21160 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
21161 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
21162 verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
21163 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
21164 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
21165 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
21166 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
21167 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
21168 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
21169 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
21170 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
21171 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
21172
21173 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
21174 format("for (const auto && [a, b] : some_range) {\n}"));
21175 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
21176 format("for (const auto & [a, b] : some_range) {\n}"));
21177 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
21178 format("for (const auto[a, b] : some_range) {\n}"));
21179 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);"));
21180 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);"));
21181 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);"));
21182 EXPECT_EQ("auto const &[x, y](expr);",
21183 format("auto const & [x,y] (expr);"));
21184 EXPECT_EQ("auto const &&[x, y](expr);",
21185 format("auto const && [x,y] (expr);"));
21186 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};"));
21187 EXPECT_EQ("auto const &[x, y]{expr};",
21188 format("auto const & [x,y] {expr};"));
21189 EXPECT_EQ("auto const &&[x, y]{expr};",
21190 format("auto const && [x,y] {expr};"));
21191
21192 format::FormatStyle Spaces = format::getLLVMStyle();
21193 Spaces.SpacesInSquareBrackets = true;
21194 verifyFormat("auto [ a, b ] = f();", Spaces);
21195 verifyFormat("auto &&[ a, b ] = f();", Spaces);
21196 verifyFormat("auto &[ a, b ] = f();", Spaces);
21197 verifyFormat("auto const &&[ a, b ] = f();", Spaces);
21198 verifyFormat("auto const &[ a, b ] = f();", Spaces);
21199 }
21200
TEST_F(FormatTest,FileAndCode)21201 TEST_F(FormatTest, FileAndCode) {
21202 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
21203 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
21204 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
21205 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
21206 EXPECT_EQ(FormatStyle::LK_ObjC,
21207 guessLanguage("foo.h", "@interface Foo\n@end\n"));
21208 EXPECT_EQ(
21209 FormatStyle::LK_ObjC,
21210 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
21211 EXPECT_EQ(FormatStyle::LK_ObjC,
21212 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
21213 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
21214 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
21215 EXPECT_EQ(FormatStyle::LK_ObjC,
21216 guessLanguage("foo", "@interface Foo\n@end\n"));
21217 EXPECT_EQ(FormatStyle::LK_ObjC,
21218 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
21219 EXPECT_EQ(
21220 FormatStyle::LK_ObjC,
21221 guessLanguage("foo.h",
21222 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
21223 EXPECT_EQ(
21224 FormatStyle::LK_Cpp,
21225 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
21226 }
21227
TEST_F(FormatTest,GuessLanguageWithCpp11AttributeSpecifiers)21228 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
21229 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
21230 EXPECT_EQ(FormatStyle::LK_ObjC,
21231 guessLanguage("foo.h", "array[[calculator getIndex]];"));
21232 EXPECT_EQ(FormatStyle::LK_Cpp,
21233 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
21234 EXPECT_EQ(
21235 FormatStyle::LK_Cpp,
21236 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
21237 EXPECT_EQ(FormatStyle::LK_ObjC,
21238 guessLanguage("foo.h", "[[noreturn foo] bar];"));
21239 EXPECT_EQ(FormatStyle::LK_Cpp,
21240 guessLanguage("foo.h", "[[clang::fallthrough]];"));
21241 EXPECT_EQ(FormatStyle::LK_ObjC,
21242 guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
21243 EXPECT_EQ(FormatStyle::LK_Cpp,
21244 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
21245 EXPECT_EQ(FormatStyle::LK_Cpp,
21246 guessLanguage("foo.h", "[[using clang: fallthrough]];"));
21247 EXPECT_EQ(FormatStyle::LK_ObjC,
21248 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
21249 EXPECT_EQ(FormatStyle::LK_Cpp,
21250 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
21251 EXPECT_EQ(
21252 FormatStyle::LK_Cpp,
21253 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
21254 EXPECT_EQ(
21255 FormatStyle::LK_Cpp,
21256 guessLanguage("foo.h",
21257 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
21258 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
21259 }
21260
TEST_F(FormatTest,GuessLanguageWithCaret)21261 TEST_F(FormatTest, GuessLanguageWithCaret) {
21262 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
21263 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
21264 EXPECT_EQ(FormatStyle::LK_ObjC,
21265 guessLanguage("foo.h", "int(^)(char, float);"));
21266 EXPECT_EQ(FormatStyle::LK_ObjC,
21267 guessLanguage("foo.h", "int(^foo)(char, float);"));
21268 EXPECT_EQ(FormatStyle::LK_ObjC,
21269 guessLanguage("foo.h", "int(^foo[10])(char, float);"));
21270 EXPECT_EQ(FormatStyle::LK_ObjC,
21271 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
21272 EXPECT_EQ(
21273 FormatStyle::LK_ObjC,
21274 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
21275 }
21276
TEST_F(FormatTest,GuessLanguageWithPragmas)21277 TEST_F(FormatTest, GuessLanguageWithPragmas) {
21278 EXPECT_EQ(FormatStyle::LK_Cpp,
21279 guessLanguage("foo.h", "__pragma(warning(disable:))"));
21280 EXPECT_EQ(FormatStyle::LK_Cpp,
21281 guessLanguage("foo.h", "#pragma(warning(disable:))"));
21282 EXPECT_EQ(FormatStyle::LK_Cpp,
21283 guessLanguage("foo.h", "_Pragma(warning(disable:))"));
21284 }
21285
TEST_F(FormatTest,FormatsInlineAsmSymbolicNames)21286 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
21287 // ASM symbolic names are identifiers that must be surrounded by [] without
21288 // space in between:
21289 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
21290
21291 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
21292 verifyFormat(R"(//
21293 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
21294 )");
21295
21296 // A list of several ASM symbolic names.
21297 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
21298
21299 // ASM symbolic names in inline ASM with inputs and outputs.
21300 verifyFormat(R"(//
21301 asm("cmoveq %1, %2, %[result]"
21302 : [result] "=r"(result)
21303 : "r"(test), "r"(new), "[result]"(old));
21304 )");
21305
21306 // ASM symbolic names in inline ASM with no outputs.
21307 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
21308 }
21309
TEST_F(FormatTest,GuessedLanguageWithInlineAsmClobbers)21310 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
21311 EXPECT_EQ(FormatStyle::LK_Cpp,
21312 guessLanguage("foo.h", "void f() {\n"
21313 " asm (\"mov %[e], %[d]\"\n"
21314 " : [d] \"=rm\" (d)\n"
21315 " [e] \"rm\" (*e));\n"
21316 "}"));
21317 EXPECT_EQ(FormatStyle::LK_Cpp,
21318 guessLanguage("foo.h", "void f() {\n"
21319 " _asm (\"mov %[e], %[d]\"\n"
21320 " : [d] \"=rm\" (d)\n"
21321 " [e] \"rm\" (*e));\n"
21322 "}"));
21323 EXPECT_EQ(FormatStyle::LK_Cpp,
21324 guessLanguage("foo.h", "void f() {\n"
21325 " __asm (\"mov %[e], %[d]\"\n"
21326 " : [d] \"=rm\" (d)\n"
21327 " [e] \"rm\" (*e));\n"
21328 "}"));
21329 EXPECT_EQ(FormatStyle::LK_Cpp,
21330 guessLanguage("foo.h", "void f() {\n"
21331 " __asm__ (\"mov %[e], %[d]\"\n"
21332 " : [d] \"=rm\" (d)\n"
21333 " [e] \"rm\" (*e));\n"
21334 "}"));
21335 EXPECT_EQ(FormatStyle::LK_Cpp,
21336 guessLanguage("foo.h", "void f() {\n"
21337 " asm (\"mov %[e], %[d]\"\n"
21338 " : [d] \"=rm\" (d),\n"
21339 " [e] \"rm\" (*e));\n"
21340 "}"));
21341 EXPECT_EQ(FormatStyle::LK_Cpp,
21342 guessLanguage("foo.h", "void f() {\n"
21343 " asm volatile (\"mov %[e], %[d]\"\n"
21344 " : [d] \"=rm\" (d)\n"
21345 " [e] \"rm\" (*e));\n"
21346 "}"));
21347 }
21348
TEST_F(FormatTest,GuessLanguageWithChildLines)21349 TEST_F(FormatTest, GuessLanguageWithChildLines) {
21350 EXPECT_EQ(FormatStyle::LK_Cpp,
21351 guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
21352 EXPECT_EQ(FormatStyle::LK_ObjC,
21353 guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
21354 EXPECT_EQ(
21355 FormatStyle::LK_Cpp,
21356 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
21357 EXPECT_EQ(
21358 FormatStyle::LK_ObjC,
21359 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
21360 }
21361
TEST_F(FormatTest,TypenameMacros)21362 TEST_F(FormatTest, TypenameMacros) {
21363 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
21364
21365 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
21366 FormatStyle Google = getGoogleStyleWithColumns(0);
21367 Google.TypenameMacros = TypenameMacros;
21368 verifyFormat("struct foo {\n"
21369 " int bar;\n"
21370 " TAILQ_ENTRY(a) bleh;\n"
21371 "};",
21372 Google);
21373
21374 FormatStyle Macros = getLLVMStyle();
21375 Macros.TypenameMacros = TypenameMacros;
21376
21377 verifyFormat("STACK_OF(int) a;", Macros);
21378 verifyFormat("STACK_OF(int) *a;", Macros);
21379 verifyFormat("STACK_OF(int const *) *a;", Macros);
21380 verifyFormat("STACK_OF(int *const) *a;", Macros);
21381 verifyFormat("STACK_OF(int, string) a;", Macros);
21382 verifyFormat("STACK_OF(LIST(int)) a;", Macros);
21383 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
21384 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
21385 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
21386 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
21387 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
21388
21389 Macros.PointerAlignment = FormatStyle::PAS_Left;
21390 verifyFormat("STACK_OF(int)* a;", Macros);
21391 verifyFormat("STACK_OF(int*)* a;", Macros);
21392 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
21393 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
21394 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
21395 }
21396
TEST_F(FormatTest,AtomicQualifier)21397 TEST_F(FormatTest, AtomicQualifier) {
21398 // Check that we treate _Atomic as a type and not a function call
21399 FormatStyle Google = getGoogleStyleWithColumns(0);
21400 verifyFormat("struct foo {\n"
21401 " int a1;\n"
21402 " _Atomic(a) a2;\n"
21403 " _Atomic(_Atomic(int) *const) a3;\n"
21404 "};",
21405 Google);
21406 verifyFormat("_Atomic(uint64_t) a;");
21407 verifyFormat("_Atomic(uint64_t) *a;");
21408 verifyFormat("_Atomic(uint64_t const *) *a;");
21409 verifyFormat("_Atomic(uint64_t *const) *a;");
21410 verifyFormat("_Atomic(const uint64_t *) *a;");
21411 verifyFormat("_Atomic(uint64_t) a;");
21412 verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
21413 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
21414 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
21415 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
21416
21417 verifyFormat("_Atomic(uint64_t) *s(InitValue);");
21418 verifyFormat("_Atomic(uint64_t) *s{InitValue};");
21419 FormatStyle Style = getLLVMStyle();
21420 Style.PointerAlignment = FormatStyle::PAS_Left;
21421 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
21422 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
21423 verifyFormat("_Atomic(int)* a;", Style);
21424 verifyFormat("_Atomic(int*)* a;", Style);
21425 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
21426
21427 Style.SpacesInCStyleCastParentheses = true;
21428 Style.SpacesInParentheses = false;
21429 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
21430 Style.SpacesInCStyleCastParentheses = false;
21431 Style.SpacesInParentheses = true;
21432 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
21433 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
21434 }
21435
TEST_F(FormatTest,AmbersandInLamda)21436 TEST_F(FormatTest, AmbersandInLamda) {
21437 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
21438 FormatStyle AlignStyle = getLLVMStyle();
21439 AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
21440 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21441 AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
21442 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21443 }
21444
TEST_F(FormatTest,SpacesInConditionalStatement)21445 TEST_F(FormatTest, SpacesInConditionalStatement) {
21446 FormatStyle Spaces = getLLVMStyle();
21447 Spaces.IfMacros.clear();
21448 Spaces.IfMacros.push_back("MYIF");
21449 Spaces.SpacesInConditionalStatement = true;
21450 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces);
21451 verifyFormat("if ( !a )\n return;", Spaces);
21452 verifyFormat("if ( a )\n return;", Spaces);
21453 verifyFormat("if constexpr ( a )\n return;", Spaces);
21454 verifyFormat("MYIF ( a )\n return;", Spaces);
21455 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces);
21456 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces);
21457 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces);
21458 verifyFormat("while ( a )\n return;", Spaces);
21459 verifyFormat("while ( (a && b) )\n return;", Spaces);
21460 verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
21461 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
21462 // Check that space on the left of "::" is inserted as expected at beginning
21463 // of condition.
21464 verifyFormat("while ( ::func() )\n return;", Spaces);
21465
21466 // Check impact of ControlStatementsExceptControlMacros is honored.
21467 Spaces.SpaceBeforeParens =
21468 FormatStyle::SBPO_ControlStatementsExceptControlMacros;
21469 verifyFormat("MYIF( a )\n return;", Spaces);
21470 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces);
21471 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces);
21472 }
21473
TEST_F(FormatTest,AlternativeOperators)21474 TEST_F(FormatTest, AlternativeOperators) {
21475 // Test case for ensuring alternate operators are not
21476 // combined with their right most neighbour.
21477 verifyFormat("int a and b;");
21478 verifyFormat("int a and_eq b;");
21479 verifyFormat("int a bitand b;");
21480 verifyFormat("int a bitor b;");
21481 verifyFormat("int a compl b;");
21482 verifyFormat("int a not b;");
21483 verifyFormat("int a not_eq b;");
21484 verifyFormat("int a or b;");
21485 verifyFormat("int a xor b;");
21486 verifyFormat("int a xor_eq b;");
21487 verifyFormat("return this not_eq bitand other;");
21488 verifyFormat("bool operator not_eq(const X bitand other)");
21489
21490 verifyFormat("int a and 5;");
21491 verifyFormat("int a and_eq 5;");
21492 verifyFormat("int a bitand 5;");
21493 verifyFormat("int a bitor 5;");
21494 verifyFormat("int a compl 5;");
21495 verifyFormat("int a not 5;");
21496 verifyFormat("int a not_eq 5;");
21497 verifyFormat("int a or 5;");
21498 verifyFormat("int a xor 5;");
21499 verifyFormat("int a xor_eq 5;");
21500
21501 verifyFormat("int a compl(5);");
21502 verifyFormat("int a not(5);");
21503
21504 /* FIXME handle alternate tokens
21505 * https://en.cppreference.com/w/cpp/language/operator_alternative
21506 // alternative tokens
21507 verifyFormat("compl foo();"); // ~foo();
21508 verifyFormat("foo() <%%>;"); // foo();
21509 verifyFormat("void foo() <%%>;"); // void foo(){}
21510 verifyFormat("int a <:1:>;"); // int a[1];[
21511 verifyFormat("%:define ABC abc"); // #define ABC abc
21512 verifyFormat("%:%:"); // ##
21513 */
21514 }
21515
TEST_F(FormatTest,STLWhileNotDefineChed)21516 TEST_F(FormatTest, STLWhileNotDefineChed) {
21517 verifyFormat("#if defined(while)\n"
21518 "#define while EMIT WARNING C4005\n"
21519 "#endif // while");
21520 }
21521
TEST_F(FormatTest,OperatorSpacing)21522 TEST_F(FormatTest, OperatorSpacing) {
21523 FormatStyle Style = getLLVMStyle();
21524 Style.PointerAlignment = FormatStyle::PAS_Right;
21525 verifyFormat("Foo::operator*();", Style);
21526 verifyFormat("Foo::operator void *();", Style);
21527 verifyFormat("Foo::operator void **();", Style);
21528 verifyFormat("Foo::operator void *&();", Style);
21529 verifyFormat("Foo::operator void *&&();", Style);
21530 verifyFormat("Foo::operator void const *();", Style);
21531 verifyFormat("Foo::operator void const **();", Style);
21532 verifyFormat("Foo::operator void const *&();", Style);
21533 verifyFormat("Foo::operator void const *&&();", Style);
21534 verifyFormat("Foo::operator()(void *);", Style);
21535 verifyFormat("Foo::operator*(void *);", Style);
21536 verifyFormat("Foo::operator*();", Style);
21537 verifyFormat("Foo::operator**();", Style);
21538 verifyFormat("Foo::operator&();", Style);
21539 verifyFormat("Foo::operator<int> *();", Style);
21540 verifyFormat("Foo::operator<Foo> *();", Style);
21541 verifyFormat("Foo::operator<int> **();", Style);
21542 verifyFormat("Foo::operator<Foo> **();", Style);
21543 verifyFormat("Foo::operator<int> &();", Style);
21544 verifyFormat("Foo::operator<Foo> &();", Style);
21545 verifyFormat("Foo::operator<int> &&();", Style);
21546 verifyFormat("Foo::operator<Foo> &&();", Style);
21547 verifyFormat("Foo::operator<int> *&();", Style);
21548 verifyFormat("Foo::operator<Foo> *&();", Style);
21549 verifyFormat("Foo::operator<int> *&&();", Style);
21550 verifyFormat("Foo::operator<Foo> *&&();", Style);
21551 verifyFormat("operator*(int (*)(), class Foo);", Style);
21552
21553 verifyFormat("Foo::operator&();", Style);
21554 verifyFormat("Foo::operator void &();", Style);
21555 verifyFormat("Foo::operator void const &();", Style);
21556 verifyFormat("Foo::operator()(void &);", Style);
21557 verifyFormat("Foo::operator&(void &);", Style);
21558 verifyFormat("Foo::operator&();", Style);
21559 verifyFormat("operator&(int (&)(), class Foo);", Style);
21560
21561 verifyFormat("Foo::operator&&();", Style);
21562 verifyFormat("Foo::operator**();", Style);
21563 verifyFormat("Foo::operator void &&();", Style);
21564 verifyFormat("Foo::operator void const &&();", Style);
21565 verifyFormat("Foo::operator()(void &&);", Style);
21566 verifyFormat("Foo::operator&&(void &&);", Style);
21567 verifyFormat("Foo::operator&&();", Style);
21568 verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21569 verifyFormat("operator const nsTArrayRight<E> &()", Style);
21570 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
21571 Style);
21572 verifyFormat("operator void **()", Style);
21573 verifyFormat("operator const FooRight<Object> &()", Style);
21574 verifyFormat("operator const FooRight<Object> *()", Style);
21575 verifyFormat("operator const FooRight<Object> **()", Style);
21576 verifyFormat("operator const FooRight<Object> *&()", Style);
21577 verifyFormat("operator const FooRight<Object> *&&()", Style);
21578
21579 Style.PointerAlignment = FormatStyle::PAS_Left;
21580 verifyFormat("Foo::operator*();", Style);
21581 verifyFormat("Foo::operator**();", Style);
21582 verifyFormat("Foo::operator void*();", Style);
21583 verifyFormat("Foo::operator void**();", Style);
21584 verifyFormat("Foo::operator void*&();", Style);
21585 verifyFormat("Foo::operator void*&&();", Style);
21586 verifyFormat("Foo::operator void const*();", Style);
21587 verifyFormat("Foo::operator void const**();", Style);
21588 verifyFormat("Foo::operator void const*&();", Style);
21589 verifyFormat("Foo::operator void const*&&();", Style);
21590 verifyFormat("Foo::operator/*comment*/ void*();", Style);
21591 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
21592 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
21593 verifyFormat("Foo::operator()(void*);", Style);
21594 verifyFormat("Foo::operator*(void*);", Style);
21595 verifyFormat("Foo::operator*();", Style);
21596 verifyFormat("Foo::operator<int>*();", Style);
21597 verifyFormat("Foo::operator<Foo>*();", Style);
21598 verifyFormat("Foo::operator<int>**();", Style);
21599 verifyFormat("Foo::operator<Foo>**();", Style);
21600 verifyFormat("Foo::operator<Foo>*&();", Style);
21601 verifyFormat("Foo::operator<int>&();", Style);
21602 verifyFormat("Foo::operator<Foo>&();", Style);
21603 verifyFormat("Foo::operator<int>&&();", Style);
21604 verifyFormat("Foo::operator<Foo>&&();", Style);
21605 verifyFormat("Foo::operator<int>*&();", Style);
21606 verifyFormat("Foo::operator<Foo>*&();", Style);
21607 verifyFormat("operator*(int (*)(), class Foo);", Style);
21608
21609 verifyFormat("Foo::operator&();", Style);
21610 verifyFormat("Foo::operator void&();", Style);
21611 verifyFormat("Foo::operator void const&();", Style);
21612 verifyFormat("Foo::operator/*comment*/ void&();", Style);
21613 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
21614 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
21615 verifyFormat("Foo::operator()(void&);", Style);
21616 verifyFormat("Foo::operator&(void&);", Style);
21617 verifyFormat("Foo::operator&();", Style);
21618 verifyFormat("operator&(int (&)(), class Foo);", Style);
21619
21620 verifyFormat("Foo::operator&&();", Style);
21621 verifyFormat("Foo::operator void&&();", Style);
21622 verifyFormat("Foo::operator void const&&();", Style);
21623 verifyFormat("Foo::operator/*comment*/ void&&();", Style);
21624 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
21625 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
21626 verifyFormat("Foo::operator()(void&&);", Style);
21627 verifyFormat("Foo::operator&&(void&&);", Style);
21628 verifyFormat("Foo::operator&&();", Style);
21629 verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21630 verifyFormat("operator const nsTArrayLeft<E>&()", Style);
21631 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
21632 Style);
21633 verifyFormat("operator void**()", Style);
21634 verifyFormat("operator const FooLeft<Object>&()", Style);
21635 verifyFormat("operator const FooLeft<Object>*()", Style);
21636 verifyFormat("operator const FooLeft<Object>**()", Style);
21637 verifyFormat("operator const FooLeft<Object>*&()", Style);
21638 verifyFormat("operator const FooLeft<Object>*&&()", Style);
21639
21640 // PR45107
21641 verifyFormat("operator Vector<String>&();", Style);
21642 verifyFormat("operator const Vector<String>&();", Style);
21643 verifyFormat("operator foo::Bar*();", Style);
21644 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
21645 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
21646 Style);
21647
21648 Style.PointerAlignment = FormatStyle::PAS_Middle;
21649 verifyFormat("Foo::operator*();", Style);
21650 verifyFormat("Foo::operator void *();", Style);
21651 verifyFormat("Foo::operator()(void *);", Style);
21652 verifyFormat("Foo::operator*(void *);", Style);
21653 verifyFormat("Foo::operator*();", Style);
21654 verifyFormat("operator*(int (*)(), class Foo);", Style);
21655
21656 verifyFormat("Foo::operator&();", Style);
21657 verifyFormat("Foo::operator void &();", Style);
21658 verifyFormat("Foo::operator void const &();", Style);
21659 verifyFormat("Foo::operator()(void &);", Style);
21660 verifyFormat("Foo::operator&(void &);", Style);
21661 verifyFormat("Foo::operator&();", Style);
21662 verifyFormat("operator&(int (&)(), class Foo);", Style);
21663
21664 verifyFormat("Foo::operator&&();", Style);
21665 verifyFormat("Foo::operator void &&();", Style);
21666 verifyFormat("Foo::operator void const &&();", Style);
21667 verifyFormat("Foo::operator()(void &&);", Style);
21668 verifyFormat("Foo::operator&&(void &&);", Style);
21669 verifyFormat("Foo::operator&&();", Style);
21670 verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21671 }
21672
TEST_F(FormatTest,OperatorPassedAsAFunctionPtr)21673 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
21674 FormatStyle Style = getLLVMStyle();
21675 // PR46157
21676 verifyFormat("foo(operator+, -42);", Style);
21677 verifyFormat("foo(operator++, -42);", Style);
21678 verifyFormat("foo(operator--, -42);", Style);
21679 verifyFormat("foo(-42, operator--);", Style);
21680 verifyFormat("foo(-42, operator, );", Style);
21681 verifyFormat("foo(operator, , -42);", Style);
21682 }
21683
TEST_F(FormatTest,WhitespaceSensitiveMacros)21684 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
21685 FormatStyle Style = getLLVMStyle();
21686 Style.WhitespaceSensitiveMacros.push_back("FOO");
21687
21688 // Don't use the helpers here, since 'mess up' will change the whitespace
21689 // and these are all whitespace sensitive by definition
21690 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
21691 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
21692 EXPECT_EQ(
21693 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
21694 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
21695 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
21696 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
21697 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
21698 " Still=Intentional);",
21699 format("FOO(String-ized&Messy+But,: :\n"
21700 " Still=Intentional);",
21701 Style));
21702 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
21703 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
21704 " Still=Intentional);",
21705 format("FOO(String-ized=&Messy+But,: :\n"
21706 " Still=Intentional);",
21707 Style));
21708
21709 Style.ColumnLimit = 21;
21710 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
21711 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
21712 }
21713
TEST_F(FormatTest,VeryLongNamespaceCommentSplit)21714 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
21715 // These tests are not in NamespaceFixer because that doesn't
21716 // test its interaction with line wrapping
21717 FormatStyle Style = getLLVMStyle();
21718 Style.ColumnLimit = 80;
21719 verifyFormat("namespace {\n"
21720 "int i;\n"
21721 "int j;\n"
21722 "} // namespace",
21723 Style);
21724
21725 verifyFormat("namespace AAA {\n"
21726 "int i;\n"
21727 "int j;\n"
21728 "} // namespace AAA",
21729 Style);
21730
21731 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
21732 "int i;\n"
21733 "int j;\n"
21734 "} // namespace Averyveryveryverylongnamespace",
21735 format("namespace Averyveryveryverylongnamespace {\n"
21736 "int i;\n"
21737 "int j;\n"
21738 "}",
21739 Style));
21740
21741 EXPECT_EQ(
21742 "namespace "
21743 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
21744 " went::mad::now {\n"
21745 "int i;\n"
21746 "int j;\n"
21747 "} // namespace\n"
21748 " // "
21749 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
21750 "went::mad::now",
21751 format("namespace "
21752 "would::it::save::you::a::lot::of::time::if_::i::"
21753 "just::gave::up::and_::went::mad::now {\n"
21754 "int i;\n"
21755 "int j;\n"
21756 "}",
21757 Style));
21758
21759 // This used to duplicate the comment again and again on subsequent runs
21760 EXPECT_EQ(
21761 "namespace "
21762 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
21763 " went::mad::now {\n"
21764 "int i;\n"
21765 "int j;\n"
21766 "} // namespace\n"
21767 " // "
21768 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
21769 "went::mad::now",
21770 format("namespace "
21771 "would::it::save::you::a::lot::of::time::if_::i::"
21772 "just::gave::up::and_::went::mad::now {\n"
21773 "int i;\n"
21774 "int j;\n"
21775 "} // namespace\n"
21776 " // "
21777 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
21778 "and_::went::mad::now",
21779 Style));
21780 }
21781
TEST_F(FormatTest,LikelyUnlikely)21782 TEST_F(FormatTest, LikelyUnlikely) {
21783 FormatStyle Style = getLLVMStyle();
21784
21785 verifyFormat("if (argc > 5) [[unlikely]] {\n"
21786 " return 29;\n"
21787 "}",
21788 Style);
21789
21790 verifyFormat("if (argc > 5) [[likely]] {\n"
21791 " return 29;\n"
21792 "}",
21793 Style);
21794
21795 verifyFormat("if (argc > 5) [[unlikely]] {\n"
21796 " return 29;\n"
21797 "} else [[likely]] {\n"
21798 " return 42;\n"
21799 "}\n",
21800 Style);
21801
21802 verifyFormat("if (argc > 5) [[unlikely]] {\n"
21803 " return 29;\n"
21804 "} else if (argc > 10) [[likely]] {\n"
21805 " return 99;\n"
21806 "} else {\n"
21807 " return 42;\n"
21808 "}\n",
21809 Style);
21810
21811 verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
21812 " return 29;\n"
21813 "}",
21814 Style);
21815 }
21816
TEST_F(FormatTest,PenaltyIndentedWhitespace)21817 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
21818 verifyFormat("Constructor()\n"
21819 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21820 " aaaa(aaaaaaaaaaaaaaaaaa, "
21821 "aaaaaaaaaaaaaaaaaat))");
21822 verifyFormat("Constructor()\n"
21823 " : aaaaaaaaaaaaa(aaaaaa), "
21824 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
21825
21826 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
21827 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
21828 verifyFormat("Constructor()\n"
21829 " : aaaaaa(aaaaaa),\n"
21830 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21831 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
21832 StyleWithWhitespacePenalty);
21833 verifyFormat("Constructor()\n"
21834 " : aaaaaaaaaaaaa(aaaaaa), "
21835 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
21836 StyleWithWhitespacePenalty);
21837 }
21838
TEST_F(FormatTest,LLVMDefaultStyle)21839 TEST_F(FormatTest, LLVMDefaultStyle) {
21840 FormatStyle Style = getLLVMStyle();
21841 verifyFormat("extern \"C\" {\n"
21842 "int foo();\n"
21843 "}",
21844 Style);
21845 }
TEST_F(FormatTest,GNUDefaultStyle)21846 TEST_F(FormatTest, GNUDefaultStyle) {
21847 FormatStyle Style = getGNUStyle();
21848 verifyFormat("extern \"C\"\n"
21849 "{\n"
21850 " int foo ();\n"
21851 "}",
21852 Style);
21853 }
TEST_F(FormatTest,MozillaDefaultStyle)21854 TEST_F(FormatTest, MozillaDefaultStyle) {
21855 FormatStyle Style = getMozillaStyle();
21856 verifyFormat("extern \"C\"\n"
21857 "{\n"
21858 " int foo();\n"
21859 "}",
21860 Style);
21861 }
TEST_F(FormatTest,GoogleDefaultStyle)21862 TEST_F(FormatTest, GoogleDefaultStyle) {
21863 FormatStyle Style = getGoogleStyle();
21864 verifyFormat("extern \"C\" {\n"
21865 "int foo();\n"
21866 "}",
21867 Style);
21868 }
TEST_F(FormatTest,ChromiumDefaultStyle)21869 TEST_F(FormatTest, ChromiumDefaultStyle) {
21870 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
21871 verifyFormat("extern \"C\" {\n"
21872 "int foo();\n"
21873 "}",
21874 Style);
21875 }
TEST_F(FormatTest,MicrosoftDefaultStyle)21876 TEST_F(FormatTest, MicrosoftDefaultStyle) {
21877 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
21878 verifyFormat("extern \"C\"\n"
21879 "{\n"
21880 " int foo();\n"
21881 "}",
21882 Style);
21883 }
TEST_F(FormatTest,WebKitDefaultStyle)21884 TEST_F(FormatTest, WebKitDefaultStyle) {
21885 FormatStyle Style = getWebKitStyle();
21886 verifyFormat("extern \"C\" {\n"
21887 "int foo();\n"
21888 "}",
21889 Style);
21890 }
21891
TEST_F(FormatTest,ConceptsAndRequires)21892 TEST_F(FormatTest, ConceptsAndRequires) {
21893 FormatStyle Style = getLLVMStyle();
21894 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
21895
21896 verifyFormat("template <typename T>\n"
21897 "concept Hashable = requires(T a) {\n"
21898 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
21899 "};",
21900 Style);
21901 verifyFormat("template <typename T>\n"
21902 "concept EqualityComparable = requires(T a, T b) {\n"
21903 " { a == b } -> bool;\n"
21904 "};",
21905 Style);
21906 verifyFormat("template <typename T>\n"
21907 "concept EqualityComparable = requires(T a, T b) {\n"
21908 " { a == b } -> bool;\n"
21909 " { a != b } -> bool;\n"
21910 "};",
21911 Style);
21912 verifyFormat("template <typename T>\n"
21913 "concept EqualityComparable = requires(T a, T b) {\n"
21914 " { a == b } -> bool;\n"
21915 " { a != b } -> bool;\n"
21916 "};",
21917 Style);
21918
21919 verifyFormat("template <typename It>\n"
21920 "requires Iterator<It>\n"
21921 "void sort(It begin, It end) {\n"
21922 " //....\n"
21923 "}",
21924 Style);
21925
21926 verifyFormat("template <typename T>\n"
21927 "concept Large = sizeof(T) > 10;",
21928 Style);
21929
21930 verifyFormat("template <typename T, typename U>\n"
21931 "concept FooableWith = requires(T t, U u) {\n"
21932 " typename T::foo_type;\n"
21933 " { t.foo(u) } -> typename T::foo_type;\n"
21934 " t++;\n"
21935 "};\n"
21936 "void doFoo(FooableWith<int> auto t) {\n"
21937 " t.foo(3);\n"
21938 "}",
21939 Style);
21940 verifyFormat("template <typename T>\n"
21941 "concept Context = sizeof(T) == 1;",
21942 Style);
21943 verifyFormat("template <typename T>\n"
21944 "concept Context = is_specialization_of_v<context, T>;",
21945 Style);
21946 verifyFormat("template <typename T>\n"
21947 "concept Node = std::is_object_v<T>;",
21948 Style);
21949 verifyFormat("template <typename T>\n"
21950 "concept Tree = true;",
21951 Style);
21952
21953 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
21954 " //...\n"
21955 "}",
21956 Style);
21957
21958 verifyFormat(
21959 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
21960 " //...\n"
21961 "}",
21962 Style);
21963
21964 verifyFormat(
21965 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
21966 " //...\n"
21967 "}",
21968 Style);
21969
21970 verifyFormat("template <typename T>\n"
21971 "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
21972 "Concept2<I> {\n"
21973 " //...\n"
21974 "}",
21975 Style);
21976
21977 verifyFormat("template <typename T>\n"
21978 "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
21979 "Concept2<I> {\n"
21980 " //...\n"
21981 "}",
21982 Style);
21983
21984 verifyFormat(
21985 "template <typename T>\n"
21986 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
21987 " //...\n"
21988 "}",
21989 Style);
21990
21991 verifyFormat(
21992 "template <typename T>\n"
21993 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
21994 " //...\n"
21995 "}",
21996 Style);
21997
21998 verifyFormat("template <typename It>\n"
21999 "requires Foo<It>() && Bar<It> {\n"
22000 " //....\n"
22001 "}",
22002 Style);
22003
22004 verifyFormat("template <typename It>\n"
22005 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
22006 " //....\n"
22007 "}",
22008 Style);
22009
22010 verifyFormat("template <typename It>\n"
22011 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
22012 " //....\n"
22013 "}",
22014 Style);
22015
22016 verifyFormat(
22017 "template <typename It>\n"
22018 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
22019 " //....\n"
22020 "}",
22021 Style);
22022
22023 Style.IndentRequires = true;
22024 verifyFormat("template <typename It>\n"
22025 " requires Iterator<It>\n"
22026 "void sort(It begin, It end) {\n"
22027 " //....\n"
22028 "}",
22029 Style);
22030 verifyFormat("template <std::size index_>\n"
22031 " requires(index_ < sizeof...(Children_))\n"
22032 "Tree auto &child() {\n"
22033 " // ...\n"
22034 "}",
22035 Style);
22036
22037 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
22038 verifyFormat("template <typename T>\n"
22039 "concept Hashable = requires (T a) {\n"
22040 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22041 "};",
22042 Style);
22043
22044 verifyFormat("template <class T = void>\n"
22045 " requires EqualityComparable<T> || Same<T, void>\n"
22046 "struct equal_to;",
22047 Style);
22048
22049 verifyFormat("template <class T>\n"
22050 " requires requires {\n"
22051 " T{};\n"
22052 " T (int);\n"
22053 " }\n",
22054 Style);
22055
22056 Style.ColumnLimit = 78;
22057 verifyFormat("template <typename T>\n"
22058 "concept Context = Traits<typename T::traits_type> and\n"
22059 " Interface<typename T::interface_type> and\n"
22060 " Request<typename T::request_type> and\n"
22061 " Response<typename T::response_type> and\n"
22062 " ContextExtension<typename T::extension_type> and\n"
22063 " ::std::is_copy_constructable<T> and "
22064 "::std::is_move_constructable<T> and\n"
22065 " requires (T c) {\n"
22066 " { c.response; } -> Response;\n"
22067 "} and requires (T c) {\n"
22068 " { c.request; } -> Request;\n"
22069 "}\n",
22070 Style);
22071
22072 verifyFormat("template <typename T>\n"
22073 "concept Context = Traits<typename T::traits_type> or\n"
22074 " Interface<typename T::interface_type> or\n"
22075 " Request<typename T::request_type> or\n"
22076 " Response<typename T::response_type> or\n"
22077 " ContextExtension<typename T::extension_type> or\n"
22078 " ::std::is_copy_constructable<T> or "
22079 "::std::is_move_constructable<T> or\n"
22080 " requires (T c) {\n"
22081 " { c.response; } -> Response;\n"
22082 "} or requires (T c) {\n"
22083 " { c.request; } -> Request;\n"
22084 "}\n",
22085 Style);
22086
22087 verifyFormat("template <typename T>\n"
22088 "concept Context = Traits<typename T::traits_type> &&\n"
22089 " Interface<typename T::interface_type> &&\n"
22090 " Request<typename T::request_type> &&\n"
22091 " Response<typename T::response_type> &&\n"
22092 " ContextExtension<typename T::extension_type> &&\n"
22093 " ::std::is_copy_constructable<T> && "
22094 "::std::is_move_constructable<T> &&\n"
22095 " requires (T c) {\n"
22096 " { c.response; } -> Response;\n"
22097 "} && requires (T c) {\n"
22098 " { c.request; } -> Request;\n"
22099 "}\n",
22100 Style);
22101
22102 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
22103 "Constraint2<T>;");
22104
22105 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
22106 Style.BraceWrapping.AfterFunction = true;
22107 Style.BraceWrapping.AfterClass = true;
22108 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
22109 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
22110 verifyFormat("void Foo () requires (std::copyable<T>)\n"
22111 "{\n"
22112 " return\n"
22113 "}\n",
22114 Style);
22115
22116 verifyFormat("void Foo () requires std::copyable<T>\n"
22117 "{\n"
22118 " return\n"
22119 "}\n",
22120 Style);
22121
22122 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22123 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
22124 "struct constant;",
22125 Style);
22126
22127 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22128 " requires std::invocable<F, std::invoke_result_t<Args>...>\n"
22129 "struct constant;",
22130 Style);
22131
22132 verifyFormat("template <class T>\n"
22133 "class plane_with_very_very_very_long_name\n"
22134 "{\n"
22135 " constexpr plane_with_very_very_very_long_name () requires "
22136 "std::copyable<T>\n"
22137 " : plane_with_very_very_very_long_name (1)\n"
22138 " {\n"
22139 " }\n"
22140 "}\n",
22141 Style);
22142
22143 verifyFormat("template <class T>\n"
22144 "class plane_with_long_name\n"
22145 "{\n"
22146 " constexpr plane_with_long_name () requires std::copyable<T>\n"
22147 " : plane_with_long_name (1)\n"
22148 " {\n"
22149 " }\n"
22150 "}\n",
22151 Style);
22152
22153 Style.BreakBeforeConceptDeclarations = false;
22154 verifyFormat("template <typename T> concept Tree = true;", Style);
22155
22156 Style.IndentRequires = false;
22157 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22158 "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
22159 "struct constant;",
22160 Style);
22161 }
22162
TEST_F(FormatTest,StatementAttributeLikeMacros)22163 TEST_F(FormatTest, StatementAttributeLikeMacros) {
22164 FormatStyle Style = getLLVMStyle();
22165 StringRef Source = "void Foo::slot() {\n"
22166 " unsigned char MyChar = 'x';\n"
22167 " emit signal(MyChar);\n"
22168 " Q_EMIT signal(MyChar);\n"
22169 "}";
22170
22171 EXPECT_EQ(Source, format(Source, Style));
22172
22173 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
22174 EXPECT_EQ("void Foo::slot() {\n"
22175 " unsigned char MyChar = 'x';\n"
22176 " emit signal(MyChar);\n"
22177 " Q_EMIT signal(MyChar);\n"
22178 "}",
22179 format(Source, Style));
22180
22181 Style.StatementAttributeLikeMacros.push_back("emit");
22182 EXPECT_EQ(Source, format(Source, Style));
22183
22184 Style.StatementAttributeLikeMacros = {};
22185 EXPECT_EQ("void Foo::slot() {\n"
22186 " unsigned char MyChar = 'x';\n"
22187 " emit signal(MyChar);\n"
22188 " Q_EMIT signal(MyChar);\n"
22189 "}",
22190 format(Source, Style));
22191 }
22192
TEST_F(FormatTest,IndentAccessModifiers)22193 TEST_F(FormatTest, IndentAccessModifiers) {
22194 FormatStyle Style = getLLVMStyle();
22195 Style.IndentAccessModifiers = true;
22196 // Members are *two* levels below the record;
22197 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
22198 verifyFormat("class C {\n"
22199 " int i;\n"
22200 "};\n",
22201 Style);
22202 verifyFormat("union C {\n"
22203 " int i;\n"
22204 " unsigned u;\n"
22205 "};\n",
22206 Style);
22207 // Access modifiers should be indented one level below the record.
22208 verifyFormat("class C {\n"
22209 " public:\n"
22210 " int i;\n"
22211 "};\n",
22212 Style);
22213 verifyFormat("struct S {\n"
22214 " private:\n"
22215 " class C {\n"
22216 " int j;\n"
22217 "\n"
22218 " public:\n"
22219 " C();\n"
22220 " };\n"
22221 "\n"
22222 " public:\n"
22223 " int i;\n"
22224 "};\n",
22225 Style);
22226 // Enumerations are not records and should be unaffected.
22227 Style.AllowShortEnumsOnASingleLine = false;
22228 verifyFormat("enum class E {\n"
22229 " A,\n"
22230 " B\n"
22231 "};\n",
22232 Style);
22233 // Test with a different indentation width;
22234 // also proves that the result is Style.AccessModifierOffset agnostic.
22235 Style.IndentWidth = 3;
22236 verifyFormat("class C {\n"
22237 " public:\n"
22238 " int i;\n"
22239 "};\n",
22240 Style);
22241 }
22242
TEST_F(FormatTest,LimitlessStringsAndComments)22243 TEST_F(FormatTest, LimitlessStringsAndComments) {
22244 auto Style = getLLVMStyleWithColumns(0);
22245 constexpr StringRef Code =
22246 "/**\n"
22247 " * This is a multiline comment with quite some long lines, at least for "
22248 "the LLVM Style.\n"
22249 " * We will redo this with strings and line comments. Just to check if "
22250 "everything is working.\n"
22251 " */\n"
22252 "bool foo() {\n"
22253 " /* Single line multi line comment. */\n"
22254 " const std::string String = \"This is a multiline string with quite "
22255 "some long lines, at least for the LLVM Style.\"\n"
22256 " \"We already did it with multi line "
22257 "comments, and we will do it with line comments. Just to check if "
22258 "everything is working.\";\n"
22259 " // This is a line comment (block) with quite some long lines, at "
22260 "least for the LLVM Style.\n"
22261 " // We already did this with multi line comments and strings. Just to "
22262 "check if everything is working.\n"
22263 " const std::string SmallString = \"Hello World\";\n"
22264 " // Small line comment\n"
22265 " return String.size() > SmallString.size();\n"
22266 "}";
22267 EXPECT_EQ(Code, format(Code, Style));
22268 }
22269 } // namespace
22270 } // namespace format
22271 } // namespace clang
22272