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::internal::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 // ...but do keep inlining and removing empty lines for non-block extern "C"
266 // functions.
267 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
268 EXPECT_EQ("extern \"C\" int f() {\n"
269 " int i = 42;\n"
270 " return i;\n"
271 "}",
272 format("extern \"C\" int f() {\n"
273 "\n"
274 " int i = 42;\n"
275 " return i;\n"
276 "}",
277 getGoogleStyle()));
278
279 // Remove empty lines at the beginning and end of blocks.
280 EXPECT_EQ("void f() {\n"
281 "\n"
282 " if (a) {\n"
283 "\n"
284 " f();\n"
285 " }\n"
286 "}",
287 format("void f() {\n"
288 "\n"
289 " if (a) {\n"
290 "\n"
291 " f();\n"
292 "\n"
293 " }\n"
294 "\n"
295 "}",
296 getLLVMStyle()));
297 EXPECT_EQ("void f() {\n"
298 " if (a) {\n"
299 " f();\n"
300 " }\n"
301 "}",
302 format("void f() {\n"
303 "\n"
304 " if (a) {\n"
305 "\n"
306 " f();\n"
307 "\n"
308 " }\n"
309 "\n"
310 "}",
311 getGoogleStyle()));
312
313 // Don't remove empty lines in more complex control statements.
314 EXPECT_EQ("void f() {\n"
315 " if (a) {\n"
316 " f();\n"
317 "\n"
318 " } else if (b) {\n"
319 " f();\n"
320 " }\n"
321 "}",
322 format("void f() {\n"
323 " if (a) {\n"
324 " f();\n"
325 "\n"
326 " } else if (b) {\n"
327 " f();\n"
328 "\n"
329 " }\n"
330 "\n"
331 "}"));
332
333 // Don't remove empty lines before namespace endings.
334 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
335 LLVMWithNoNamespaceFix.FixNamespaceComments = false;
336 EXPECT_EQ("namespace {\n"
337 "int i;\n"
338 "\n"
339 "}",
340 format("namespace {\n"
341 "int i;\n"
342 "\n"
343 "}",
344 LLVMWithNoNamespaceFix));
345 EXPECT_EQ("namespace {\n"
346 "int i;\n"
347 "}",
348 format("namespace {\n"
349 "int i;\n"
350 "}",
351 LLVMWithNoNamespaceFix));
352 EXPECT_EQ("namespace {\n"
353 "int i;\n"
354 "\n"
355 "};",
356 format("namespace {\n"
357 "int i;\n"
358 "\n"
359 "};",
360 LLVMWithNoNamespaceFix));
361 EXPECT_EQ("namespace {\n"
362 "int i;\n"
363 "};",
364 format("namespace {\n"
365 "int i;\n"
366 "};",
367 LLVMWithNoNamespaceFix));
368 EXPECT_EQ("namespace {\n"
369 "int i;\n"
370 "\n"
371 "}",
372 format("namespace {\n"
373 "int i;\n"
374 "\n"
375 "}"));
376 EXPECT_EQ("namespace {\n"
377 "int i;\n"
378 "\n"
379 "} // namespace",
380 format("namespace {\n"
381 "int i;\n"
382 "\n"
383 "} // namespace"));
384
385 FormatStyle Style = getLLVMStyle();
386 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
387 Style.MaxEmptyLinesToKeep = 2;
388 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
389 Style.BraceWrapping.AfterClass = true;
390 Style.BraceWrapping.AfterFunction = true;
391 Style.KeepEmptyLinesAtTheStartOfBlocks = false;
392
393 EXPECT_EQ("class Foo\n"
394 "{\n"
395 " Foo() {}\n"
396 "\n"
397 " void funk() {}\n"
398 "};",
399 format("class Foo\n"
400 "{\n"
401 " Foo()\n"
402 " {\n"
403 " }\n"
404 "\n"
405 " void funk() {}\n"
406 "};",
407 Style));
408 }
409
TEST_F(FormatTest,RecognizesBinaryOperatorKeywords)410 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
411 verifyFormat("x = (a) and (b);");
412 verifyFormat("x = (a) or (b);");
413 verifyFormat("x = (a) bitand (b);");
414 verifyFormat("x = (a) bitor (b);");
415 verifyFormat("x = (a) not_eq (b);");
416 verifyFormat("x = (a) and_eq (b);");
417 verifyFormat("x = (a) or_eq (b);");
418 verifyFormat("x = (a) xor (b);");
419 }
420
TEST_F(FormatTest,RecognizesUnaryOperatorKeywords)421 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
422 verifyFormat("x = compl(a);");
423 verifyFormat("x = not(a);");
424 verifyFormat("x = bitand(a);");
425 // Unary operator must not be merged with the next identifier
426 verifyFormat("x = compl a;");
427 verifyFormat("x = not a;");
428 verifyFormat("x = bitand a;");
429 }
430
431 //===----------------------------------------------------------------------===//
432 // Tests for control statements.
433 //===----------------------------------------------------------------------===//
434
TEST_F(FormatTest,FormatIfWithoutCompoundStatement)435 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
436 verifyFormat("if (true)\n f();\ng();");
437 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();");
438 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();");
439 verifyFormat("if constexpr (true)\n"
440 " f();\ng();");
441 verifyFormat("if CONSTEXPR (true)\n"
442 " f();\ng();");
443 verifyFormat("if constexpr (a)\n"
444 " if constexpr (b)\n"
445 " if constexpr (c)\n"
446 " g();\n"
447 "h();");
448 verifyFormat("if CONSTEXPR (a)\n"
449 " if CONSTEXPR (b)\n"
450 " if CONSTEXPR (c)\n"
451 " g();\n"
452 "h();");
453 verifyFormat("if constexpr (a)\n"
454 " if constexpr (b) {\n"
455 " f();\n"
456 " }\n"
457 "g();");
458 verifyFormat("if CONSTEXPR (a)\n"
459 " if CONSTEXPR (b) {\n"
460 " f();\n"
461 " }\n"
462 "g();");
463
464 FormatStyle AllowsMergedIf = getLLVMStyle();
465 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
466 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
467 FormatStyle::SIS_WithoutElse;
468 verifyFormat("if (a)\n"
469 " // comment\n"
470 " f();",
471 AllowsMergedIf);
472 verifyFormat("{\n"
473 " if (a)\n"
474 " label:\n"
475 " f();\n"
476 "}",
477 AllowsMergedIf);
478 verifyFormat("#define A \\\n"
479 " if (a) \\\n"
480 " label: \\\n"
481 " f()",
482 AllowsMergedIf);
483 verifyFormat("if (a)\n"
484 " ;",
485 AllowsMergedIf);
486 verifyFormat("if (a)\n"
487 " if (b) return;",
488 AllowsMergedIf);
489
490 verifyFormat("if (a) // Can't merge this\n"
491 " f();\n",
492 AllowsMergedIf);
493 verifyFormat("if (a) /* still don't merge */\n"
494 " f();",
495 AllowsMergedIf);
496 verifyFormat("if (a) { // Never merge this\n"
497 " f();\n"
498 "}",
499 AllowsMergedIf);
500 verifyFormat("if (a) { /* Never merge this */\n"
501 " f();\n"
502 "}",
503 AllowsMergedIf);
504
505 AllowsMergedIf.ColumnLimit = 14;
506 verifyFormat("if (a) return;", AllowsMergedIf);
507 verifyFormat("if (aaaaaaaaa)\n"
508 " return;",
509 AllowsMergedIf);
510
511 AllowsMergedIf.ColumnLimit = 13;
512 verifyFormat("if (a)\n return;", AllowsMergedIf);
513 }
514
TEST_F(FormatTest,FormatIfWithoutCompoundStatementButElseWith)515 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
516 FormatStyle AllowsMergedIf = getLLVMStyle();
517 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
518 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
519 FormatStyle::SIS_WithoutElse;
520 verifyFormat("if (a)\n"
521 " f();\n"
522 "else {\n"
523 " g();\n"
524 "}",
525 AllowsMergedIf);
526 verifyFormat("if (a)\n"
527 " f();\n"
528 "else\n"
529 " g();\n",
530 AllowsMergedIf);
531
532 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
533
534 verifyFormat("if (a) f();\n"
535 "else {\n"
536 " g();\n"
537 "}",
538 AllowsMergedIf);
539 verifyFormat("if (a) f();\n"
540 "else {\n"
541 " if (a) f();\n"
542 " else {\n"
543 " g();\n"
544 " }\n"
545 " g();\n"
546 "}",
547 AllowsMergedIf);
548 }
549
TEST_F(FormatTest,FormatLoopsWithoutCompoundStatement)550 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
551 FormatStyle AllowsMergedLoops = getLLVMStyle();
552 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
553 verifyFormat("while (true) continue;", AllowsMergedLoops);
554 verifyFormat("for (;;) continue;", AllowsMergedLoops);
555 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
556 verifyFormat("while (true)\n"
557 " ;",
558 AllowsMergedLoops);
559 verifyFormat("for (;;)\n"
560 " ;",
561 AllowsMergedLoops);
562 verifyFormat("for (;;)\n"
563 " for (;;) continue;",
564 AllowsMergedLoops);
565 verifyFormat("for (;;) // Can't merge this\n"
566 " continue;",
567 AllowsMergedLoops);
568 verifyFormat("for (;;) /* still don't merge */\n"
569 " continue;",
570 AllowsMergedLoops);
571 verifyFormat("do a++;\n"
572 "while (true);",
573 AllowsMergedLoops);
574 verifyFormat("do /* Don't merge */\n"
575 " a++;\n"
576 "while (true);",
577 AllowsMergedLoops);
578 verifyFormat("do // Don't merge\n"
579 " a++;\n"
580 "while (true);",
581 AllowsMergedLoops);
582 verifyFormat("do\n"
583 " // Don't merge\n"
584 " a++;\n"
585 "while (true);",
586 AllowsMergedLoops);
587 // Without braces labels are interpreted differently.
588 verifyFormat("{\n"
589 " do\n"
590 " label:\n"
591 " a++;\n"
592 " while (true);\n"
593 "}",
594 AllowsMergedLoops);
595 }
596
TEST_F(FormatTest,FormatShortBracedStatements)597 TEST_F(FormatTest, FormatShortBracedStatements) {
598 FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
599 AllowSimpleBracedStatements.ColumnLimit = 40;
600 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
601 FormatStyle::SBS_Always;
602
603 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
604 FormatStyle::SIS_WithoutElse;
605 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
606
607 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
608 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
609 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
610
611 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
612 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
613 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
614 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
615 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
616 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
617 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
618 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
619 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
620 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
621 verifyFormat("if (true) { fffffffffffffffffffffff(); }",
622 AllowSimpleBracedStatements);
623 verifyFormat("if (true) {\n"
624 " ffffffffffffffffffffffff();\n"
625 "}",
626 AllowSimpleBracedStatements);
627 verifyFormat("if (true) {\n"
628 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
629 "}",
630 AllowSimpleBracedStatements);
631 verifyFormat("if (true) { //\n"
632 " f();\n"
633 "}",
634 AllowSimpleBracedStatements);
635 verifyFormat("if (true) {\n"
636 " f();\n"
637 " f();\n"
638 "}",
639 AllowSimpleBracedStatements);
640 verifyFormat("if (true) {\n"
641 " f();\n"
642 "} else {\n"
643 " f();\n"
644 "}",
645 AllowSimpleBracedStatements);
646
647 verifyFormat("struct A2 {\n"
648 " int X;\n"
649 "};",
650 AllowSimpleBracedStatements);
651 verifyFormat("typedef struct A2 {\n"
652 " int X;\n"
653 "} A2_t;",
654 AllowSimpleBracedStatements);
655 verifyFormat("template <int> struct A2 {\n"
656 " struct B {};\n"
657 "};",
658 AllowSimpleBracedStatements);
659
660 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
661 FormatStyle::SIS_Never;
662 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
663 verifyFormat("if (true) {\n"
664 " f();\n"
665 "}",
666 AllowSimpleBracedStatements);
667 verifyFormat("if (true) {\n"
668 " f();\n"
669 "} else {\n"
670 " f();\n"
671 "}",
672 AllowSimpleBracedStatements);
673
674 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
675 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
676 verifyFormat("while (true) {\n"
677 " f();\n"
678 "}",
679 AllowSimpleBracedStatements);
680 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
681 verifyFormat("for (;;) {\n"
682 " f();\n"
683 "}",
684 AllowSimpleBracedStatements);
685
686 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
687 FormatStyle::SIS_WithoutElse;
688 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
689 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
690 FormatStyle::BWACS_Always;
691
692 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
693 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
694 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
695 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
696 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
697 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
698 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
699 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
700 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
701 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
702 verifyFormat("if (true) { fffffffffffffffffffffff(); }",
703 AllowSimpleBracedStatements);
704 verifyFormat("if (true)\n"
705 "{\n"
706 " ffffffffffffffffffffffff();\n"
707 "}",
708 AllowSimpleBracedStatements);
709 verifyFormat("if (true)\n"
710 "{\n"
711 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
712 "}",
713 AllowSimpleBracedStatements);
714 verifyFormat("if (true)\n"
715 "{ //\n"
716 " f();\n"
717 "}",
718 AllowSimpleBracedStatements);
719 verifyFormat("if (true)\n"
720 "{\n"
721 " f();\n"
722 " f();\n"
723 "}",
724 AllowSimpleBracedStatements);
725 verifyFormat("if (true)\n"
726 "{\n"
727 " f();\n"
728 "} else\n"
729 "{\n"
730 " f();\n"
731 "}",
732 AllowSimpleBracedStatements);
733
734 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
735 FormatStyle::SIS_Never;
736 verifyFormat("if (true) {}", AllowSimpleBracedStatements);
737 verifyFormat("if (true)\n"
738 "{\n"
739 " f();\n"
740 "}",
741 AllowSimpleBracedStatements);
742 verifyFormat("if (true)\n"
743 "{\n"
744 " f();\n"
745 "} else\n"
746 "{\n"
747 " f();\n"
748 "}",
749 AllowSimpleBracedStatements);
750
751 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
752 verifyFormat("while (true) {}", AllowSimpleBracedStatements);
753 verifyFormat("while (true)\n"
754 "{\n"
755 " f();\n"
756 "}",
757 AllowSimpleBracedStatements);
758 verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
759 verifyFormat("for (;;)\n"
760 "{\n"
761 " f();\n"
762 "}",
763 AllowSimpleBracedStatements);
764 }
765
TEST_F(FormatTest,ShortBlocksInMacrosDontMergeWithCodeAfterMacro)766 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
767 FormatStyle Style = getLLVMStyleWithColumns(60);
768 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
769 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
770 Style.BreakBeforeBraces = FormatStyle::BS_Allman;
771 EXPECT_EQ("#define A \\\n"
772 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
773 " { \\\n"
774 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
775 " }\n"
776 "X;",
777 format("#define A \\\n"
778 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
779 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
780 " }\n"
781 "X;",
782 Style));
783 }
784
TEST_F(FormatTest,ParseIfElse)785 TEST_F(FormatTest, ParseIfElse) {
786 verifyFormat("if (true)\n"
787 " if (true)\n"
788 " if (true)\n"
789 " f();\n"
790 " else\n"
791 " g();\n"
792 " else\n"
793 " h();\n"
794 "else\n"
795 " i();");
796 verifyFormat("if (true)\n"
797 " if (true)\n"
798 " if (true) {\n"
799 " if (true)\n"
800 " f();\n"
801 " } else {\n"
802 " g();\n"
803 " }\n"
804 " else\n"
805 " h();\n"
806 "else {\n"
807 " i();\n"
808 "}");
809 verifyFormat("if (true)\n"
810 " if constexpr (true)\n"
811 " if (true) {\n"
812 " if constexpr (true)\n"
813 " f();\n"
814 " } else {\n"
815 " g();\n"
816 " }\n"
817 " else\n"
818 " h();\n"
819 "else {\n"
820 " i();\n"
821 "}");
822 verifyFormat("if (true)\n"
823 " if CONSTEXPR (true)\n"
824 " if (true) {\n"
825 " if CONSTEXPR (true)\n"
826 " f();\n"
827 " } else {\n"
828 " g();\n"
829 " }\n"
830 " else\n"
831 " h();\n"
832 "else {\n"
833 " i();\n"
834 "}");
835 verifyFormat("void f() {\n"
836 " if (a) {\n"
837 " } else {\n"
838 " }\n"
839 "}");
840 }
841
TEST_F(FormatTest,ElseIf)842 TEST_F(FormatTest, ElseIf) {
843 verifyFormat("if (a) {\n} else if (b) {\n}");
844 verifyFormat("if (a)\n"
845 " f();\n"
846 "else if (b)\n"
847 " g();\n"
848 "else\n"
849 " h();");
850 verifyFormat("if constexpr (a)\n"
851 " f();\n"
852 "else if constexpr (b)\n"
853 " g();\n"
854 "else\n"
855 " h();");
856 verifyFormat("if CONSTEXPR (a)\n"
857 " f();\n"
858 "else if CONSTEXPR (b)\n"
859 " g();\n"
860 "else\n"
861 " h();");
862 verifyFormat("if (a) {\n"
863 " f();\n"
864 "}\n"
865 "// or else ..\n"
866 "else {\n"
867 " g()\n"
868 "}");
869
870 verifyFormat("if (a) {\n"
871 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
872 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
873 "}");
874 verifyFormat("if (a) {\n"
875 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
876 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
877 "}");
878 verifyFormat("if (a) {\n"
879 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
880 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
881 "}");
882 verifyFormat("if (a) {\n"
883 "} else if (\n"
884 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
885 "}",
886 getLLVMStyleWithColumns(62));
887 verifyFormat("if (a) {\n"
888 "} else if constexpr (\n"
889 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
890 "}",
891 getLLVMStyleWithColumns(62));
892 verifyFormat("if (a) {\n"
893 "} else if CONSTEXPR (\n"
894 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
895 "}",
896 getLLVMStyleWithColumns(62));
897 }
898
TEST_F(FormatTest,FormatsForLoop)899 TEST_F(FormatTest, FormatsForLoop) {
900 verifyFormat(
901 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
902 " ++VeryVeryLongLoopVariable)\n"
903 " ;");
904 verifyFormat("for (;;)\n"
905 " f();");
906 verifyFormat("for (;;) {\n}");
907 verifyFormat("for (;;) {\n"
908 " f();\n"
909 "}");
910 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
911
912 verifyFormat(
913 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
914 " E = UnwrappedLines.end();\n"
915 " I != E; ++I) {\n}");
916
917 verifyFormat(
918 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
919 " ++IIIII) {\n}");
920 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
921 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
922 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
923 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
924 " I = FD->getDeclsInPrototypeScope().begin(),\n"
925 " E = FD->getDeclsInPrototypeScope().end();\n"
926 " I != E; ++I) {\n}");
927 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
928 " I = Container.begin(),\n"
929 " E = Container.end();\n"
930 " I != E; ++I) {\n}",
931 getLLVMStyleWithColumns(76));
932
933 verifyFormat(
934 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
935 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
936 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
937 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
938 " ++aaaaaaaaaaa) {\n}");
939 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
940 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
941 " ++i) {\n}");
942 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
943 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
944 "}");
945 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
946 " aaaaaaaaaa);\n"
947 " iter; ++iter) {\n"
948 "}");
949 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
950 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
951 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
952 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
953
954 // These should not be formatted as Objective-C for-in loops.
955 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
956 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
957 verifyFormat("Foo *x;\nfor (x in y) {\n}");
958 verifyFormat(
959 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
960
961 FormatStyle NoBinPacking = getLLVMStyle();
962 NoBinPacking.BinPackParameters = false;
963 verifyFormat("for (int aaaaaaaaaaa = 1;\n"
964 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
965 " aaaaaaaaaaaaaaaa,\n"
966 " aaaaaaaaaaaaaaaa,\n"
967 " aaaaaaaaaaaaaaaa);\n"
968 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
969 "}",
970 NoBinPacking);
971 verifyFormat(
972 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
973 " E = UnwrappedLines.end();\n"
974 " I != E;\n"
975 " ++I) {\n}",
976 NoBinPacking);
977
978 FormatStyle AlignLeft = getLLVMStyle();
979 AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
980 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
981 }
982
TEST_F(FormatTest,RangeBasedForLoops)983 TEST_F(FormatTest, RangeBasedForLoops) {
984 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
985 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
986 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
987 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
988 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
989 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
990 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
991 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
992 }
993
TEST_F(FormatTest,ForEachLoops)994 TEST_F(FormatTest, ForEachLoops) {
995 verifyFormat("void f() {\n"
996 " foreach (Item *item, itemlist) {}\n"
997 " Q_FOREACH (Item *item, itemlist) {}\n"
998 " BOOST_FOREACH (Item *item, itemlist) {}\n"
999 " UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1000 "}");
1001
1002 FormatStyle Style = getLLVMStyle();
1003 Style.SpaceBeforeParens =
1004 FormatStyle::SBPO_ControlStatementsExceptForEachMacros;
1005 verifyFormat("void f() {\n"
1006 " foreach(Item *item, itemlist) {}\n"
1007 " Q_FOREACH(Item *item, itemlist) {}\n"
1008 " BOOST_FOREACH(Item *item, itemlist) {}\n"
1009 " UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1010 "}",
1011 Style);
1012
1013 // As function-like macros.
1014 verifyFormat("#define foreach(x, y)\n"
1015 "#define Q_FOREACH(x, y)\n"
1016 "#define BOOST_FOREACH(x, y)\n"
1017 "#define UNKNOWN_FOREACH(x, y)\n");
1018
1019 // Not as function-like macros.
1020 verifyFormat("#define foreach (x, y)\n"
1021 "#define Q_FOREACH (x, y)\n"
1022 "#define BOOST_FOREACH (x, y)\n"
1023 "#define UNKNOWN_FOREACH (x, y)\n");
1024
1025 // handle microsoft non standard extension
1026 verifyFormat("for each (char c in x->MyStringProperty)");
1027 }
1028
TEST_F(FormatTest,FormatsWhileLoop)1029 TEST_F(FormatTest, FormatsWhileLoop) {
1030 verifyFormat("while (true) {\n}");
1031 verifyFormat("while (true)\n"
1032 " f();");
1033 verifyFormat("while () {\n}");
1034 verifyFormat("while () {\n"
1035 " f();\n"
1036 "}");
1037 }
1038
TEST_F(FormatTest,FormatsDoWhile)1039 TEST_F(FormatTest, FormatsDoWhile) {
1040 verifyFormat("do {\n"
1041 " do_something();\n"
1042 "} while (something());");
1043 verifyFormat("do\n"
1044 " do_something();\n"
1045 "while (something());");
1046 }
1047
TEST_F(FormatTest,FormatsSwitchStatement)1048 TEST_F(FormatTest, FormatsSwitchStatement) {
1049 verifyFormat("switch (x) {\n"
1050 "case 1:\n"
1051 " f();\n"
1052 " break;\n"
1053 "case kFoo:\n"
1054 "case ns::kBar:\n"
1055 "case kBaz:\n"
1056 " break;\n"
1057 "default:\n"
1058 " g();\n"
1059 " break;\n"
1060 "}");
1061 verifyFormat("switch (x) {\n"
1062 "case 1: {\n"
1063 " f();\n"
1064 " break;\n"
1065 "}\n"
1066 "case 2: {\n"
1067 " break;\n"
1068 "}\n"
1069 "}");
1070 verifyFormat("switch (x) {\n"
1071 "case 1: {\n"
1072 " f();\n"
1073 " {\n"
1074 " g();\n"
1075 " h();\n"
1076 " }\n"
1077 " break;\n"
1078 "}\n"
1079 "}");
1080 verifyFormat("switch (x) {\n"
1081 "case 1: {\n"
1082 " f();\n"
1083 " if (foo) {\n"
1084 " g();\n"
1085 " h();\n"
1086 " }\n"
1087 " break;\n"
1088 "}\n"
1089 "}");
1090 verifyFormat("switch (x) {\n"
1091 "case 1: {\n"
1092 " f();\n"
1093 " g();\n"
1094 "} break;\n"
1095 "}");
1096 verifyFormat("switch (test)\n"
1097 " ;");
1098 verifyFormat("switch (x) {\n"
1099 "default: {\n"
1100 " // Do nothing.\n"
1101 "}\n"
1102 "}");
1103 verifyFormat("switch (x) {\n"
1104 "// comment\n"
1105 "// if 1, do f()\n"
1106 "case 1:\n"
1107 " f();\n"
1108 "}");
1109 verifyFormat("switch (x) {\n"
1110 "case 1:\n"
1111 " // Do amazing stuff\n"
1112 " {\n"
1113 " f();\n"
1114 " g();\n"
1115 " }\n"
1116 " break;\n"
1117 "}");
1118 verifyFormat("#define A \\\n"
1119 " switch (x) { \\\n"
1120 " case a: \\\n"
1121 " foo = b; \\\n"
1122 " }",
1123 getLLVMStyleWithColumns(20));
1124 verifyFormat("#define OPERATION_CASE(name) \\\n"
1125 " case OP_name: \\\n"
1126 " return operations::Operation##name\n",
1127 getLLVMStyleWithColumns(40));
1128 verifyFormat("switch (x) {\n"
1129 "case 1:;\n"
1130 "default:;\n"
1131 " int i;\n"
1132 "}");
1133
1134 verifyGoogleFormat("switch (x) {\n"
1135 " case 1:\n"
1136 " f();\n"
1137 " break;\n"
1138 " case kFoo:\n"
1139 " case ns::kBar:\n"
1140 " case kBaz:\n"
1141 " break;\n"
1142 " default:\n"
1143 " g();\n"
1144 " break;\n"
1145 "}");
1146 verifyGoogleFormat("switch (x) {\n"
1147 " case 1: {\n"
1148 " f();\n"
1149 " break;\n"
1150 " }\n"
1151 "}");
1152 verifyGoogleFormat("switch (test)\n"
1153 " ;");
1154
1155 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
1156 " case OP_name: \\\n"
1157 " return operations::Operation##name\n");
1158 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
1159 " // Get the correction operation class.\n"
1160 " switch (OpCode) {\n"
1161 " CASE(Add);\n"
1162 " CASE(Subtract);\n"
1163 " default:\n"
1164 " return operations::Unknown;\n"
1165 " }\n"
1166 "#undef OPERATION_CASE\n"
1167 "}");
1168 verifyFormat("DEBUG({\n"
1169 " switch (x) {\n"
1170 " case A:\n"
1171 " f();\n"
1172 " break;\n"
1173 " // fallthrough\n"
1174 " case B:\n"
1175 " g();\n"
1176 " break;\n"
1177 " }\n"
1178 "});");
1179 EXPECT_EQ("DEBUG({\n"
1180 " switch (x) {\n"
1181 " case A:\n"
1182 " f();\n"
1183 " break;\n"
1184 " // On B:\n"
1185 " case B:\n"
1186 " g();\n"
1187 " break;\n"
1188 " }\n"
1189 "});",
1190 format("DEBUG({\n"
1191 " switch (x) {\n"
1192 " case A:\n"
1193 " f();\n"
1194 " break;\n"
1195 " // On B:\n"
1196 " case B:\n"
1197 " g();\n"
1198 " break;\n"
1199 " }\n"
1200 "});",
1201 getLLVMStyle()));
1202 EXPECT_EQ("switch (n) {\n"
1203 "case 0: {\n"
1204 " return false;\n"
1205 "}\n"
1206 "default: {\n"
1207 " return true;\n"
1208 "}\n"
1209 "}",
1210 format("switch (n)\n"
1211 "{\n"
1212 "case 0: {\n"
1213 " return false;\n"
1214 "}\n"
1215 "default: {\n"
1216 " return true;\n"
1217 "}\n"
1218 "}",
1219 getLLVMStyle()));
1220 verifyFormat("switch (a) {\n"
1221 "case (b):\n"
1222 " return;\n"
1223 "}");
1224
1225 verifyFormat("switch (a) {\n"
1226 "case some_namespace::\n"
1227 " some_constant:\n"
1228 " return;\n"
1229 "}",
1230 getLLVMStyleWithColumns(34));
1231
1232 FormatStyle Style = getLLVMStyle();
1233 Style.IndentCaseLabels = true;
1234 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1235 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1236 Style.BraceWrapping.AfterCaseLabel = true;
1237 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1238 EXPECT_EQ("switch (n)\n"
1239 "{\n"
1240 " case 0:\n"
1241 " {\n"
1242 " return false;\n"
1243 " }\n"
1244 " default:\n"
1245 " {\n"
1246 " return true;\n"
1247 " }\n"
1248 "}",
1249 format("switch (n) {\n"
1250 " case 0: {\n"
1251 " return false;\n"
1252 " }\n"
1253 " default: {\n"
1254 " return true;\n"
1255 " }\n"
1256 "}",
1257 Style));
1258 Style.BraceWrapping.AfterCaseLabel = false;
1259 EXPECT_EQ("switch (n)\n"
1260 "{\n"
1261 " case 0: {\n"
1262 " return false;\n"
1263 " }\n"
1264 " default: {\n"
1265 " return true;\n"
1266 " }\n"
1267 "}",
1268 format("switch (n) {\n"
1269 " case 0:\n"
1270 " {\n"
1271 " return false;\n"
1272 " }\n"
1273 " default:\n"
1274 " {\n"
1275 " return true;\n"
1276 " }\n"
1277 "}",
1278 Style));
1279 Style.IndentCaseLabels = false;
1280 Style.IndentCaseBlocks = true;
1281 EXPECT_EQ("switch (n)\n"
1282 "{\n"
1283 "case 0:\n"
1284 " {\n"
1285 " return false;\n"
1286 " }\n"
1287 "case 1:\n"
1288 " break;\n"
1289 "default:\n"
1290 " {\n"
1291 " return true;\n"
1292 " }\n"
1293 "}",
1294 format("switch (n) {\n"
1295 "case 0: {\n"
1296 " return false;\n"
1297 "}\n"
1298 "case 1:\n"
1299 " break;\n"
1300 "default: {\n"
1301 " return true;\n"
1302 "}\n"
1303 "}",
1304 Style));
1305 Style.IndentCaseLabels = true;
1306 Style.IndentCaseBlocks = true;
1307 EXPECT_EQ("switch (n)\n"
1308 "{\n"
1309 " case 0:\n"
1310 " {\n"
1311 " return false;\n"
1312 " }\n"
1313 " case 1:\n"
1314 " break;\n"
1315 " default:\n"
1316 " {\n"
1317 " return true;\n"
1318 " }\n"
1319 "}",
1320 format("switch (n) {\n"
1321 "case 0: {\n"
1322 " return false;\n"
1323 "}\n"
1324 "case 1:\n"
1325 " break;\n"
1326 "default: {\n"
1327 " return true;\n"
1328 "}\n"
1329 "}",
1330 Style));
1331 }
1332
TEST_F(FormatTest,CaseRanges)1333 TEST_F(FormatTest, CaseRanges) {
1334 verifyFormat("switch (x) {\n"
1335 "case 'A' ... 'Z':\n"
1336 "case 1 ... 5:\n"
1337 "case a ... b:\n"
1338 " break;\n"
1339 "}");
1340 }
1341
TEST_F(FormatTest,ShortEnums)1342 TEST_F(FormatTest, ShortEnums) {
1343 FormatStyle Style = getLLVMStyle();
1344 Style.AllowShortEnumsOnASingleLine = true;
1345 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
1346 Style.AllowShortEnumsOnASingleLine = false;
1347 verifyFormat("enum\n"
1348 "{\n"
1349 " A,\n"
1350 " B,\n"
1351 " C\n"
1352 "} ShortEnum1, ShortEnum2;",
1353 Style);
1354 }
1355
TEST_F(FormatTest,ShortCaseLabels)1356 TEST_F(FormatTest, ShortCaseLabels) {
1357 FormatStyle Style = getLLVMStyle();
1358 Style.AllowShortCaseLabelsOnASingleLine = true;
1359 verifyFormat("switch (a) {\n"
1360 "case 1: x = 1; break;\n"
1361 "case 2: return;\n"
1362 "case 3:\n"
1363 "case 4:\n"
1364 "case 5: return;\n"
1365 "case 6: // comment\n"
1366 " return;\n"
1367 "case 7:\n"
1368 " // comment\n"
1369 " return;\n"
1370 "case 8:\n"
1371 " x = 8; // comment\n"
1372 " break;\n"
1373 "default: y = 1; break;\n"
1374 "}",
1375 Style);
1376 verifyFormat("switch (a) {\n"
1377 "case 0: return; // comment\n"
1378 "case 1: break; // comment\n"
1379 "case 2: return;\n"
1380 "// comment\n"
1381 "case 3: return;\n"
1382 "// comment 1\n"
1383 "// comment 2\n"
1384 "// comment 3\n"
1385 "case 4: break; /* comment */\n"
1386 "case 5:\n"
1387 " // comment\n"
1388 " break;\n"
1389 "case 6: /* comment */ x = 1; break;\n"
1390 "case 7: x = /* comment */ 1; break;\n"
1391 "case 8:\n"
1392 " x = 1; /* comment */\n"
1393 " break;\n"
1394 "case 9:\n"
1395 " break; // comment line 1\n"
1396 " // comment line 2\n"
1397 "}",
1398 Style);
1399 EXPECT_EQ("switch (a) {\n"
1400 "case 1:\n"
1401 " x = 8;\n"
1402 " // fall through\n"
1403 "case 2: x = 8;\n"
1404 "// comment\n"
1405 "case 3:\n"
1406 " return; /* comment line 1\n"
1407 " * comment line 2 */\n"
1408 "case 4: i = 8;\n"
1409 "// something else\n"
1410 "#if FOO\n"
1411 "case 5: break;\n"
1412 "#endif\n"
1413 "}",
1414 format("switch (a) {\n"
1415 "case 1: x = 8;\n"
1416 " // fall through\n"
1417 "case 2:\n"
1418 " x = 8;\n"
1419 "// comment\n"
1420 "case 3:\n"
1421 " return; /* comment line 1\n"
1422 " * comment line 2 */\n"
1423 "case 4:\n"
1424 " i = 8;\n"
1425 "// something else\n"
1426 "#if FOO\n"
1427 "case 5: break;\n"
1428 "#endif\n"
1429 "}",
1430 Style));
1431 EXPECT_EQ("switch (a) {\n"
1432 "case 0:\n"
1433 " return; // long long long long long long long long long long "
1434 "long long comment\n"
1435 " // line\n"
1436 "}",
1437 format("switch (a) {\n"
1438 "case 0: return; // long long long long long long long long "
1439 "long long long long comment line\n"
1440 "}",
1441 Style));
1442 EXPECT_EQ("switch (a) {\n"
1443 "case 0:\n"
1444 " return; /* long long long long long long long long long long "
1445 "long long comment\n"
1446 " line */\n"
1447 "}",
1448 format("switch (a) {\n"
1449 "case 0: return; /* long long long long long long long long "
1450 "long long long long comment line */\n"
1451 "}",
1452 Style));
1453 verifyFormat("switch (a) {\n"
1454 "#if FOO\n"
1455 "case 0: return 0;\n"
1456 "#endif\n"
1457 "}",
1458 Style);
1459 verifyFormat("switch (a) {\n"
1460 "case 1: {\n"
1461 "}\n"
1462 "case 2: {\n"
1463 " return;\n"
1464 "}\n"
1465 "case 3: {\n"
1466 " x = 1;\n"
1467 " return;\n"
1468 "}\n"
1469 "case 4:\n"
1470 " if (x)\n"
1471 " return;\n"
1472 "}",
1473 Style);
1474 Style.ColumnLimit = 21;
1475 verifyFormat("switch (a) {\n"
1476 "case 1: x = 1; break;\n"
1477 "case 2: return;\n"
1478 "case 3:\n"
1479 "case 4:\n"
1480 "case 5: return;\n"
1481 "default:\n"
1482 " y = 1;\n"
1483 " break;\n"
1484 "}",
1485 Style);
1486 Style.ColumnLimit = 80;
1487 Style.AllowShortCaseLabelsOnASingleLine = false;
1488 Style.IndentCaseLabels = true;
1489 EXPECT_EQ("switch (n) {\n"
1490 " default /*comments*/:\n"
1491 " return true;\n"
1492 " case 0:\n"
1493 " return false;\n"
1494 "}",
1495 format("switch (n) {\n"
1496 "default/*comments*/:\n"
1497 " return true;\n"
1498 "case 0:\n"
1499 " return false;\n"
1500 "}",
1501 Style));
1502 Style.AllowShortCaseLabelsOnASingleLine = true;
1503 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1504 Style.BraceWrapping.AfterCaseLabel = true;
1505 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1506 EXPECT_EQ("switch (n)\n"
1507 "{\n"
1508 " case 0:\n"
1509 " {\n"
1510 " return false;\n"
1511 " }\n"
1512 " default:\n"
1513 " {\n"
1514 " return true;\n"
1515 " }\n"
1516 "}",
1517 format("switch (n) {\n"
1518 " case 0: {\n"
1519 " return false;\n"
1520 " }\n"
1521 " default:\n"
1522 " {\n"
1523 " return true;\n"
1524 " }\n"
1525 "}",
1526 Style));
1527 }
1528
TEST_F(FormatTest,FormatsLabels)1529 TEST_F(FormatTest, FormatsLabels) {
1530 verifyFormat("void f() {\n"
1531 " some_code();\n"
1532 "test_label:\n"
1533 " some_other_code();\n"
1534 " {\n"
1535 " some_more_code();\n"
1536 " another_label:\n"
1537 " some_more_code();\n"
1538 " }\n"
1539 "}");
1540 verifyFormat("{\n"
1541 " some_code();\n"
1542 "test_label:\n"
1543 " some_other_code();\n"
1544 "}");
1545 verifyFormat("{\n"
1546 " some_code();\n"
1547 "test_label:;\n"
1548 " int i = 0;\n"
1549 "}");
1550 FormatStyle Style = getLLVMStyle();
1551 Style.IndentGotoLabels = false;
1552 verifyFormat("void f() {\n"
1553 " some_code();\n"
1554 "test_label:\n"
1555 " some_other_code();\n"
1556 " {\n"
1557 " some_more_code();\n"
1558 "another_label:\n"
1559 " some_more_code();\n"
1560 " }\n"
1561 "}",
1562 Style);
1563 verifyFormat("{\n"
1564 " some_code();\n"
1565 "test_label:\n"
1566 " some_other_code();\n"
1567 "}",
1568 Style);
1569 verifyFormat("{\n"
1570 " some_code();\n"
1571 "test_label:;\n"
1572 " int i = 0;\n"
1573 "}");
1574 }
1575
TEST_F(FormatTest,MultiLineControlStatements)1576 TEST_F(FormatTest, MultiLineControlStatements) {
1577 FormatStyle Style = getLLVMStyle();
1578 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1579 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
1580 Style.ColumnLimit = 20;
1581 // Short lines should keep opening brace on same line.
1582 EXPECT_EQ("if (foo) {\n"
1583 " bar();\n"
1584 "}",
1585 format("if(foo){bar();}", Style));
1586 EXPECT_EQ("if (foo) {\n"
1587 " bar();\n"
1588 "} else {\n"
1589 " baz();\n"
1590 "}",
1591 format("if(foo){bar();}else{baz();}", Style));
1592 EXPECT_EQ("if (foo && bar) {\n"
1593 " baz();\n"
1594 "}",
1595 format("if(foo&&bar){baz();}", Style));
1596 EXPECT_EQ("if (foo) {\n"
1597 " bar();\n"
1598 "} else if (baz) {\n"
1599 " quux();\n"
1600 "}",
1601 format("if(foo){bar();}else if(baz){quux();}", Style));
1602 EXPECT_EQ(
1603 "if (foo) {\n"
1604 " bar();\n"
1605 "} else if (baz) {\n"
1606 " quux();\n"
1607 "} else {\n"
1608 " foobar();\n"
1609 "}",
1610 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
1611 EXPECT_EQ("for (;;) {\n"
1612 " foo();\n"
1613 "}",
1614 format("for(;;){foo();}"));
1615 EXPECT_EQ("while (1) {\n"
1616 " foo();\n"
1617 "}",
1618 format("while(1){foo();}", Style));
1619 EXPECT_EQ("switch (foo) {\n"
1620 "case bar:\n"
1621 " return;\n"
1622 "}",
1623 format("switch(foo){case bar:return;}", Style));
1624 EXPECT_EQ("try {\n"
1625 " foo();\n"
1626 "} catch (...) {\n"
1627 " bar();\n"
1628 "}",
1629 format("try{foo();}catch(...){bar();}", Style));
1630 EXPECT_EQ("do {\n"
1631 " foo();\n"
1632 "} while (bar &&\n"
1633 " baz);",
1634 format("do{foo();}while(bar&&baz);", Style));
1635 // Long lines should put opening brace on new line.
1636 EXPECT_EQ("if (foo && bar &&\n"
1637 " baz)\n"
1638 "{\n"
1639 " quux();\n"
1640 "}",
1641 format("if(foo&&bar&&baz){quux();}", Style));
1642 EXPECT_EQ("if (foo && bar &&\n"
1643 " baz)\n"
1644 "{\n"
1645 " quux();\n"
1646 "}",
1647 format("if (foo && bar &&\n"
1648 " baz) {\n"
1649 " quux();\n"
1650 "}",
1651 Style));
1652 EXPECT_EQ("if (foo) {\n"
1653 " bar();\n"
1654 "} else if (baz ||\n"
1655 " quux)\n"
1656 "{\n"
1657 " foobar();\n"
1658 "}",
1659 format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
1660 EXPECT_EQ(
1661 "if (foo) {\n"
1662 " bar();\n"
1663 "} else if (baz ||\n"
1664 " quux)\n"
1665 "{\n"
1666 " foobar();\n"
1667 "} else {\n"
1668 " barbaz();\n"
1669 "}",
1670 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1671 Style));
1672 EXPECT_EQ("for (int i = 0;\n"
1673 " i < 10; ++i)\n"
1674 "{\n"
1675 " foo();\n"
1676 "}",
1677 format("for(int i=0;i<10;++i){foo();}", Style));
1678 EXPECT_EQ("foreach (int i,\n"
1679 " list)\n"
1680 "{\n"
1681 " foo();\n"
1682 "}",
1683 format("foreach(int i, list){foo();}", Style));
1684 Style.ColumnLimit =
1685 40; // to concentrate at brace wrapping, not line wrap due to column limit
1686 EXPECT_EQ("foreach (int i, list) {\n"
1687 " foo();\n"
1688 "}",
1689 format("foreach(int i, list){foo();}", Style));
1690 Style.ColumnLimit =
1691 20; // to concentrate at brace wrapping, not line wrap due to column limit
1692 EXPECT_EQ("while (foo || bar ||\n"
1693 " baz)\n"
1694 "{\n"
1695 " quux();\n"
1696 "}",
1697 format("while(foo||bar||baz){quux();}", Style));
1698 EXPECT_EQ("switch (\n"
1699 " foo = barbaz)\n"
1700 "{\n"
1701 "case quux:\n"
1702 " return;\n"
1703 "}",
1704 format("switch(foo=barbaz){case quux:return;}", Style));
1705 EXPECT_EQ("try {\n"
1706 " foo();\n"
1707 "} catch (\n"
1708 " Exception &bar)\n"
1709 "{\n"
1710 " baz();\n"
1711 "}",
1712 format("try{foo();}catch(Exception&bar){baz();}", Style));
1713 Style.ColumnLimit =
1714 40; // to concentrate at brace wrapping, not line wrap due to column limit
1715 EXPECT_EQ("try {\n"
1716 " foo();\n"
1717 "} catch (Exception &bar) {\n"
1718 " baz();\n"
1719 "}",
1720 format("try{foo();}catch(Exception&bar){baz();}", Style));
1721 Style.ColumnLimit =
1722 20; // to concentrate at brace wrapping, not line wrap due to column limit
1723
1724 Style.BraceWrapping.BeforeElse = true;
1725 EXPECT_EQ(
1726 "if (foo) {\n"
1727 " bar();\n"
1728 "}\n"
1729 "else if (baz ||\n"
1730 " quux)\n"
1731 "{\n"
1732 " foobar();\n"
1733 "}\n"
1734 "else {\n"
1735 " barbaz();\n"
1736 "}",
1737 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1738 Style));
1739
1740 Style.BraceWrapping.BeforeCatch = true;
1741 EXPECT_EQ("try {\n"
1742 " foo();\n"
1743 "}\n"
1744 "catch (...) {\n"
1745 " baz();\n"
1746 "}",
1747 format("try{foo();}catch(...){baz();}", Style));
1748 }
1749
TEST_F(FormatTest,BeforeWhile)1750 TEST_F(FormatTest, BeforeWhile) {
1751 FormatStyle Style = getLLVMStyle();
1752 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1753
1754 verifyFormat("do {\n"
1755 " foo();\n"
1756 "} while (1);",
1757 Style);
1758 Style.BraceWrapping.BeforeWhile = true;
1759 verifyFormat("do {\n"
1760 " foo();\n"
1761 "}\n"
1762 "while (1);",
1763 Style);
1764 }
1765
1766 //===----------------------------------------------------------------------===//
1767 // Tests for classes, namespaces, etc.
1768 //===----------------------------------------------------------------------===//
1769
TEST_F(FormatTest,DoesNotBreakSemiAfterClassDecl)1770 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1771 verifyFormat("class A {};");
1772 }
1773
TEST_F(FormatTest,UnderstandsAccessSpecifiers)1774 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1775 verifyFormat("class A {\n"
1776 "public:\n"
1777 "public: // comment\n"
1778 "protected:\n"
1779 "private:\n"
1780 " void f() {}\n"
1781 "};");
1782 verifyFormat("export class A {\n"
1783 "public:\n"
1784 "public: // comment\n"
1785 "protected:\n"
1786 "private:\n"
1787 " void f() {}\n"
1788 "};");
1789 verifyGoogleFormat("class A {\n"
1790 " public:\n"
1791 " protected:\n"
1792 " private:\n"
1793 " void f() {}\n"
1794 "};");
1795 verifyGoogleFormat("export class A {\n"
1796 " public:\n"
1797 " protected:\n"
1798 " private:\n"
1799 " void f() {}\n"
1800 "};");
1801 verifyFormat("class A {\n"
1802 "public slots:\n"
1803 " void f1() {}\n"
1804 "public Q_SLOTS:\n"
1805 " void f2() {}\n"
1806 "protected slots:\n"
1807 " void f3() {}\n"
1808 "protected Q_SLOTS:\n"
1809 " void f4() {}\n"
1810 "private slots:\n"
1811 " void f5() {}\n"
1812 "private Q_SLOTS:\n"
1813 " void f6() {}\n"
1814 "signals:\n"
1815 " void g1();\n"
1816 "Q_SIGNALS:\n"
1817 " void g2();\n"
1818 "};");
1819
1820 // Don't interpret 'signals' the wrong way.
1821 verifyFormat("signals.set();");
1822 verifyFormat("for (Signals signals : f()) {\n}");
1823 verifyFormat("{\n"
1824 " signals.set(); // This needs indentation.\n"
1825 "}");
1826 verifyFormat("void f() {\n"
1827 "label:\n"
1828 " signals.baz();\n"
1829 "}");
1830 }
1831
TEST_F(FormatTest,SeparatesLogicalBlocks)1832 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1833 EXPECT_EQ("class A {\n"
1834 "public:\n"
1835 " void f();\n"
1836 "\n"
1837 "private:\n"
1838 " void g() {}\n"
1839 " // test\n"
1840 "protected:\n"
1841 " int h;\n"
1842 "};",
1843 format("class A {\n"
1844 "public:\n"
1845 "void f();\n"
1846 "private:\n"
1847 "void g() {}\n"
1848 "// test\n"
1849 "protected:\n"
1850 "int h;\n"
1851 "};"));
1852 EXPECT_EQ("class A {\n"
1853 "protected:\n"
1854 "public:\n"
1855 " void f();\n"
1856 "};",
1857 format("class A {\n"
1858 "protected:\n"
1859 "\n"
1860 "public:\n"
1861 "\n"
1862 " void f();\n"
1863 "};"));
1864
1865 // Even ensure proper spacing inside macros.
1866 EXPECT_EQ("#define B \\\n"
1867 " class A { \\\n"
1868 " protected: \\\n"
1869 " public: \\\n"
1870 " void f(); \\\n"
1871 " };",
1872 format("#define B \\\n"
1873 " class A { \\\n"
1874 " protected: \\\n"
1875 " \\\n"
1876 " public: \\\n"
1877 " \\\n"
1878 " void f(); \\\n"
1879 " };",
1880 getGoogleStyle()));
1881 // But don't remove empty lines after macros ending in access specifiers.
1882 EXPECT_EQ("#define A private:\n"
1883 "\n"
1884 "int i;",
1885 format("#define A private:\n"
1886 "\n"
1887 "int i;"));
1888 }
1889
TEST_F(FormatTest,FormatsClasses)1890 TEST_F(FormatTest, FormatsClasses) {
1891 verifyFormat("class A : public B {};");
1892 verifyFormat("class A : public ::B {};");
1893
1894 verifyFormat(
1895 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1896 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1897 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1898 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1899 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1900 verifyFormat(
1901 "class A : public B, public C, public D, public E, public F {};");
1902 verifyFormat("class AAAAAAAAAAAA : public B,\n"
1903 " public C,\n"
1904 " public D,\n"
1905 " public E,\n"
1906 " public F,\n"
1907 " public G {};");
1908
1909 verifyFormat("class\n"
1910 " ReallyReallyLongClassName {\n"
1911 " int i;\n"
1912 "};",
1913 getLLVMStyleWithColumns(32));
1914 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1915 " aaaaaaaaaaaaaaaa> {};");
1916 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1917 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1918 " aaaaaaaaaaaaaaaaaaaaaa> {};");
1919 verifyFormat("template <class R, class C>\n"
1920 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1921 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1922 verifyFormat("class ::A::B {};");
1923 }
1924
TEST_F(FormatTest,BreakInheritanceStyle)1925 TEST_F(FormatTest, BreakInheritanceStyle) {
1926 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
1927 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
1928 FormatStyle::BILS_BeforeComma;
1929 verifyFormat("class MyClass : public X {};",
1930 StyleWithInheritanceBreakBeforeComma);
1931 verifyFormat("class MyClass\n"
1932 " : public X\n"
1933 " , public Y {};",
1934 StyleWithInheritanceBreakBeforeComma);
1935 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
1936 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
1937 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1938 StyleWithInheritanceBreakBeforeComma);
1939 verifyFormat("struct aaaaaaaaaaaaa\n"
1940 " : public aaaaaaaaaaaaaaaaaaa< // break\n"
1941 " aaaaaaaaaaaaaaaa> {};",
1942 StyleWithInheritanceBreakBeforeComma);
1943
1944 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
1945 StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
1946 FormatStyle::BILS_AfterColon;
1947 verifyFormat("class MyClass : public X {};",
1948 StyleWithInheritanceBreakAfterColon);
1949 verifyFormat("class MyClass : public X, public Y {};",
1950 StyleWithInheritanceBreakAfterColon);
1951 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
1952 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1953 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1954 StyleWithInheritanceBreakAfterColon);
1955 verifyFormat("struct aaaaaaaaaaaaa :\n"
1956 " public aaaaaaaaaaaaaaaaaaa< // break\n"
1957 " aaaaaaaaaaaaaaaa> {};",
1958 StyleWithInheritanceBreakAfterColon);
1959 }
1960
TEST_F(FormatTest,FormatsVariableDeclarationsAfterStructOrClass)1961 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1962 verifyFormat("class A {\n} a, b;");
1963 verifyFormat("struct A {\n} a, b;");
1964 verifyFormat("union A {\n} a;");
1965 }
1966
TEST_F(FormatTest,FormatsEnum)1967 TEST_F(FormatTest, FormatsEnum) {
1968 verifyFormat("enum {\n"
1969 " Zero,\n"
1970 " One = 1,\n"
1971 " Two = One + 1,\n"
1972 " Three = (One + Two),\n"
1973 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
1974 " Five = (One, Two, Three, Four, 5)\n"
1975 "};");
1976 verifyGoogleFormat("enum {\n"
1977 " Zero,\n"
1978 " One = 1,\n"
1979 " Two = One + 1,\n"
1980 " Three = (One + Two),\n"
1981 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
1982 " Five = (One, Two, Three, Four, 5)\n"
1983 "};");
1984 verifyFormat("enum Enum {};");
1985 verifyFormat("enum {};");
1986 verifyFormat("enum X E {} d;");
1987 verifyFormat("enum __attribute__((...)) E {} d;");
1988 verifyFormat("enum __declspec__((...)) E {} d;");
1989 verifyFormat("enum {\n"
1990 " Bar = Foo<int, int>::value\n"
1991 "};",
1992 getLLVMStyleWithColumns(30));
1993
1994 verifyFormat("enum ShortEnum { A, B, C };");
1995 verifyGoogleFormat("enum ShortEnum { A, B, C };");
1996
1997 EXPECT_EQ("enum KeepEmptyLines {\n"
1998 " ONE,\n"
1999 "\n"
2000 " TWO,\n"
2001 "\n"
2002 " THREE\n"
2003 "}",
2004 format("enum KeepEmptyLines {\n"
2005 " ONE,\n"
2006 "\n"
2007 " TWO,\n"
2008 "\n"
2009 "\n"
2010 " THREE\n"
2011 "}"));
2012 verifyFormat("enum E { // comment\n"
2013 " ONE,\n"
2014 " TWO\n"
2015 "};\n"
2016 "int i;");
2017
2018 FormatStyle EightIndent = getLLVMStyle();
2019 EightIndent.IndentWidth = 8;
2020 verifyFormat("enum {\n"
2021 " VOID,\n"
2022 " CHAR,\n"
2023 " SHORT,\n"
2024 " INT,\n"
2025 " LONG,\n"
2026 " SIGNED,\n"
2027 " UNSIGNED,\n"
2028 " BOOL,\n"
2029 " FLOAT,\n"
2030 " DOUBLE,\n"
2031 " COMPLEX\n"
2032 "};",
2033 EightIndent);
2034
2035 // Not enums.
2036 verifyFormat("enum X f() {\n"
2037 " a();\n"
2038 " return 42;\n"
2039 "}");
2040 verifyFormat("enum X Type::f() {\n"
2041 " a();\n"
2042 " return 42;\n"
2043 "}");
2044 verifyFormat("enum ::X f() {\n"
2045 " a();\n"
2046 " return 42;\n"
2047 "}");
2048 verifyFormat("enum ns::X f() {\n"
2049 " a();\n"
2050 " return 42;\n"
2051 "}");
2052 }
2053
TEST_F(FormatTest,FormatsEnumsWithErrors)2054 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2055 verifyFormat("enum Type {\n"
2056 " One = 0; // These semicolons should be commas.\n"
2057 " Two = 1;\n"
2058 "};");
2059 verifyFormat("namespace n {\n"
2060 "enum Type {\n"
2061 " One,\n"
2062 " Two, // missing };\n"
2063 " int i;\n"
2064 "}\n"
2065 "void g() {}");
2066 }
2067
TEST_F(FormatTest,FormatsEnumStruct)2068 TEST_F(FormatTest, FormatsEnumStruct) {
2069 verifyFormat("enum struct {\n"
2070 " Zero,\n"
2071 " One = 1,\n"
2072 " Two = One + 1,\n"
2073 " Three = (One + Two),\n"
2074 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
2075 " Five = (One, Two, Three, Four, 5)\n"
2076 "};");
2077 verifyFormat("enum struct Enum {};");
2078 verifyFormat("enum struct {};");
2079 verifyFormat("enum struct X E {} d;");
2080 verifyFormat("enum struct __attribute__((...)) E {} d;");
2081 verifyFormat("enum struct __declspec__((...)) E {} d;");
2082 verifyFormat("enum struct X f() {\n a();\n return 42;\n}");
2083 }
2084
TEST_F(FormatTest,FormatsEnumClass)2085 TEST_F(FormatTest, FormatsEnumClass) {
2086 verifyFormat("enum class {\n"
2087 " Zero,\n"
2088 " One = 1,\n"
2089 " Two = One + 1,\n"
2090 " Three = (One + Two),\n"
2091 " Four = (Zero && (One ^ Two)) | (One << Two),\n"
2092 " Five = (One, Two, Three, Four, 5)\n"
2093 "};");
2094 verifyFormat("enum class Enum {};");
2095 verifyFormat("enum class {};");
2096 verifyFormat("enum class X E {} d;");
2097 verifyFormat("enum class __attribute__((...)) E {} d;");
2098 verifyFormat("enum class __declspec__((...)) E {} d;");
2099 verifyFormat("enum class X f() {\n a();\n return 42;\n}");
2100 }
2101
TEST_F(FormatTest,FormatsEnumTypes)2102 TEST_F(FormatTest, FormatsEnumTypes) {
2103 verifyFormat("enum X : int {\n"
2104 " A, // Force multiple lines.\n"
2105 " B\n"
2106 "};");
2107 verifyFormat("enum X : int { A, B };");
2108 verifyFormat("enum X : std::uint32_t { A, B };");
2109 }
2110
TEST_F(FormatTest,FormatsTypedefEnum)2111 TEST_F(FormatTest, FormatsTypedefEnum) {
2112 FormatStyle Style = getLLVMStyle();
2113 Style.ColumnLimit = 40;
2114 verifyFormat("typedef enum {} EmptyEnum;");
2115 verifyFormat("typedef enum { A, B, C } ShortEnum;");
2116 verifyFormat("typedef enum {\n"
2117 " ZERO = 0,\n"
2118 " ONE = 1,\n"
2119 " TWO = 2,\n"
2120 " THREE = 3\n"
2121 "} LongEnum;",
2122 Style);
2123 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2124 Style.BraceWrapping.AfterEnum = true;
2125 verifyFormat("typedef enum {} EmptyEnum;");
2126 verifyFormat("typedef enum { A, B, C } ShortEnum;");
2127 verifyFormat("typedef enum\n"
2128 "{\n"
2129 " ZERO = 0,\n"
2130 " ONE = 1,\n"
2131 " TWO = 2,\n"
2132 " THREE = 3\n"
2133 "} LongEnum;",
2134 Style);
2135 }
2136
TEST_F(FormatTest,FormatsNSEnums)2137 TEST_F(FormatTest, FormatsNSEnums) {
2138 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2139 verifyGoogleFormat(
2140 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
2141 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2142 " // Information about someDecentlyLongValue.\n"
2143 " someDecentlyLongValue,\n"
2144 " // Information about anotherDecentlyLongValue.\n"
2145 " anotherDecentlyLongValue,\n"
2146 " // Information about aThirdDecentlyLongValue.\n"
2147 " aThirdDecentlyLongValue\n"
2148 "};");
2149 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
2150 " // Information about someDecentlyLongValue.\n"
2151 " someDecentlyLongValue,\n"
2152 " // Information about anotherDecentlyLongValue.\n"
2153 " anotherDecentlyLongValue,\n"
2154 " // Information about aThirdDecentlyLongValue.\n"
2155 " aThirdDecentlyLongValue\n"
2156 "};");
2157 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2158 " a = 1,\n"
2159 " b = 2,\n"
2160 " c = 3,\n"
2161 "};");
2162 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2163 " a = 1,\n"
2164 " b = 2,\n"
2165 " c = 3,\n"
2166 "};");
2167 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
2168 " a = 1,\n"
2169 " b = 2,\n"
2170 " c = 3,\n"
2171 "};");
2172 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2173 " a = 1,\n"
2174 " b = 2,\n"
2175 " c = 3,\n"
2176 "};");
2177 }
2178
TEST_F(FormatTest,FormatsBitfields)2179 TEST_F(FormatTest, FormatsBitfields) {
2180 verifyFormat("struct Bitfields {\n"
2181 " unsigned sClass : 8;\n"
2182 " unsigned ValueKind : 2;\n"
2183 "};");
2184 verifyFormat("struct A {\n"
2185 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2186 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2187 "};");
2188 verifyFormat("struct MyStruct {\n"
2189 " uchar data;\n"
2190 " uchar : 8;\n"
2191 " uchar : 8;\n"
2192 " uchar other;\n"
2193 "};");
2194 FormatStyle Style = getLLVMStyle();
2195 Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
2196 verifyFormat("struct Bitfields {\n"
2197 " unsigned sClass:8;\n"
2198 " unsigned ValueKind:2;\n"
2199 " uchar other;\n"
2200 "};",
2201 Style);
2202 verifyFormat("struct A {\n"
2203 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
2204 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
2205 "};",
2206 Style);
2207 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
2208 verifyFormat("struct Bitfields {\n"
2209 " unsigned sClass :8;\n"
2210 " unsigned ValueKind :2;\n"
2211 " uchar other;\n"
2212 "};",
2213 Style);
2214 Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
2215 verifyFormat("struct Bitfields {\n"
2216 " unsigned sClass: 8;\n"
2217 " unsigned ValueKind: 2;\n"
2218 " uchar other;\n"
2219 "};",
2220 Style);
2221 }
2222
TEST_F(FormatTest,FormatsNamespaces)2223 TEST_F(FormatTest, FormatsNamespaces) {
2224 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
2225 LLVMWithNoNamespaceFix.FixNamespaceComments = false;
2226
2227 verifyFormat("namespace some_namespace {\n"
2228 "class A {};\n"
2229 "void f() { f(); }\n"
2230 "}",
2231 LLVMWithNoNamespaceFix);
2232 verifyFormat("namespace N::inline D {\n"
2233 "class A {};\n"
2234 "void f() { f(); }\n"
2235 "}",
2236 LLVMWithNoNamespaceFix);
2237 verifyFormat("namespace N::inline D::E {\n"
2238 "class A {};\n"
2239 "void f() { f(); }\n"
2240 "}",
2241 LLVMWithNoNamespaceFix);
2242 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
2243 "class A {};\n"
2244 "void f() { f(); }\n"
2245 "}",
2246 LLVMWithNoNamespaceFix);
2247 verifyFormat("/* something */ namespace some_namespace {\n"
2248 "class A {};\n"
2249 "void f() { f(); }\n"
2250 "}",
2251 LLVMWithNoNamespaceFix);
2252 verifyFormat("namespace {\n"
2253 "class A {};\n"
2254 "void f() { f(); }\n"
2255 "}",
2256 LLVMWithNoNamespaceFix);
2257 verifyFormat("/* something */ namespace {\n"
2258 "class A {};\n"
2259 "void f() { f(); }\n"
2260 "}",
2261 LLVMWithNoNamespaceFix);
2262 verifyFormat("inline namespace X {\n"
2263 "class A {};\n"
2264 "void f() { f(); }\n"
2265 "}",
2266 LLVMWithNoNamespaceFix);
2267 verifyFormat("/* something */ inline namespace X {\n"
2268 "class A {};\n"
2269 "void f() { f(); }\n"
2270 "}",
2271 LLVMWithNoNamespaceFix);
2272 verifyFormat("export namespace X {\n"
2273 "class A {};\n"
2274 "void f() { f(); }\n"
2275 "}",
2276 LLVMWithNoNamespaceFix);
2277 verifyFormat("using namespace some_namespace;\n"
2278 "class A {};\n"
2279 "void f() { f(); }",
2280 LLVMWithNoNamespaceFix);
2281
2282 // This code is more common than we thought; if we
2283 // layout this correctly the semicolon will go into
2284 // its own line, which is undesirable.
2285 verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
2286 verifyFormat("namespace {\n"
2287 "class A {};\n"
2288 "};",
2289 LLVMWithNoNamespaceFix);
2290
2291 verifyFormat("namespace {\n"
2292 "int SomeVariable = 0; // comment\n"
2293 "} // namespace",
2294 LLVMWithNoNamespaceFix);
2295 EXPECT_EQ("#ifndef HEADER_GUARD\n"
2296 "#define HEADER_GUARD\n"
2297 "namespace my_namespace {\n"
2298 "int i;\n"
2299 "} // my_namespace\n"
2300 "#endif // HEADER_GUARD",
2301 format("#ifndef HEADER_GUARD\n"
2302 " #define HEADER_GUARD\n"
2303 " namespace my_namespace {\n"
2304 "int i;\n"
2305 "} // my_namespace\n"
2306 "#endif // HEADER_GUARD",
2307 LLVMWithNoNamespaceFix));
2308
2309 EXPECT_EQ("namespace A::B {\n"
2310 "class C {};\n"
2311 "}",
2312 format("namespace A::B {\n"
2313 "class C {};\n"
2314 "}",
2315 LLVMWithNoNamespaceFix));
2316
2317 FormatStyle Style = getLLVMStyle();
2318 Style.NamespaceIndentation = FormatStyle::NI_All;
2319 EXPECT_EQ("namespace out {\n"
2320 " int i;\n"
2321 " namespace in {\n"
2322 " int i;\n"
2323 " } // namespace in\n"
2324 "} // namespace out",
2325 format("namespace out {\n"
2326 "int i;\n"
2327 "namespace in {\n"
2328 "int i;\n"
2329 "} // namespace in\n"
2330 "} // namespace out",
2331 Style));
2332
2333 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2334 EXPECT_EQ("namespace out {\n"
2335 "int i;\n"
2336 "namespace in {\n"
2337 " int i;\n"
2338 "} // namespace in\n"
2339 "} // namespace out",
2340 format("namespace out {\n"
2341 "int i;\n"
2342 "namespace in {\n"
2343 "int i;\n"
2344 "} // namespace in\n"
2345 "} // namespace out",
2346 Style));
2347 }
2348
TEST_F(FormatTest,NamespaceMacros)2349 TEST_F(FormatTest, NamespaceMacros) {
2350 FormatStyle Style = getLLVMStyle();
2351 Style.NamespaceMacros.push_back("TESTSUITE");
2352
2353 verifyFormat("TESTSUITE(A) {\n"
2354 "int foo();\n"
2355 "} // TESTSUITE(A)",
2356 Style);
2357
2358 verifyFormat("TESTSUITE(A, B) {\n"
2359 "int foo();\n"
2360 "} // TESTSUITE(A)",
2361 Style);
2362
2363 // Properly indent according to NamespaceIndentation style
2364 Style.NamespaceIndentation = FormatStyle::NI_All;
2365 verifyFormat("TESTSUITE(A) {\n"
2366 " int foo();\n"
2367 "} // TESTSUITE(A)",
2368 Style);
2369 verifyFormat("TESTSUITE(A) {\n"
2370 " namespace B {\n"
2371 " int foo();\n"
2372 " } // namespace B\n"
2373 "} // TESTSUITE(A)",
2374 Style);
2375 verifyFormat("namespace A {\n"
2376 " TESTSUITE(B) {\n"
2377 " int foo();\n"
2378 " } // TESTSUITE(B)\n"
2379 "} // namespace A",
2380 Style);
2381
2382 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2383 verifyFormat("TESTSUITE(A) {\n"
2384 "TESTSUITE(B) {\n"
2385 " int foo();\n"
2386 "} // TESTSUITE(B)\n"
2387 "} // TESTSUITE(A)",
2388 Style);
2389 verifyFormat("TESTSUITE(A) {\n"
2390 "namespace B {\n"
2391 " int foo();\n"
2392 "} // namespace B\n"
2393 "} // TESTSUITE(A)",
2394 Style);
2395 verifyFormat("namespace A {\n"
2396 "TESTSUITE(B) {\n"
2397 " int foo();\n"
2398 "} // TESTSUITE(B)\n"
2399 "} // namespace A",
2400 Style);
2401
2402 // Properly merge namespace-macros blocks in CompactNamespaces mode
2403 Style.NamespaceIndentation = FormatStyle::NI_None;
2404 Style.CompactNamespaces = true;
2405 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
2406 "}} // TESTSUITE(A::B)",
2407 Style);
2408
2409 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2410 "}} // TESTSUITE(out::in)",
2411 format("TESTSUITE(out) {\n"
2412 "TESTSUITE(in) {\n"
2413 "} // TESTSUITE(in)\n"
2414 "} // TESTSUITE(out)",
2415 Style));
2416
2417 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2418 "}} // TESTSUITE(out::in)",
2419 format("TESTSUITE(out) {\n"
2420 "TESTSUITE(in) {\n"
2421 "} // TESTSUITE(in)\n"
2422 "} // TESTSUITE(out)",
2423 Style));
2424
2425 // Do not merge different namespaces/macros
2426 EXPECT_EQ("namespace out {\n"
2427 "TESTSUITE(in) {\n"
2428 "} // TESTSUITE(in)\n"
2429 "} // namespace out",
2430 format("namespace out {\n"
2431 "TESTSUITE(in) {\n"
2432 "} // TESTSUITE(in)\n"
2433 "} // namespace out",
2434 Style));
2435 EXPECT_EQ("TESTSUITE(out) {\n"
2436 "namespace in {\n"
2437 "} // namespace in\n"
2438 "} // TESTSUITE(out)",
2439 format("TESTSUITE(out) {\n"
2440 "namespace in {\n"
2441 "} // namespace in\n"
2442 "} // TESTSUITE(out)",
2443 Style));
2444 Style.NamespaceMacros.push_back("FOOBAR");
2445 EXPECT_EQ("TESTSUITE(out) {\n"
2446 "FOOBAR(in) {\n"
2447 "} // FOOBAR(in)\n"
2448 "} // TESTSUITE(out)",
2449 format("TESTSUITE(out) {\n"
2450 "FOOBAR(in) {\n"
2451 "} // FOOBAR(in)\n"
2452 "} // TESTSUITE(out)",
2453 Style));
2454 }
2455
TEST_F(FormatTest,FormatsCompactNamespaces)2456 TEST_F(FormatTest, FormatsCompactNamespaces) {
2457 FormatStyle Style = getLLVMStyle();
2458 Style.CompactNamespaces = true;
2459 Style.NamespaceMacros.push_back("TESTSUITE");
2460
2461 verifyFormat("namespace A { namespace B {\n"
2462 "}} // namespace A::B",
2463 Style);
2464
2465 EXPECT_EQ("namespace out { namespace in {\n"
2466 "}} // namespace out::in",
2467 format("namespace out {\n"
2468 "namespace in {\n"
2469 "} // namespace in\n"
2470 "} // namespace out",
2471 Style));
2472
2473 // Only namespaces which have both consecutive opening and end get compacted
2474 EXPECT_EQ("namespace out {\n"
2475 "namespace in1 {\n"
2476 "} // namespace in1\n"
2477 "namespace in2 {\n"
2478 "} // namespace in2\n"
2479 "} // namespace out",
2480 format("namespace out {\n"
2481 "namespace in1 {\n"
2482 "} // namespace in1\n"
2483 "namespace in2 {\n"
2484 "} // namespace in2\n"
2485 "} // namespace out",
2486 Style));
2487
2488 EXPECT_EQ("namespace out {\n"
2489 "int i;\n"
2490 "namespace in {\n"
2491 "int j;\n"
2492 "} // namespace in\n"
2493 "int k;\n"
2494 "} // namespace out",
2495 format("namespace out { int i;\n"
2496 "namespace in { int j; } // namespace in\n"
2497 "int k; } // namespace out",
2498 Style));
2499
2500 EXPECT_EQ("namespace A { namespace B { namespace C {\n"
2501 "}}} // namespace A::B::C\n",
2502 format("namespace A { namespace B {\n"
2503 "namespace C {\n"
2504 "}} // namespace B::C\n"
2505 "} // namespace A\n",
2506 Style));
2507
2508 Style.ColumnLimit = 40;
2509 EXPECT_EQ("namespace aaaaaaaaaa {\n"
2510 "namespace bbbbbbbbbb {\n"
2511 "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
2512 format("namespace aaaaaaaaaa {\n"
2513 "namespace bbbbbbbbbb {\n"
2514 "} // namespace bbbbbbbbbb\n"
2515 "} // namespace aaaaaaaaaa",
2516 Style));
2517
2518 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
2519 "namespace cccccc {\n"
2520 "}}} // namespace aaaaaa::bbbbbb::cccccc",
2521 format("namespace aaaaaa {\n"
2522 "namespace bbbbbb {\n"
2523 "namespace cccccc {\n"
2524 "} // namespace cccccc\n"
2525 "} // namespace bbbbbb\n"
2526 "} // namespace aaaaaa",
2527 Style));
2528 Style.ColumnLimit = 80;
2529
2530 // Extra semicolon after 'inner' closing brace prevents merging
2531 EXPECT_EQ("namespace out { namespace in {\n"
2532 "}; } // namespace out::in",
2533 format("namespace out {\n"
2534 "namespace in {\n"
2535 "}; // namespace in\n"
2536 "} // namespace out",
2537 Style));
2538
2539 // Extra semicolon after 'outer' closing brace is conserved
2540 EXPECT_EQ("namespace out { namespace in {\n"
2541 "}}; // namespace out::in",
2542 format("namespace out {\n"
2543 "namespace in {\n"
2544 "} // namespace in\n"
2545 "}; // namespace out",
2546 Style));
2547
2548 Style.NamespaceIndentation = FormatStyle::NI_All;
2549 EXPECT_EQ("namespace out { namespace in {\n"
2550 " int i;\n"
2551 "}} // namespace out::in",
2552 format("namespace out {\n"
2553 "namespace in {\n"
2554 "int i;\n"
2555 "} // namespace in\n"
2556 "} // namespace out",
2557 Style));
2558 EXPECT_EQ("namespace out { namespace mid {\n"
2559 " namespace in {\n"
2560 " int j;\n"
2561 " } // namespace in\n"
2562 " int k;\n"
2563 "}} // namespace out::mid",
2564 format("namespace out { namespace mid {\n"
2565 "namespace in { int j; } // namespace in\n"
2566 "int k; }} // namespace out::mid",
2567 Style));
2568
2569 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2570 EXPECT_EQ("namespace out { namespace in {\n"
2571 " int i;\n"
2572 "}} // namespace out::in",
2573 format("namespace out {\n"
2574 "namespace in {\n"
2575 "int i;\n"
2576 "} // namespace in\n"
2577 "} // namespace out",
2578 Style));
2579 EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
2580 " int i;\n"
2581 "}}} // namespace out::mid::in",
2582 format("namespace out {\n"
2583 "namespace mid {\n"
2584 "namespace in {\n"
2585 "int i;\n"
2586 "} // namespace in\n"
2587 "} // namespace mid\n"
2588 "} // namespace out",
2589 Style));
2590 }
2591
TEST_F(FormatTest,FormatsExternC)2592 TEST_F(FormatTest, FormatsExternC) {
2593 verifyFormat("extern \"C\" {\nint a;");
2594 verifyFormat("extern \"C\" {}");
2595 verifyFormat("extern \"C\" {\n"
2596 "int foo();\n"
2597 "}");
2598 verifyFormat("extern \"C\" int foo() {}");
2599 verifyFormat("extern \"C\" int foo();");
2600 verifyFormat("extern \"C\" int foo() {\n"
2601 " int i = 42;\n"
2602 " return i;\n"
2603 "}");
2604
2605 FormatStyle Style = getLLVMStyle();
2606 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2607 Style.BraceWrapping.AfterFunction = true;
2608 verifyFormat("extern \"C\" int foo() {}", Style);
2609 verifyFormat("extern \"C\" int foo();", Style);
2610 verifyFormat("extern \"C\" int foo()\n"
2611 "{\n"
2612 " int i = 42;\n"
2613 " return i;\n"
2614 "}",
2615 Style);
2616
2617 Style.BraceWrapping.AfterExternBlock = true;
2618 Style.BraceWrapping.SplitEmptyRecord = false;
2619 verifyFormat("extern \"C\"\n"
2620 "{}",
2621 Style);
2622 verifyFormat("extern \"C\"\n"
2623 "{\n"
2624 " int foo();\n"
2625 "}",
2626 Style);
2627 }
2628
TEST_F(FormatTest,IndentExternBlockStyle)2629 TEST_F(FormatTest, IndentExternBlockStyle) {
2630 FormatStyle Style = getLLVMStyle();
2631 Style.IndentWidth = 2;
2632
2633 Style.IndentExternBlock = FormatStyle::IEBS_Indent;
2634 verifyFormat("extern \"C\" { /*9*/\n}", Style);
2635 verifyFormat("extern \"C\" {\n"
2636 " int foo10();\n"
2637 "}",
2638 Style);
2639
2640 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
2641 verifyFormat("extern \"C\" { /*11*/\n}", Style);
2642 verifyFormat("extern \"C\" {\n"
2643 "int foo12();\n"
2644 "}",
2645 Style);
2646
2647 Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2648 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2649 Style.BraceWrapping.AfterExternBlock = true;
2650 verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
2651 verifyFormat("extern \"C\"\n{\n"
2652 " int foo14();\n"
2653 "}",
2654 Style);
2655
2656 Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2657 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2658 Style.BraceWrapping.AfterExternBlock = false;
2659 verifyFormat("extern \"C\" { /*15*/\n}", Style);
2660 verifyFormat("extern \"C\" {\n"
2661 "int foo16();\n"
2662 "}",
2663 Style);
2664 }
2665
TEST_F(FormatTest,FormatsInlineASM)2666 TEST_F(FormatTest, FormatsInlineASM) {
2667 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2668 verifyFormat("asm(\"nop\" ::: \"memory\");");
2669 verifyFormat(
2670 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2671 " \"cpuid\\n\\t\"\n"
2672 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2673 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2674 " : \"a\"(value));");
2675 EXPECT_EQ(
2676 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2677 " __asm {\n"
2678 " mov edx,[that] // vtable in edx\n"
2679 " mov eax,methodIndex\n"
2680 " call [edx][eax*4] // stdcall\n"
2681 " }\n"
2682 "}",
2683 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2684 " __asm {\n"
2685 " mov edx,[that] // vtable in edx\n"
2686 " mov eax,methodIndex\n"
2687 " call [edx][eax*4] // stdcall\n"
2688 " }\n"
2689 "}"));
2690 EXPECT_EQ("_asm {\n"
2691 " xor eax, eax;\n"
2692 " cpuid;\n"
2693 "}",
2694 format("_asm {\n"
2695 " xor eax, eax;\n"
2696 " cpuid;\n"
2697 "}"));
2698 verifyFormat("void function() {\n"
2699 " // comment\n"
2700 " asm(\"\");\n"
2701 "}");
2702 EXPECT_EQ("__asm {\n"
2703 "}\n"
2704 "int i;",
2705 format("__asm {\n"
2706 "}\n"
2707 "int i;"));
2708 }
2709
TEST_F(FormatTest,FormatTryCatch)2710 TEST_F(FormatTest, FormatTryCatch) {
2711 verifyFormat("try {\n"
2712 " throw a * b;\n"
2713 "} catch (int a) {\n"
2714 " // Do nothing.\n"
2715 "} catch (...) {\n"
2716 " exit(42);\n"
2717 "}");
2718
2719 // Function-level try statements.
2720 verifyFormat("int f() try { return 4; } catch (...) {\n"
2721 " return 5;\n"
2722 "}");
2723 verifyFormat("class A {\n"
2724 " int a;\n"
2725 " A() try : a(0) {\n"
2726 " } catch (...) {\n"
2727 " throw;\n"
2728 " }\n"
2729 "};\n");
2730
2731 // Incomplete try-catch blocks.
2732 verifyIncompleteFormat("try {} catch (");
2733 }
2734
TEST_F(FormatTest,FormatTryAsAVariable)2735 TEST_F(FormatTest, FormatTryAsAVariable) {
2736 verifyFormat("int try;");
2737 verifyFormat("int try, size;");
2738 verifyFormat("try = foo();");
2739 verifyFormat("if (try < size) {\n return true;\n}");
2740
2741 verifyFormat("int catch;");
2742 verifyFormat("int catch, size;");
2743 verifyFormat("catch = foo();");
2744 verifyFormat("if (catch < size) {\n return true;\n}");
2745
2746 FormatStyle Style = getLLVMStyle();
2747 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2748 Style.BraceWrapping.AfterFunction = true;
2749 Style.BraceWrapping.BeforeCatch = true;
2750 verifyFormat("try {\n"
2751 " int bar = 1;\n"
2752 "}\n"
2753 "catch (...) {\n"
2754 " int bar = 1;\n"
2755 "}",
2756 Style);
2757 verifyFormat("#if NO_EX\n"
2758 "try\n"
2759 "#endif\n"
2760 "{\n"
2761 "}\n"
2762 "#if NO_EX\n"
2763 "catch (...) {\n"
2764 "}",
2765 Style);
2766 verifyFormat("try /* abc */ {\n"
2767 " int bar = 1;\n"
2768 "}\n"
2769 "catch (...) {\n"
2770 " int bar = 1;\n"
2771 "}",
2772 Style);
2773 verifyFormat("try\n"
2774 "// abc\n"
2775 "{\n"
2776 " int bar = 1;\n"
2777 "}\n"
2778 "catch (...) {\n"
2779 " int bar = 1;\n"
2780 "}",
2781 Style);
2782 }
2783
TEST_F(FormatTest,FormatSEHTryCatch)2784 TEST_F(FormatTest, FormatSEHTryCatch) {
2785 verifyFormat("__try {\n"
2786 " int a = b * c;\n"
2787 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2788 " // Do nothing.\n"
2789 "}");
2790
2791 verifyFormat("__try {\n"
2792 " int a = b * c;\n"
2793 "} __finally {\n"
2794 " // Do nothing.\n"
2795 "}");
2796
2797 verifyFormat("DEBUG({\n"
2798 " __try {\n"
2799 " } __finally {\n"
2800 " }\n"
2801 "});\n");
2802 }
2803
TEST_F(FormatTest,IncompleteTryCatchBlocks)2804 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2805 verifyFormat("try {\n"
2806 " f();\n"
2807 "} catch {\n"
2808 " g();\n"
2809 "}");
2810 verifyFormat("try {\n"
2811 " f();\n"
2812 "} catch (A a) MACRO(x) {\n"
2813 " g();\n"
2814 "} catch (B b) MACRO(x) {\n"
2815 " g();\n"
2816 "}");
2817 }
2818
TEST_F(FormatTest,FormatTryCatchBraceStyles)2819 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2820 FormatStyle Style = getLLVMStyle();
2821 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2822 FormatStyle::BS_WebKit}) {
2823 Style.BreakBeforeBraces = BraceStyle;
2824 verifyFormat("try {\n"
2825 " // something\n"
2826 "} catch (...) {\n"
2827 " // something\n"
2828 "}",
2829 Style);
2830 }
2831 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2832 verifyFormat("try {\n"
2833 " // something\n"
2834 "}\n"
2835 "catch (...) {\n"
2836 " // something\n"
2837 "}",
2838 Style);
2839 verifyFormat("__try {\n"
2840 " // something\n"
2841 "}\n"
2842 "__finally {\n"
2843 " // something\n"
2844 "}",
2845 Style);
2846 verifyFormat("@try {\n"
2847 " // something\n"
2848 "}\n"
2849 "@finally {\n"
2850 " // something\n"
2851 "}",
2852 Style);
2853 Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2854 verifyFormat("try\n"
2855 "{\n"
2856 " // something\n"
2857 "}\n"
2858 "catch (...)\n"
2859 "{\n"
2860 " // something\n"
2861 "}",
2862 Style);
2863 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
2864 verifyFormat("try\n"
2865 " {\n"
2866 " // something white\n"
2867 " }\n"
2868 "catch (...)\n"
2869 " {\n"
2870 " // something white\n"
2871 " }",
2872 Style);
2873 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2874 verifyFormat("try\n"
2875 " {\n"
2876 " // something\n"
2877 " }\n"
2878 "catch (...)\n"
2879 " {\n"
2880 " // something\n"
2881 " }",
2882 Style);
2883 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2884 Style.BraceWrapping.BeforeCatch = true;
2885 verifyFormat("try {\n"
2886 " // something\n"
2887 "}\n"
2888 "catch (...) {\n"
2889 " // something\n"
2890 "}",
2891 Style);
2892 }
2893
TEST_F(FormatTest,StaticInitializers)2894 TEST_F(FormatTest, StaticInitializers) {
2895 verifyFormat("static SomeClass SC = {1, 'a'};");
2896
2897 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2898 " 100000000, "
2899 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2900
2901 // Here, everything other than the "}" would fit on a line.
2902 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2903 " 10000000000000000000000000};");
2904 EXPECT_EQ("S s = {a,\n"
2905 "\n"
2906 " b};",
2907 format("S s = {\n"
2908 " a,\n"
2909 "\n"
2910 " b\n"
2911 "};"));
2912
2913 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2914 // line. However, the formatting looks a bit off and this probably doesn't
2915 // happen often in practice.
2916 verifyFormat("static int Variable[1] = {\n"
2917 " {1000000000000000000000000000000000000}};",
2918 getLLVMStyleWithColumns(40));
2919 }
2920
TEST_F(FormatTest,DesignatedInitializers)2921 TEST_F(FormatTest, DesignatedInitializers) {
2922 verifyFormat("const struct A a = {.a = 1, .b = 2};");
2923 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2924 " .bbbbbbbbbb = 2,\n"
2925 " .cccccccccc = 3,\n"
2926 " .dddddddddd = 4,\n"
2927 " .eeeeeeeeee = 5};");
2928 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2929 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2930 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2931 " .ccccccccccccccccccccccccccc = 3,\n"
2932 " .ddddddddddddddddddddddddddd = 4,\n"
2933 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2934
2935 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2936
2937 verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
2938 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
2939 " [2] = bbbbbbbbbb,\n"
2940 " [3] = cccccccccc,\n"
2941 " [4] = dddddddddd,\n"
2942 " [5] = eeeeeeeeee};");
2943 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2944 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2945 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2946 " [3] = cccccccccccccccccccccccccccccccccccccc,\n"
2947 " [4] = dddddddddddddddddddddddddddddddddddddd,\n"
2948 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
2949 }
2950
TEST_F(FormatTest,NestedStaticInitializers)2951 TEST_F(FormatTest, NestedStaticInitializers) {
2952 verifyFormat("static A x = {{{}}};\n");
2953 verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2954 " {init1, init2, init3, init4}}};",
2955 getLLVMStyleWithColumns(50));
2956
2957 verifyFormat("somes Status::global_reps[3] = {\n"
2958 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2959 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2960 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2961 getLLVMStyleWithColumns(60));
2962 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2963 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2964 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2965 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2966 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2967 " {rect.fRight - rect.fLeft, rect.fBottom - "
2968 "rect.fTop}};");
2969
2970 verifyFormat(
2971 "SomeArrayOfSomeType a = {\n"
2972 " {{1, 2, 3},\n"
2973 " {1, 2, 3},\n"
2974 " {111111111111111111111111111111, 222222222222222222222222222222,\n"
2975 " 333333333333333333333333333333},\n"
2976 " {1, 2, 3},\n"
2977 " {1, 2, 3}}};");
2978 verifyFormat(
2979 "SomeArrayOfSomeType a = {\n"
2980 " {{1, 2, 3}},\n"
2981 " {{1, 2, 3}},\n"
2982 " {{111111111111111111111111111111, 222222222222222222222222222222,\n"
2983 " 333333333333333333333333333333}},\n"
2984 " {{1, 2, 3}},\n"
2985 " {{1, 2, 3}}};");
2986
2987 verifyFormat("struct {\n"
2988 " unsigned bit;\n"
2989 " const char *const name;\n"
2990 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
2991 " {kOsWin, \"Windows\"},\n"
2992 " {kOsLinux, \"Linux\"},\n"
2993 " {kOsCrOS, \"Chrome OS\"}};");
2994 verifyFormat("struct {\n"
2995 " unsigned bit;\n"
2996 " const char *const name;\n"
2997 "} kBitsToOs[] = {\n"
2998 " {kOsMac, \"Mac\"},\n"
2999 " {kOsWin, \"Windows\"},\n"
3000 " {kOsLinux, \"Linux\"},\n"
3001 " {kOsCrOS, \"Chrome OS\"},\n"
3002 "};");
3003 }
3004
TEST_F(FormatTest,FormatsSmallMacroDefinitionsInSingleLine)3005 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
3006 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3007 " \\\n"
3008 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
3009 }
3010
TEST_F(FormatTest,DoesNotBreakPureVirtualFunctionDefinition)3011 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
3012 verifyFormat("virtual void write(ELFWriter *writerrr,\n"
3013 " OwningPtr<FileOutputBuffer> &buffer) = 0;");
3014
3015 // Do break defaulted and deleted functions.
3016 verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3017 " default;",
3018 getLLVMStyleWithColumns(40));
3019 verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3020 " delete;",
3021 getLLVMStyleWithColumns(40));
3022 }
3023
TEST_F(FormatTest,BreaksStringLiteralsOnlyInDefine)3024 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
3025 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
3026 getLLVMStyleWithColumns(40));
3027 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3028 getLLVMStyleWithColumns(40));
3029 EXPECT_EQ("#define Q \\\n"
3030 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n"
3031 " \"aaaaaaaa.cpp\"",
3032 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3033 getLLVMStyleWithColumns(40)));
3034 }
3035
TEST_F(FormatTest,UnderstandsLinePPDirective)3036 TEST_F(FormatTest, UnderstandsLinePPDirective) {
3037 EXPECT_EQ("# 123 \"A string literal\"",
3038 format(" # 123 \"A string literal\""));
3039 }
3040
TEST_F(FormatTest,LayoutUnknownPPDirective)3041 TEST_F(FormatTest, LayoutUnknownPPDirective) {
3042 EXPECT_EQ("#;", format("#;"));
3043 verifyFormat("#\n;\n;\n;");
3044 }
3045
TEST_F(FormatTest,UnescapedEndOfLineEndsPPDirective)3046 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
3047 EXPECT_EQ("#line 42 \"test\"\n",
3048 format("# \\\n line \\\n 42 \\\n \"test\"\n"));
3049 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n",
3050 getLLVMStyleWithColumns(12)));
3051 }
3052
TEST_F(FormatTest,EndOfFileEndsPPDirective)3053 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
3054 EXPECT_EQ("#line 42 \"test\"",
3055 format("# \\\n line \\\n 42 \\\n \"test\""));
3056 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B"));
3057 }
3058
TEST_F(FormatTest,DoesntRemoveUnknownTokens)3059 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
3060 verifyFormat("#define A \\x20");
3061 verifyFormat("#define A \\ x20");
3062 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20"));
3063 verifyFormat("#define A ''");
3064 verifyFormat("#define A ''qqq");
3065 verifyFormat("#define A `qqq");
3066 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
3067 EXPECT_EQ("const char *c = STRINGIFY(\n"
3068 "\\na : b);",
3069 format("const char * c = STRINGIFY(\n"
3070 "\\na : b);"));
3071
3072 verifyFormat("a\r\\");
3073 verifyFormat("a\v\\");
3074 verifyFormat("a\f\\");
3075 }
3076
TEST_F(FormatTest,IndentsPPDirectiveInReducedSpace)3077 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
3078 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
3079 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12));
3080 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12));
3081 // FIXME: We never break before the macro name.
3082 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12));
3083
3084 verifyFormat("#define A A\n#define A A");
3085 verifyFormat("#define A(X) A\n#define A A");
3086
3087 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
3088 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22));
3089 }
3090
TEST_F(FormatTest,HandlePreprocessorDirectiveContext)3091 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
3092 EXPECT_EQ("// somecomment\n"
3093 "#include \"a.h\"\n"
3094 "#define A( \\\n"
3095 " A, B)\n"
3096 "#include \"b.h\"\n"
3097 "// somecomment\n",
3098 format(" // somecomment\n"
3099 " #include \"a.h\"\n"
3100 "#define A(A,\\\n"
3101 " B)\n"
3102 " #include \"b.h\"\n"
3103 " // somecomment\n",
3104 getLLVMStyleWithColumns(13)));
3105 }
3106
TEST_F(FormatTest,LayoutSingleHash)3107 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
3108
TEST_F(FormatTest,LayoutCodeInMacroDefinitions)3109 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
3110 EXPECT_EQ("#define A \\\n"
3111 " c; \\\n"
3112 " e;\n"
3113 "f;",
3114 format("#define A c; e;\n"
3115 "f;",
3116 getLLVMStyleWithColumns(14)));
3117 }
3118
TEST_F(FormatTest,LayoutRemainingTokens)3119 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
3120
TEST_F(FormatTest,MacroDefinitionInsideStatement)3121 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
3122 EXPECT_EQ("int x,\n"
3123 "#define A\n"
3124 " y;",
3125 format("int x,\n#define A\ny;"));
3126 }
3127
TEST_F(FormatTest,HashInMacroDefinition)3128 TEST_F(FormatTest, HashInMacroDefinition) {
3129 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
3130 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11));
3131 verifyFormat("#define A \\\n"
3132 " { \\\n"
3133 " f(#c); \\\n"
3134 " }",
3135 getLLVMStyleWithColumns(11));
3136
3137 verifyFormat("#define A(X) \\\n"
3138 " void function##X()",
3139 getLLVMStyleWithColumns(22));
3140
3141 verifyFormat("#define A(a, b, c) \\\n"
3142 " void a##b##c()",
3143 getLLVMStyleWithColumns(22));
3144
3145 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
3146 }
3147
TEST_F(FormatTest,RespectWhitespaceInMacroDefinitions)3148 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
3149 EXPECT_EQ("#define A (x)", format("#define A (x)"));
3150 EXPECT_EQ("#define A(x)", format("#define A(x)"));
3151
3152 FormatStyle Style = getLLVMStyle();
3153 Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
3154 verifyFormat("#define true ((foo)1)", Style);
3155 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
3156 verifyFormat("#define false((foo)0)", Style);
3157 }
3158
TEST_F(FormatTest,EmptyLinesInMacroDefinitions)3159 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
3160 EXPECT_EQ("#define A b;", format("#define A \\\n"
3161 " \\\n"
3162 " b;",
3163 getLLVMStyleWithColumns(25)));
3164 EXPECT_EQ("#define A \\\n"
3165 " \\\n"
3166 " a; \\\n"
3167 " b;",
3168 format("#define A \\\n"
3169 " \\\n"
3170 " a; \\\n"
3171 " b;",
3172 getLLVMStyleWithColumns(11)));
3173 EXPECT_EQ("#define A \\\n"
3174 " a; \\\n"
3175 " \\\n"
3176 " b;",
3177 format("#define A \\\n"
3178 " a; \\\n"
3179 " \\\n"
3180 " b;",
3181 getLLVMStyleWithColumns(11)));
3182 }
3183
TEST_F(FormatTest,MacroDefinitionsWithIncompleteCode)3184 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
3185 verifyIncompleteFormat("#define A :");
3186 verifyFormat("#define SOMECASES \\\n"
3187 " case 1: \\\n"
3188 " case 2\n",
3189 getLLVMStyleWithColumns(20));
3190 verifyFormat("#define MACRO(a) \\\n"
3191 " if (a) \\\n"
3192 " f(); \\\n"
3193 " else \\\n"
3194 " g()",
3195 getLLVMStyleWithColumns(18));
3196 verifyFormat("#define A template <typename T>");
3197 verifyIncompleteFormat("#define STR(x) #x\n"
3198 "f(STR(this_is_a_string_literal{));");
3199 verifyFormat("#pragma omp threadprivate( \\\n"
3200 " y)), // expected-warning",
3201 getLLVMStyleWithColumns(28));
3202 verifyFormat("#d, = };");
3203 verifyFormat("#if \"a");
3204 verifyIncompleteFormat("({\n"
3205 "#define b \\\n"
3206 " } \\\n"
3207 " a\n"
3208 "a",
3209 getLLVMStyleWithColumns(15));
3210 verifyFormat("#define A \\\n"
3211 " { \\\n"
3212 " {\n"
3213 "#define B \\\n"
3214 " } \\\n"
3215 " }",
3216 getLLVMStyleWithColumns(15));
3217 verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
3218 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
3219 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
3220 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}");
3221 }
3222
TEST_F(FormatTest,MacrosWithoutTrailingSemicolon)3223 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
3224 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
3225 EXPECT_EQ("class A : public QObject {\n"
3226 " Q_OBJECT\n"
3227 "\n"
3228 " A() {}\n"
3229 "};",
3230 format("class A : public QObject {\n"
3231 " Q_OBJECT\n"
3232 "\n"
3233 " A() {\n}\n"
3234 "} ;"));
3235 EXPECT_EQ("MACRO\n"
3236 "/*static*/ int i;",
3237 format("MACRO\n"
3238 " /*static*/ int i;"));
3239 EXPECT_EQ("SOME_MACRO\n"
3240 "namespace {\n"
3241 "void f();\n"
3242 "} // namespace",
3243 format("SOME_MACRO\n"
3244 " namespace {\n"
3245 "void f( );\n"
3246 "} // namespace"));
3247 // Only if the identifier contains at least 5 characters.
3248 EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
3249 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
3250 // Only if everything is upper case.
3251 EXPECT_EQ("class A : public QObject {\n"
3252 " Q_Object A() {}\n"
3253 "};",
3254 format("class A : public QObject {\n"
3255 " Q_Object\n"
3256 " A() {\n}\n"
3257 "} ;"));
3258
3259 // Only if the next line can actually start an unwrapped line.
3260 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
3261 format("SOME_WEIRD_LOG_MACRO\n"
3262 "<< SomeThing;"));
3263
3264 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
3265 "(n, buffers))\n",
3266 getChromiumStyle(FormatStyle::LK_Cpp));
3267
3268 // See PR41483
3269 EXPECT_EQ("/**/ FOO(a)\n"
3270 "FOO(b)",
3271 format("/**/ FOO(a)\n"
3272 "FOO(b)"));
3273 }
3274
TEST_F(FormatTest,MacroCallsWithoutTrailingSemicolon)3275 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
3276 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3277 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3278 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3279 "class X {};\n"
3280 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3281 "int *createScopDetectionPass() { return 0; }",
3282 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3283 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3284 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3285 " class X {};\n"
3286 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3287 " int *createScopDetectionPass() { return 0; }"));
3288 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
3289 // braces, so that inner block is indented one level more.
3290 EXPECT_EQ("int q() {\n"
3291 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3292 " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3293 " IPC_END_MESSAGE_MAP()\n"
3294 "}",
3295 format("int q() {\n"
3296 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3297 " IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3298 " IPC_END_MESSAGE_MAP()\n"
3299 "}"));
3300
3301 // Same inside macros.
3302 EXPECT_EQ("#define LIST(L) \\\n"
3303 " L(A) \\\n"
3304 " L(B) \\\n"
3305 " L(C)",
3306 format("#define LIST(L) \\\n"
3307 " L(A) \\\n"
3308 " L(B) \\\n"
3309 " L(C)",
3310 getGoogleStyle()));
3311
3312 // These must not be recognized as macros.
3313 EXPECT_EQ("int q() {\n"
3314 " f(x);\n"
3315 " f(x) {}\n"
3316 " f(x)->g();\n"
3317 " f(x)->*g();\n"
3318 " f(x).g();\n"
3319 " f(x) = x;\n"
3320 " f(x) += x;\n"
3321 " f(x) -= x;\n"
3322 " f(x) *= x;\n"
3323 " f(x) /= x;\n"
3324 " f(x) %= x;\n"
3325 " f(x) &= x;\n"
3326 " f(x) |= x;\n"
3327 " f(x) ^= x;\n"
3328 " f(x) >>= x;\n"
3329 " f(x) <<= x;\n"
3330 " f(x)[y].z();\n"
3331 " LOG(INFO) << x;\n"
3332 " ifstream(x) >> x;\n"
3333 "}\n",
3334 format("int q() {\n"
3335 " f(x)\n;\n"
3336 " f(x)\n {}\n"
3337 " f(x)\n->g();\n"
3338 " f(x)\n->*g();\n"
3339 " f(x)\n.g();\n"
3340 " f(x)\n = x;\n"
3341 " f(x)\n += x;\n"
3342 " f(x)\n -= x;\n"
3343 " f(x)\n *= x;\n"
3344 " f(x)\n /= x;\n"
3345 " f(x)\n %= x;\n"
3346 " f(x)\n &= x;\n"
3347 " f(x)\n |= x;\n"
3348 " f(x)\n ^= x;\n"
3349 " f(x)\n >>= x;\n"
3350 " f(x)\n <<= x;\n"
3351 " f(x)\n[y].z();\n"
3352 " LOG(INFO)\n << x;\n"
3353 " ifstream(x)\n >> x;\n"
3354 "}\n"));
3355 EXPECT_EQ("int q() {\n"
3356 " F(x)\n"
3357 " if (1) {\n"
3358 " }\n"
3359 " F(x)\n"
3360 " while (1) {\n"
3361 " }\n"
3362 " F(x)\n"
3363 " G(x);\n"
3364 " F(x)\n"
3365 " try {\n"
3366 " Q();\n"
3367 " } catch (...) {\n"
3368 " }\n"
3369 "}\n",
3370 format("int q() {\n"
3371 "F(x)\n"
3372 "if (1) {}\n"
3373 "F(x)\n"
3374 "while (1) {}\n"
3375 "F(x)\n"
3376 "G(x);\n"
3377 "F(x)\n"
3378 "try { Q(); } catch (...) {}\n"
3379 "}\n"));
3380 EXPECT_EQ("class A {\n"
3381 " A() : t(0) {}\n"
3382 " A(int i) noexcept() : {}\n"
3383 " A(X x)\n" // FIXME: function-level try blocks are broken.
3384 " try : t(0) {\n"
3385 " } catch (...) {\n"
3386 " }\n"
3387 "};",
3388 format("class A {\n"
3389 " A()\n : t(0) {}\n"
3390 " A(int i)\n noexcept() : {}\n"
3391 " A(X x)\n"
3392 " try : t(0) {} catch (...) {}\n"
3393 "};"));
3394 FormatStyle Style = getLLVMStyle();
3395 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3396 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
3397 Style.BraceWrapping.AfterFunction = true;
3398 EXPECT_EQ("void f()\n"
3399 "try\n"
3400 "{\n"
3401 "}",
3402 format("void f() try {\n"
3403 "}",
3404 Style));
3405 EXPECT_EQ("class SomeClass {\n"
3406 "public:\n"
3407 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3408 "};",
3409 format("class SomeClass {\n"
3410 "public:\n"
3411 " SomeClass()\n"
3412 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3413 "};"));
3414 EXPECT_EQ("class SomeClass {\n"
3415 "public:\n"
3416 " SomeClass()\n"
3417 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3418 "};",
3419 format("class SomeClass {\n"
3420 "public:\n"
3421 " SomeClass()\n"
3422 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3423 "};",
3424 getLLVMStyleWithColumns(40)));
3425
3426 verifyFormat("MACRO(>)");
3427
3428 // Some macros contain an implicit semicolon.
3429 Style = getLLVMStyle();
3430 Style.StatementMacros.push_back("FOO");
3431 verifyFormat("FOO(a) int b = 0;");
3432 verifyFormat("FOO(a)\n"
3433 "int b = 0;",
3434 Style);
3435 verifyFormat("FOO(a);\n"
3436 "int b = 0;",
3437 Style);
3438 verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
3439 "int b = 0;",
3440 Style);
3441 verifyFormat("FOO()\n"
3442 "int b = 0;",
3443 Style);
3444 verifyFormat("FOO\n"
3445 "int b = 0;",
3446 Style);
3447 verifyFormat("void f() {\n"
3448 " FOO(a)\n"
3449 " return a;\n"
3450 "}",
3451 Style);
3452 verifyFormat("FOO(a)\n"
3453 "FOO(b)",
3454 Style);
3455 verifyFormat("int a = 0;\n"
3456 "FOO(b)\n"
3457 "int c = 0;",
3458 Style);
3459 verifyFormat("int a = 0;\n"
3460 "int x = FOO(a)\n"
3461 "int b = 0;",
3462 Style);
3463 verifyFormat("void foo(int a) { FOO(a) }\n"
3464 "uint32_t bar() {}",
3465 Style);
3466 }
3467
TEST_F(FormatTest,LayoutMacroDefinitionsStatementsSpanningBlocks)3468 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
3469 verifyFormat("#define A \\\n"
3470 " f({ \\\n"
3471 " g(); \\\n"
3472 " });",
3473 getLLVMStyleWithColumns(11));
3474 }
3475
TEST_F(FormatTest,IndentPreprocessorDirectives)3476 TEST_F(FormatTest, IndentPreprocessorDirectives) {
3477 FormatStyle Style = getLLVMStyle();
3478 Style.IndentPPDirectives = FormatStyle::PPDIS_None;
3479 Style.ColumnLimit = 40;
3480 verifyFormat("#ifdef _WIN32\n"
3481 "#define A 0\n"
3482 "#ifdef VAR2\n"
3483 "#define B 1\n"
3484 "#include <someheader.h>\n"
3485 "#define MACRO \\\n"
3486 " some_very_long_func_aaaaaaaaaa();\n"
3487 "#endif\n"
3488 "#else\n"
3489 "#define A 1\n"
3490 "#endif",
3491 Style);
3492 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3493 verifyFormat("#ifdef _WIN32\n"
3494 "# define A 0\n"
3495 "# ifdef VAR2\n"
3496 "# define B 1\n"
3497 "# include <someheader.h>\n"
3498 "# define MACRO \\\n"
3499 " some_very_long_func_aaaaaaaaaa();\n"
3500 "# endif\n"
3501 "#else\n"
3502 "# define A 1\n"
3503 "#endif",
3504 Style);
3505 verifyFormat("#if A\n"
3506 "# define MACRO \\\n"
3507 " void a(int x) { \\\n"
3508 " b(); \\\n"
3509 " c(); \\\n"
3510 " d(); \\\n"
3511 " e(); \\\n"
3512 " f(); \\\n"
3513 " }\n"
3514 "#endif",
3515 Style);
3516 // Comments before include guard.
3517 verifyFormat("// file comment\n"
3518 "// file comment\n"
3519 "#ifndef HEADER_H\n"
3520 "#define HEADER_H\n"
3521 "code();\n"
3522 "#endif",
3523 Style);
3524 // Test with include guards.
3525 verifyFormat("#ifndef HEADER_H\n"
3526 "#define HEADER_H\n"
3527 "code();\n"
3528 "#endif",
3529 Style);
3530 // Include guards must have a #define with the same variable immediately
3531 // after #ifndef.
3532 verifyFormat("#ifndef NOT_GUARD\n"
3533 "# define FOO\n"
3534 "code();\n"
3535 "#endif",
3536 Style);
3537
3538 // Include guards must cover the entire file.
3539 verifyFormat("code();\n"
3540 "code();\n"
3541 "#ifndef NOT_GUARD\n"
3542 "# define NOT_GUARD\n"
3543 "code();\n"
3544 "#endif",
3545 Style);
3546 verifyFormat("#ifndef NOT_GUARD\n"
3547 "# define NOT_GUARD\n"
3548 "code();\n"
3549 "#endif\n"
3550 "code();",
3551 Style);
3552 // Test with trailing blank lines.
3553 verifyFormat("#ifndef HEADER_H\n"
3554 "#define HEADER_H\n"
3555 "code();\n"
3556 "#endif\n",
3557 Style);
3558 // Include guards don't have #else.
3559 verifyFormat("#ifndef NOT_GUARD\n"
3560 "# define NOT_GUARD\n"
3561 "code();\n"
3562 "#else\n"
3563 "#endif",
3564 Style);
3565 verifyFormat("#ifndef NOT_GUARD\n"
3566 "# define NOT_GUARD\n"
3567 "code();\n"
3568 "#elif FOO\n"
3569 "#endif",
3570 Style);
3571 // Non-identifier #define after potential include guard.
3572 verifyFormat("#ifndef FOO\n"
3573 "# define 1\n"
3574 "#endif\n",
3575 Style);
3576 // #if closes past last non-preprocessor line.
3577 verifyFormat("#ifndef FOO\n"
3578 "#define FOO\n"
3579 "#if 1\n"
3580 "int i;\n"
3581 "# define A 0\n"
3582 "#endif\n"
3583 "#endif\n",
3584 Style);
3585 // Don't crash if there is an #elif directive without a condition.
3586 verifyFormat("#if 1\n"
3587 "int x;\n"
3588 "#elif\n"
3589 "int y;\n"
3590 "#else\n"
3591 "int z;\n"
3592 "#endif",
3593 Style);
3594 // FIXME: This doesn't handle the case where there's code between the
3595 // #ifndef and #define but all other conditions hold. This is because when
3596 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
3597 // previous code line yet, so we can't detect it.
3598 EXPECT_EQ("#ifndef NOT_GUARD\n"
3599 "code();\n"
3600 "#define NOT_GUARD\n"
3601 "code();\n"
3602 "#endif",
3603 format("#ifndef NOT_GUARD\n"
3604 "code();\n"
3605 "# define NOT_GUARD\n"
3606 "code();\n"
3607 "#endif",
3608 Style));
3609 // FIXME: This doesn't handle cases where legitimate preprocessor lines may
3610 // be outside an include guard. Examples are #pragma once and
3611 // #pragma GCC diagnostic, or anything else that does not change the meaning
3612 // of the file if it's included multiple times.
3613 EXPECT_EQ("#ifdef WIN32\n"
3614 "# pragma once\n"
3615 "#endif\n"
3616 "#ifndef HEADER_H\n"
3617 "# define HEADER_H\n"
3618 "code();\n"
3619 "#endif",
3620 format("#ifdef WIN32\n"
3621 "# pragma once\n"
3622 "#endif\n"
3623 "#ifndef HEADER_H\n"
3624 "#define HEADER_H\n"
3625 "code();\n"
3626 "#endif",
3627 Style));
3628 // FIXME: This does not detect when there is a single non-preprocessor line
3629 // in front of an include-guard-like structure where other conditions hold
3630 // because ScopedLineState hides the line.
3631 EXPECT_EQ("code();\n"
3632 "#ifndef HEADER_H\n"
3633 "#define HEADER_H\n"
3634 "code();\n"
3635 "#endif",
3636 format("code();\n"
3637 "#ifndef HEADER_H\n"
3638 "# define HEADER_H\n"
3639 "code();\n"
3640 "#endif",
3641 Style));
3642 // Keep comments aligned with #, otherwise indent comments normally. These
3643 // tests cannot use verifyFormat because messUp manipulates leading
3644 // whitespace.
3645 {
3646 const char *Expected = ""
3647 "void f() {\n"
3648 "#if 1\n"
3649 "// Preprocessor aligned.\n"
3650 "# define A 0\n"
3651 " // Code. Separated by blank line.\n"
3652 "\n"
3653 "# define B 0\n"
3654 " // Code. Not aligned with #\n"
3655 "# define C 0\n"
3656 "#endif";
3657 const char *ToFormat = ""
3658 "void f() {\n"
3659 "#if 1\n"
3660 "// Preprocessor aligned.\n"
3661 "# define A 0\n"
3662 "// Code. Separated by blank line.\n"
3663 "\n"
3664 "# define B 0\n"
3665 " // Code. Not aligned with #\n"
3666 "# define C 0\n"
3667 "#endif";
3668 EXPECT_EQ(Expected, format(ToFormat, Style));
3669 EXPECT_EQ(Expected, format(Expected, Style));
3670 }
3671 // Keep block quotes aligned.
3672 {
3673 const char *Expected = ""
3674 "void f() {\n"
3675 "#if 1\n"
3676 "/* Preprocessor aligned. */\n"
3677 "# define A 0\n"
3678 " /* Code. Separated by blank line. */\n"
3679 "\n"
3680 "# define B 0\n"
3681 " /* Code. Not aligned with # */\n"
3682 "# define C 0\n"
3683 "#endif";
3684 const char *ToFormat = ""
3685 "void f() {\n"
3686 "#if 1\n"
3687 "/* Preprocessor aligned. */\n"
3688 "# define A 0\n"
3689 "/* Code. Separated by blank line. */\n"
3690 "\n"
3691 "# define B 0\n"
3692 " /* Code. Not aligned with # */\n"
3693 "# define C 0\n"
3694 "#endif";
3695 EXPECT_EQ(Expected, format(ToFormat, Style));
3696 EXPECT_EQ(Expected, format(Expected, Style));
3697 }
3698 // Keep comments aligned with un-indented directives.
3699 {
3700 const char *Expected = ""
3701 "void f() {\n"
3702 "// Preprocessor aligned.\n"
3703 "#define A 0\n"
3704 " // Code. Separated by blank line.\n"
3705 "\n"
3706 "#define B 0\n"
3707 " // Code. Not aligned with #\n"
3708 "#define C 0\n";
3709 const char *ToFormat = ""
3710 "void f() {\n"
3711 "// Preprocessor aligned.\n"
3712 "#define A 0\n"
3713 "// Code. Separated by blank line.\n"
3714 "\n"
3715 "#define B 0\n"
3716 " // Code. Not aligned with #\n"
3717 "#define C 0\n";
3718 EXPECT_EQ(Expected, format(ToFormat, Style));
3719 EXPECT_EQ(Expected, format(Expected, Style));
3720 }
3721 // Test AfterHash with tabs.
3722 {
3723 FormatStyle Tabbed = Style;
3724 Tabbed.UseTab = FormatStyle::UT_Always;
3725 Tabbed.IndentWidth = 8;
3726 Tabbed.TabWidth = 8;
3727 verifyFormat("#ifdef _WIN32\n"
3728 "#\tdefine A 0\n"
3729 "#\tifdef VAR2\n"
3730 "#\t\tdefine B 1\n"
3731 "#\t\tinclude <someheader.h>\n"
3732 "#\t\tdefine MACRO \\\n"
3733 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
3734 "#\tendif\n"
3735 "#else\n"
3736 "#\tdefine A 1\n"
3737 "#endif",
3738 Tabbed);
3739 }
3740
3741 // Regression test: Multiline-macro inside include guards.
3742 verifyFormat("#ifndef HEADER_H\n"
3743 "#define HEADER_H\n"
3744 "#define A() \\\n"
3745 " int i; \\\n"
3746 " int j;\n"
3747 "#endif // HEADER_H",
3748 getLLVMStyleWithColumns(20));
3749
3750 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
3751 // Basic before hash indent tests
3752 verifyFormat("#ifdef _WIN32\n"
3753 " #define A 0\n"
3754 " #ifdef VAR2\n"
3755 " #define B 1\n"
3756 " #include <someheader.h>\n"
3757 " #define MACRO \\\n"
3758 " some_very_long_func_aaaaaaaaaa();\n"
3759 " #endif\n"
3760 "#else\n"
3761 " #define A 1\n"
3762 "#endif",
3763 Style);
3764 verifyFormat("#if A\n"
3765 " #define MACRO \\\n"
3766 " void a(int x) { \\\n"
3767 " b(); \\\n"
3768 " c(); \\\n"
3769 " d(); \\\n"
3770 " e(); \\\n"
3771 " f(); \\\n"
3772 " }\n"
3773 "#endif",
3774 Style);
3775 // Keep comments aligned with indented directives. These
3776 // tests cannot use verifyFormat because messUp manipulates leading
3777 // whitespace.
3778 {
3779 const char *Expected = "void f() {\n"
3780 "// Aligned to preprocessor.\n"
3781 "#if 1\n"
3782 " // Aligned to code.\n"
3783 " int a;\n"
3784 " #if 1\n"
3785 " // Aligned to preprocessor.\n"
3786 " #define A 0\n"
3787 " // Aligned to code.\n"
3788 " int b;\n"
3789 " #endif\n"
3790 "#endif\n"
3791 "}";
3792 const char *ToFormat = "void f() {\n"
3793 "// Aligned to preprocessor.\n"
3794 "#if 1\n"
3795 "// Aligned to code.\n"
3796 "int a;\n"
3797 "#if 1\n"
3798 "// Aligned to preprocessor.\n"
3799 "#define A 0\n"
3800 "// Aligned to code.\n"
3801 "int b;\n"
3802 "#endif\n"
3803 "#endif\n"
3804 "}";
3805 EXPECT_EQ(Expected, format(ToFormat, Style));
3806 EXPECT_EQ(Expected, format(Expected, Style));
3807 }
3808 {
3809 const char *Expected = "void f() {\n"
3810 "/* Aligned to preprocessor. */\n"
3811 "#if 1\n"
3812 " /* Aligned to code. */\n"
3813 " int a;\n"
3814 " #if 1\n"
3815 " /* Aligned to preprocessor. */\n"
3816 " #define A 0\n"
3817 " /* Aligned to code. */\n"
3818 " int b;\n"
3819 " #endif\n"
3820 "#endif\n"
3821 "}";
3822 const char *ToFormat = "void f() {\n"
3823 "/* Aligned to preprocessor. */\n"
3824 "#if 1\n"
3825 "/* Aligned to code. */\n"
3826 "int a;\n"
3827 "#if 1\n"
3828 "/* Aligned to preprocessor. */\n"
3829 "#define A 0\n"
3830 "/* Aligned to code. */\n"
3831 "int b;\n"
3832 "#endif\n"
3833 "#endif\n"
3834 "}";
3835 EXPECT_EQ(Expected, format(ToFormat, Style));
3836 EXPECT_EQ(Expected, format(Expected, Style));
3837 }
3838
3839 // Test single comment before preprocessor
3840 verifyFormat("// Comment\n"
3841 "\n"
3842 "#if 1\n"
3843 "#endif",
3844 Style);
3845 }
3846
TEST_F(FormatTest,FormatHashIfNotAtStartOfLine)3847 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
3848 verifyFormat("{\n { a #c; }\n}");
3849 }
3850
TEST_F(FormatTest,FormatUnbalancedStructuralElements)3851 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
3852 EXPECT_EQ("#define A \\\n { \\\n {\nint i;",
3853 format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
3854 EXPECT_EQ("#define A \\\n } \\\n }\nint i;",
3855 format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
3856 }
3857
TEST_F(FormatTest,EscapedNewlines)3858 TEST_F(FormatTest, EscapedNewlines) {
3859 FormatStyle Narrow = getLLVMStyleWithColumns(11);
3860 EXPECT_EQ("#define A \\\n int i; \\\n int j;",
3861 format("#define A \\\nint i;\\\n int j;", Narrow));
3862 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
3863 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3864 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */"));
3865 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
3866
3867 FormatStyle AlignLeft = getLLVMStyle();
3868 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
3869 EXPECT_EQ("#define MACRO(x) \\\n"
3870 "private: \\\n"
3871 " int x(int a);\n",
3872 format("#define MACRO(x) \\\n"
3873 "private: \\\n"
3874 " int x(int a);\n",
3875 AlignLeft));
3876
3877 // CRLF line endings
3878 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;",
3879 format("#define A \\\r\nint i;\\\r\n int j;", Narrow));
3880 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
3881 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3882 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */"));
3883 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
3884 EXPECT_EQ("#define MACRO(x) \\\r\n"
3885 "private: \\\r\n"
3886 " int x(int a);\r\n",
3887 format("#define MACRO(x) \\\r\n"
3888 "private: \\\r\n"
3889 " int x(int a);\r\n",
3890 AlignLeft));
3891
3892 FormatStyle DontAlign = getLLVMStyle();
3893 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
3894 DontAlign.MaxEmptyLinesToKeep = 3;
3895 // FIXME: can't use verifyFormat here because the newline before
3896 // "public:" is not inserted the first time it's reformatted
3897 EXPECT_EQ("#define A \\\n"
3898 " class Foo { \\\n"
3899 " void bar(); \\\n"
3900 "\\\n"
3901 "\\\n"
3902 "\\\n"
3903 " public: \\\n"
3904 " void baz(); \\\n"
3905 " };",
3906 format("#define A \\\n"
3907 " class Foo { \\\n"
3908 " void bar(); \\\n"
3909 "\\\n"
3910 "\\\n"
3911 "\\\n"
3912 " public: \\\n"
3913 " void baz(); \\\n"
3914 " };",
3915 DontAlign));
3916 }
3917
TEST_F(FormatTest,CalculateSpaceOnConsecutiveLinesInMacro)3918 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
3919 verifyFormat("#define A \\\n"
3920 " int v( \\\n"
3921 " a); \\\n"
3922 " int i;",
3923 getLLVMStyleWithColumns(11));
3924 }
3925
TEST_F(FormatTest,MixingPreprocessorDirectivesAndNormalCode)3926 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3927 EXPECT_EQ(
3928 "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3929 " \\\n"
3930 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3931 "\n"
3932 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3933 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3934 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro("
3935 "\\\n"
3936 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3937 " \n"
3938 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3939 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3940 }
3941
TEST_F(FormatTest,LayoutStatementsAroundPreprocessorDirectives)3942 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3943 EXPECT_EQ("int\n"
3944 "#define A\n"
3945 " a;",
3946 format("int\n#define A\na;"));
3947 verifyFormat("functionCallTo(\n"
3948 " someOtherFunction(\n"
3949 " withSomeParameters, whichInSequence,\n"
3950 " areLongerThanALine(andAnotherCall,\n"
3951 "#define A B\n"
3952 " withMoreParamters,\n"
3953 " whichStronglyInfluenceTheLayout),\n"
3954 " andMoreParameters),\n"
3955 " trailing);",
3956 getLLVMStyleWithColumns(69));
3957 verifyFormat("Foo::Foo()\n"
3958 "#ifdef BAR\n"
3959 " : baz(0)\n"
3960 "#endif\n"
3961 "{\n"
3962 "}");
3963 verifyFormat("void f() {\n"
3964 " if (true)\n"
3965 "#ifdef A\n"
3966 " f(42);\n"
3967 " x();\n"
3968 "#else\n"
3969 " g();\n"
3970 " x();\n"
3971 "#endif\n"
3972 "}");
3973 verifyFormat("void f(param1, param2,\n"
3974 " param3,\n"
3975 "#ifdef A\n"
3976 " param4(param5,\n"
3977 "#ifdef A1\n"
3978 " param6,\n"
3979 "#ifdef A2\n"
3980 " param7),\n"
3981 "#else\n"
3982 " param8),\n"
3983 " param9,\n"
3984 "#endif\n"
3985 " param10,\n"
3986 "#endif\n"
3987 " param11)\n"
3988 "#else\n"
3989 " param12)\n"
3990 "#endif\n"
3991 "{\n"
3992 " x();\n"
3993 "}",
3994 getLLVMStyleWithColumns(28));
3995 verifyFormat("#if 1\n"
3996 "int i;");
3997 verifyFormat("#if 1\n"
3998 "#endif\n"
3999 "#if 1\n"
4000 "#else\n"
4001 "#endif\n");
4002 verifyFormat("DEBUG({\n"
4003 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4004 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
4005 "});\n"
4006 "#if a\n"
4007 "#else\n"
4008 "#endif");
4009
4010 verifyIncompleteFormat("void f(\n"
4011 "#if A\n"
4012 ");\n"
4013 "#else\n"
4014 "#endif");
4015 }
4016
TEST_F(FormatTest,GraciouslyHandleIncorrectPreprocessorConditions)4017 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
4018 verifyFormat("#endif\n"
4019 "#if B");
4020 }
4021
TEST_F(FormatTest,FormatsJoinedLinesOnSubsequentRuns)4022 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
4023 FormatStyle SingleLine = getLLVMStyle();
4024 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
4025 verifyFormat("#if 0\n"
4026 "#elif 1\n"
4027 "#endif\n"
4028 "void foo() {\n"
4029 " if (test) foo2();\n"
4030 "}",
4031 SingleLine);
4032 }
4033
TEST_F(FormatTest,LayoutBlockInsideParens)4034 TEST_F(FormatTest, LayoutBlockInsideParens) {
4035 verifyFormat("functionCall({ int i; });");
4036 verifyFormat("functionCall({\n"
4037 " int i;\n"
4038 " int j;\n"
4039 "});");
4040 verifyFormat("functionCall(\n"
4041 " {\n"
4042 " int i;\n"
4043 " int j;\n"
4044 " },\n"
4045 " aaaa, bbbb, cccc);");
4046 verifyFormat("functionA(functionB({\n"
4047 " int i;\n"
4048 " int j;\n"
4049 " }),\n"
4050 " aaaa, bbbb, cccc);");
4051 verifyFormat("functionCall(\n"
4052 " {\n"
4053 " int i;\n"
4054 " int j;\n"
4055 " },\n"
4056 " aaaa, bbbb, // comment\n"
4057 " cccc);");
4058 verifyFormat("functionA(functionB({\n"
4059 " int i;\n"
4060 " int j;\n"
4061 " }),\n"
4062 " aaaa, bbbb, // comment\n"
4063 " cccc);");
4064 verifyFormat("functionCall(aaaa, bbbb, { int i; });");
4065 verifyFormat("functionCall(aaaa, bbbb, {\n"
4066 " int i;\n"
4067 " int j;\n"
4068 "});");
4069 verifyFormat(
4070 "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
4071 " {\n"
4072 " int i; // break\n"
4073 " },\n"
4074 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4075 " ccccccccccccccccc));");
4076 verifyFormat("DEBUG({\n"
4077 " if (a)\n"
4078 " f();\n"
4079 "});");
4080 }
4081
TEST_F(FormatTest,LayoutBlockInsideStatement)4082 TEST_F(FormatTest, LayoutBlockInsideStatement) {
4083 EXPECT_EQ("SOME_MACRO { int i; }\n"
4084 "int i;",
4085 format(" SOME_MACRO {int i;} int i;"));
4086 }
4087
TEST_F(FormatTest,LayoutNestedBlocks)4088 TEST_F(FormatTest, LayoutNestedBlocks) {
4089 verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
4090 " struct s {\n"
4091 " int i;\n"
4092 " };\n"
4093 " s kBitsToOs[] = {{10}};\n"
4094 " for (int i = 0; i < 10; ++i)\n"
4095 " return;\n"
4096 "}");
4097 verifyFormat("call(parameter, {\n"
4098 " something();\n"
4099 " // Comment using all columns.\n"
4100 " somethingelse();\n"
4101 "});",
4102 getLLVMStyleWithColumns(40));
4103 verifyFormat("DEBUG( //\n"
4104 " { f(); }, a);");
4105 verifyFormat("DEBUG( //\n"
4106 " {\n"
4107 " f(); //\n"
4108 " },\n"
4109 " a);");
4110
4111 EXPECT_EQ("call(parameter, {\n"
4112 " something();\n"
4113 " // Comment too\n"
4114 " // looooooooooong.\n"
4115 " somethingElse();\n"
4116 "});",
4117 format("call(parameter, {\n"
4118 " something();\n"
4119 " // Comment too looooooooooong.\n"
4120 " somethingElse();\n"
4121 "});",
4122 getLLVMStyleWithColumns(29)));
4123 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });"));
4124 EXPECT_EQ("DEBUG({ // comment\n"
4125 " int i;\n"
4126 "});",
4127 format("DEBUG({ // comment\n"
4128 "int i;\n"
4129 "});"));
4130 EXPECT_EQ("DEBUG({\n"
4131 " int i;\n"
4132 "\n"
4133 " // comment\n"
4134 " int j;\n"
4135 "});",
4136 format("DEBUG({\n"
4137 " int i;\n"
4138 "\n"
4139 " // comment\n"
4140 " int j;\n"
4141 "});"));
4142
4143 verifyFormat("DEBUG({\n"
4144 " if (a)\n"
4145 " return;\n"
4146 "});");
4147 verifyGoogleFormat("DEBUG({\n"
4148 " if (a) return;\n"
4149 "});");
4150 FormatStyle Style = getGoogleStyle();
4151 Style.ColumnLimit = 45;
4152 verifyFormat("Debug(\n"
4153 " aaaaa,\n"
4154 " {\n"
4155 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
4156 " },\n"
4157 " a);",
4158 Style);
4159
4160 verifyFormat("SomeFunction({MACRO({ return output; }), b});");
4161
4162 verifyNoCrash("^{v^{a}}");
4163 }
4164
TEST_F(FormatTest,FormatNestedBlocksInMacros)4165 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
4166 EXPECT_EQ("#define MACRO() \\\n"
4167 " Debug(aaa, /* force line break */ \\\n"
4168 " { \\\n"
4169 " int i; \\\n"
4170 " int j; \\\n"
4171 " })",
4172 format("#define MACRO() Debug(aaa, /* force line break */ \\\n"
4173 " { int i; int j; })",
4174 getGoogleStyle()));
4175
4176 EXPECT_EQ("#define A \\\n"
4177 " [] { \\\n"
4178 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
4179 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
4180 " }",
4181 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
4182 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
4183 getGoogleStyle()));
4184 }
4185
TEST_F(FormatTest,PutEmptyBlocksIntoOneLine)4186 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
4187 EXPECT_EQ("{}", format("{}"));
4188 verifyFormat("enum E {};");
4189 verifyFormat("enum E {}");
4190 FormatStyle Style = getLLVMStyle();
4191 Style.SpaceInEmptyBlock = true;
4192 EXPECT_EQ("void f() { }", format("void f() {}", Style));
4193 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
4194 EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
4195 }
4196
TEST_F(FormatTest,FormatBeginBlockEndMacros)4197 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
4198 FormatStyle Style = getLLVMStyle();
4199 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
4200 Style.MacroBlockEnd = "^[A-Z_]+_END$";
4201 verifyFormat("FOO_BEGIN\n"
4202 " FOO_ENTRY\n"
4203 "FOO_END",
4204 Style);
4205 verifyFormat("FOO_BEGIN\n"
4206 " NESTED_FOO_BEGIN\n"
4207 " NESTED_FOO_ENTRY\n"
4208 " NESTED_FOO_END\n"
4209 "FOO_END",
4210 Style);
4211 verifyFormat("FOO_BEGIN(Foo, Bar)\n"
4212 " int x;\n"
4213 " x = 1;\n"
4214 "FOO_END(Baz)",
4215 Style);
4216 }
4217
4218 //===----------------------------------------------------------------------===//
4219 // Line break tests.
4220 //===----------------------------------------------------------------------===//
4221
TEST_F(FormatTest,PreventConfusingIndents)4222 TEST_F(FormatTest, PreventConfusingIndents) {
4223 verifyFormat(
4224 "void f() {\n"
4225 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
4226 " parameter, parameter, parameter)),\n"
4227 " SecondLongCall(parameter));\n"
4228 "}");
4229 verifyFormat(
4230 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4231 " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4233 " aaaaaaaaaaaaaaaaaaaaaaaa);");
4234 verifyFormat(
4235 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4236 " [aaaaaaaaaaaaaaaaaaaaaaaa\n"
4237 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
4238 " [aaaaaaaaaaaaaaaaaaaaaaaa]];");
4239 verifyFormat(
4240 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4241 " aaaaaaaaaaaaaaaaaaaaaaaa<\n"
4242 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
4243 " aaaaaaaaaaaaaaaaaaaaaaaa>;");
4244 verifyFormat("int a = bbbb && ccc &&\n"
4245 " fffff(\n"
4246 "#define A Just forcing a new line\n"
4247 " ddd);");
4248 }
4249
TEST_F(FormatTest,LineBreakingInBinaryExpressions)4250 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
4251 verifyFormat(
4252 "bool aaaaaaa =\n"
4253 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
4254 " bbbbbbbb();");
4255 verifyFormat(
4256 "bool aaaaaaa =\n"
4257 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
4258 " bbbbbbbb();");
4259
4260 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4261 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
4262 " ccccccccc == ddddddddddd;");
4263 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4264 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
4265 " ccccccccc == ddddddddddd;");
4266 verifyFormat(
4267 "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
4269 " ccccccccc == ddddddddddd;");
4270
4271 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4272 " aaaaaa) &&\n"
4273 " bbbbbb && cccccc;");
4274 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4275 " aaaaaa) >>\n"
4276 " bbbbbb;");
4277 verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
4278 " SourceMgr.getSpellingColumnNumber(\n"
4279 " TheLine.Last->FormatTok.Tok.getLocation()) -\n"
4280 " 1);");
4281
4282 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4283 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
4284 " cccccc) {\n}");
4285 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4286 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4287 " cccccc) {\n}");
4288 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4289 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4290 " cccccc) {\n}");
4291 verifyFormat("b = a &&\n"
4292 " // Comment\n"
4293 " b.c && d;");
4294
4295 // If the LHS of a comparison is not a binary expression itself, the
4296 // additional linebreak confuses many people.
4297 verifyFormat(
4298 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4299 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
4300 "}");
4301 verifyFormat(
4302 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4304 "}");
4305 verifyFormat(
4306 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
4307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4308 "}");
4309 verifyFormat(
4310 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4311 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
4312 "}");
4313 // Even explicit parentheses stress the precedence enough to make the
4314 // additional break unnecessary.
4315 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4316 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4317 "}");
4318 // This cases is borderline, but with the indentation it is still readable.
4319 verifyFormat(
4320 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4321 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4322 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4323 "}",
4324 getLLVMStyleWithColumns(75));
4325
4326 // If the LHS is a binary expression, we should still use the additional break
4327 // as otherwise the formatting hides the operator precedence.
4328 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4329 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4330 " 5) {\n"
4331 "}");
4332 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4333 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
4334 " 5) {\n"
4335 "}");
4336
4337 FormatStyle OnePerLine = getLLVMStyle();
4338 OnePerLine.BinPackParameters = false;
4339 verifyFormat(
4340 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4341 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4342 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
4343 OnePerLine);
4344
4345 verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
4346 " .aaa(aaaaaaaaaaaaa) *\n"
4347 " aaaaaaa +\n"
4348 " aaaaaaa;",
4349 getLLVMStyleWithColumns(40));
4350 }
4351
TEST_F(FormatTest,ExpressionIndentation)4352 TEST_F(FormatTest, ExpressionIndentation) {
4353 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4354 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4355 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4356 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4357 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
4358 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
4359 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4360 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
4361 " ccccccccccccccccccccccccccccccccccccccccc;");
4362 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4363 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4364 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4365 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4366 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4367 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4368 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4369 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4370 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4371 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4372 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4373 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4374 verifyFormat("if () {\n"
4375 "} else if (aaaaa && bbbbb > // break\n"
4376 " ccccc) {\n"
4377 "}");
4378 verifyFormat("if () {\n"
4379 "} else if constexpr (aaaaa && bbbbb > // break\n"
4380 " ccccc) {\n"
4381 "}");
4382 verifyFormat("if () {\n"
4383 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
4384 " ccccc) {\n"
4385 "}");
4386 verifyFormat("if () {\n"
4387 "} else if (aaaaa &&\n"
4388 " bbbbb > // break\n"
4389 " ccccc &&\n"
4390 " ddddd) {\n"
4391 "}");
4392
4393 // Presence of a trailing comment used to change indentation of b.
4394 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
4395 " b;\n"
4396 "return aaaaaaaaaaaaaaaaaaa +\n"
4397 " b; //",
4398 getLLVMStyleWithColumns(30));
4399 }
4400
TEST_F(FormatTest,ExpressionIndentationBreakingBeforeOperators)4401 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
4402 // Not sure what the best system is here. Like this, the LHS can be found
4403 // immediately above an operator (everything with the same or a higher
4404 // indent). The RHS is aligned right of the operator and so compasses
4405 // everything until something with the same indent as the operator is found.
4406 // FIXME: Is this a good system?
4407 FormatStyle Style = getLLVMStyle();
4408 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4409 verifyFormat(
4410 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4411 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4412 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4413 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4414 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4415 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4416 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4417 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4418 " > ccccccccccccccccccccccccccccccccccccccccc;",
4419 Style);
4420 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4421 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4422 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4423 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4424 Style);
4425 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4426 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4427 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4428 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4429 Style);
4430 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4431 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4432 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4433 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4434 Style);
4435 verifyFormat("if () {\n"
4436 "} else if (aaaaa\n"
4437 " && bbbbb // break\n"
4438 " > ccccc) {\n"
4439 "}",
4440 Style);
4441 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4442 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4443 Style);
4444 verifyFormat("return (a)\n"
4445 " // comment\n"
4446 " + b;",
4447 Style);
4448 verifyFormat(
4449 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4450 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4451 " + cc;",
4452 Style);
4453
4454 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4455 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4456 Style);
4457
4458 // Forced by comments.
4459 verifyFormat(
4460 "unsigned ContentSize =\n"
4461 " sizeof(int16_t) // DWARF ARange version number\n"
4462 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4463 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
4464 " + sizeof(int8_t); // Segment Size (in bytes)");
4465
4466 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4467 " == boost::fusion::at_c<1>(iiii).second;",
4468 Style);
4469
4470 Style.ColumnLimit = 60;
4471 verifyFormat("zzzzzzzzzz\n"
4472 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4473 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4474 Style);
4475
4476 Style.ColumnLimit = 80;
4477 Style.IndentWidth = 4;
4478 Style.TabWidth = 4;
4479 Style.UseTab = FormatStyle::UT_Always;
4480 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4481 Style.AlignOperands = FormatStyle::OAS_DontAlign;
4482 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
4483 "\t&& (someOtherLongishConditionPart1\n"
4484 "\t\t|| someOtherEvenLongerNestedConditionPart2);",
4485 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
4486 "(someOtherLongishConditionPart1 || "
4487 "someOtherEvenLongerNestedConditionPart2);",
4488 Style));
4489 }
4490
TEST_F(FormatTest,ExpressionIndentationStrictAlign)4491 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
4492 FormatStyle Style = getLLVMStyle();
4493 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4494 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
4495
4496 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4497 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4498 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4499 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4500 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4501 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4502 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4503 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4504 " > ccccccccccccccccccccccccccccccccccccccccc;",
4505 Style);
4506 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4507 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4508 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4509 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4510 Style);
4511 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4512 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4513 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4514 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4515 Style);
4516 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4517 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4518 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4519 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4520 Style);
4521 verifyFormat("if () {\n"
4522 "} else if (aaaaa\n"
4523 " && bbbbb // break\n"
4524 " > ccccc) {\n"
4525 "}",
4526 Style);
4527 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4528 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4529 Style);
4530 verifyFormat("return (a)\n"
4531 " // comment\n"
4532 " + b;",
4533 Style);
4534 verifyFormat(
4535 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4536 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4537 " + cc;",
4538 Style);
4539 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
4540 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4541 " : 3333333333333333;",
4542 Style);
4543 verifyFormat(
4544 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
4545 " : ccccccccccccccc ? dddddddddddddddddd\n"
4546 " : eeeeeeeeeeeeeeeeee)\n"
4547 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4548 " : 3333333333333333;",
4549 Style);
4550 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4551 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4552 Style);
4553
4554 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4555 " == boost::fusion::at_c<1>(iiii).second;",
4556 Style);
4557
4558 Style.ColumnLimit = 60;
4559 verifyFormat("zzzzzzzzzzzzz\n"
4560 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4561 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4562 Style);
4563
4564 // Forced by comments.
4565 Style.ColumnLimit = 80;
4566 verifyFormat(
4567 "unsigned ContentSize\n"
4568 " = sizeof(int16_t) // DWARF ARange version number\n"
4569 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4570 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
4571 " + sizeof(int8_t); // Segment Size (in bytes)",
4572 Style);
4573
4574 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4575 verifyFormat(
4576 "unsigned ContentSize =\n"
4577 " sizeof(int16_t) // DWARF ARange version number\n"
4578 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4579 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
4580 " + sizeof(int8_t); // Segment Size (in bytes)",
4581 Style);
4582
4583 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4584 verifyFormat(
4585 "unsigned ContentSize =\n"
4586 " sizeof(int16_t) // DWARF ARange version number\n"
4587 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4588 " + sizeof(int8_t) // Pointer Size (in bytes)\n"
4589 " + sizeof(int8_t); // Segment Size (in bytes)",
4590 Style);
4591 }
4592
TEST_F(FormatTest,EnforcedOperatorWraps)4593 TEST_F(FormatTest, EnforcedOperatorWraps) {
4594 // Here we'd like to wrap after the || operators, but a comment is forcing an
4595 // earlier wrap.
4596 verifyFormat("bool x = aaaaa //\n"
4597 " || bbbbb\n"
4598 " //\n"
4599 " || cccc;");
4600 }
4601
TEST_F(FormatTest,NoOperandAlignment)4602 TEST_F(FormatTest, NoOperandAlignment) {
4603 FormatStyle Style = getLLVMStyle();
4604 Style.AlignOperands = FormatStyle::OAS_DontAlign;
4605 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
4606 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4607 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4608 Style);
4609 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4610 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4611 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4612 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4613 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4614 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4615 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4616 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4617 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4618 " > ccccccccccccccccccccccccccccccccccccccccc;",
4619 Style);
4620
4621 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4622 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4623 " + cc;",
4624 Style);
4625 verifyFormat("int a = aa\n"
4626 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4627 " * cccccccccccccccccccccccccccccccccccc;\n",
4628 Style);
4629
4630 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4631 verifyFormat("return (a > b\n"
4632 " // comment1\n"
4633 " // comment2\n"
4634 " || c);",
4635 Style);
4636 }
4637
TEST_F(FormatTest,BreakingBeforeNonAssigmentOperators)4638 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
4639 FormatStyle Style = getLLVMStyle();
4640 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4641 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4642 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4643 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4644 Style);
4645 }
4646
TEST_F(FormatTest,AllowBinPackingInsideArguments)4647 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
4648 FormatStyle Style = getLLVMStyle();
4649 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4650 Style.BinPackArguments = false;
4651 Style.ColumnLimit = 40;
4652 verifyFormat("void test() {\n"
4653 " someFunction(\n"
4654 " this + argument + is + quite\n"
4655 " + long + so + it + gets + wrapped\n"
4656 " + but + remains + bin - packed);\n"
4657 "}",
4658 Style);
4659 verifyFormat("void test() {\n"
4660 " someFunction(arg1,\n"
4661 " this + argument + is\n"
4662 " + quite + long + so\n"
4663 " + it + gets + wrapped\n"
4664 " + but + remains + bin\n"
4665 " - packed,\n"
4666 " arg3);\n"
4667 "}",
4668 Style);
4669 verifyFormat("void test() {\n"
4670 " someFunction(\n"
4671 " arg1,\n"
4672 " this + argument + has\n"
4673 " + anotherFunc(nested,\n"
4674 " calls + whose\n"
4675 " + arguments\n"
4676 " + are + also\n"
4677 " + wrapped,\n"
4678 " in + addition)\n"
4679 " + to + being + bin - packed,\n"
4680 " arg3);\n"
4681 "}",
4682 Style);
4683
4684 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4685 verifyFormat("void test() {\n"
4686 " someFunction(\n"
4687 " arg1,\n"
4688 " this + argument + has +\n"
4689 " anotherFunc(nested,\n"
4690 " calls + whose +\n"
4691 " arguments +\n"
4692 " are + also +\n"
4693 " wrapped,\n"
4694 " in + addition) +\n"
4695 " to + being + bin - packed,\n"
4696 " arg3);\n"
4697 "}",
4698 Style);
4699 }
4700
TEST_F(FormatTest,ConstructorInitializers)4701 TEST_F(FormatTest, ConstructorInitializers) {
4702 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4703 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
4704 getLLVMStyleWithColumns(45));
4705 verifyFormat("Constructor()\n"
4706 " : Inttializer(FitsOnTheLine) {}",
4707 getLLVMStyleWithColumns(44));
4708 verifyFormat("Constructor()\n"
4709 " : Inttializer(FitsOnTheLine) {}",
4710 getLLVMStyleWithColumns(43));
4711
4712 verifyFormat("template <typename T>\n"
4713 "Constructor() : Initializer(FitsOnTheLine) {}",
4714 getLLVMStyleWithColumns(45));
4715
4716 verifyFormat(
4717 "SomeClass::Constructor()\n"
4718 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4719
4720 verifyFormat(
4721 "SomeClass::Constructor()\n"
4722 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4723 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
4724 verifyFormat(
4725 "SomeClass::Constructor()\n"
4726 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4727 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4728 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4729 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4730 " : aaaaaaaaaa(aaaaaa) {}");
4731
4732 verifyFormat("Constructor()\n"
4733 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4734 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4735 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4736 " aaaaaaaaaaaaaaaaaaaaaaa() {}");
4737
4738 verifyFormat("Constructor()\n"
4739 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4740 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4741
4742 verifyFormat("Constructor(int Parameter = 0)\n"
4743 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4744 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
4745 verifyFormat("Constructor()\n"
4746 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4747 "}",
4748 getLLVMStyleWithColumns(60));
4749 verifyFormat("Constructor()\n"
4750 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4751 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
4752
4753 // Here a line could be saved by splitting the second initializer onto two
4754 // lines, but that is not desirable.
4755 verifyFormat("Constructor()\n"
4756 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4757 " aaaaaaaaaaa(aaaaaaaaaaa),\n"
4758 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4759
4760 FormatStyle OnePerLine = getLLVMStyle();
4761 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4762 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
4763 verifyFormat("SomeClass::Constructor()\n"
4764 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4765 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4766 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4767 OnePerLine);
4768 verifyFormat("SomeClass::Constructor()\n"
4769 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4770 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4771 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4772 OnePerLine);
4773 verifyFormat("MyClass::MyClass(int var)\n"
4774 " : some_var_(var), // 4 space indent\n"
4775 " some_other_var_(var + 1) { // lined up\n"
4776 "}",
4777 OnePerLine);
4778 verifyFormat("Constructor()\n"
4779 " : aaaaa(aaaaaa),\n"
4780 " aaaaa(aaaaaa),\n"
4781 " aaaaa(aaaaaa),\n"
4782 " aaaaa(aaaaaa),\n"
4783 " aaaaa(aaaaaa) {}",
4784 OnePerLine);
4785 verifyFormat("Constructor()\n"
4786 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4787 " aaaaaaaaaaaaaaaaaaaaaa) {}",
4788 OnePerLine);
4789 OnePerLine.BinPackParameters = false;
4790 verifyFormat(
4791 "Constructor()\n"
4792 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4793 " aaaaaaaaaaa().aaa(),\n"
4794 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4795 OnePerLine);
4796 OnePerLine.ColumnLimit = 60;
4797 verifyFormat("Constructor()\n"
4798 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
4799 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4800 OnePerLine);
4801
4802 EXPECT_EQ("Constructor()\n"
4803 " : // Comment forcing unwanted break.\n"
4804 " aaaa(aaaa) {}",
4805 format("Constructor() :\n"
4806 " // Comment forcing unwanted break.\n"
4807 " aaaa(aaaa) {}"));
4808 }
4809
TEST_F(FormatTest,AllowAllConstructorInitializersOnNextLine)4810 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
4811 FormatStyle Style = getLLVMStyle();
4812 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4813 Style.ColumnLimit = 60;
4814 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4815 Style.AllowAllConstructorInitializersOnNextLine = true;
4816 Style.BinPackParameters = false;
4817
4818 for (int i = 0; i < 4; ++i) {
4819 // Test all combinations of parameters that should not have an effect.
4820 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4821 Style.AllowAllArgumentsOnNextLine = i & 2;
4822
4823 Style.AllowAllConstructorInitializersOnNextLine = true;
4824 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4825 verifyFormat("Constructor()\n"
4826 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4827 Style);
4828 verifyFormat("Constructor() : a(a), b(b) {}", Style);
4829
4830 Style.AllowAllConstructorInitializersOnNextLine = false;
4831 verifyFormat("Constructor()\n"
4832 " : aaaaaaaaaaaaaaaaaaaa(a)\n"
4833 " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4834 Style);
4835 verifyFormat("Constructor() : a(a), b(b) {}", Style);
4836
4837 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4838 Style.AllowAllConstructorInitializersOnNextLine = true;
4839 verifyFormat("Constructor()\n"
4840 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4841 Style);
4842
4843 Style.AllowAllConstructorInitializersOnNextLine = false;
4844 verifyFormat("Constructor()\n"
4845 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
4846 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
4847 Style);
4848
4849 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4850 Style.AllowAllConstructorInitializersOnNextLine = true;
4851 verifyFormat("Constructor() :\n"
4852 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4853 Style);
4854
4855 Style.AllowAllConstructorInitializersOnNextLine = false;
4856 verifyFormat("Constructor() :\n"
4857 " aaaaaaaaaaaaaaaaaa(a),\n"
4858 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
4859 Style);
4860 }
4861
4862 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
4863 // AllowAllConstructorInitializersOnNextLine in all
4864 // BreakConstructorInitializers modes
4865 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4866 Style.AllowAllParametersOfDeclarationOnNextLine = true;
4867 Style.AllowAllConstructorInitializersOnNextLine = false;
4868 verifyFormat("SomeClassWithALongName::Constructor(\n"
4869 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4870 " : aaaaaaaaaaaaaaaaaaaa(a)\n"
4871 " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4872 Style);
4873
4874 Style.AllowAllConstructorInitializersOnNextLine = true;
4875 verifyFormat("SomeClassWithALongName::Constructor(\n"
4876 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4877 " int bbbbbbbbbbbbb,\n"
4878 " int cccccccccccccccc)\n"
4879 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4880 Style);
4881
4882 Style.AllowAllParametersOfDeclarationOnNextLine = false;
4883 Style.AllowAllConstructorInitializersOnNextLine = false;
4884 verifyFormat("SomeClassWithALongName::Constructor(\n"
4885 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4886 " int bbbbbbbbbbbbb)\n"
4887 " : aaaaaaaaaaaaaaaaaaaa(a)\n"
4888 " , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4889 Style);
4890
4891 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4892
4893 Style.AllowAllParametersOfDeclarationOnNextLine = true;
4894 verifyFormat("SomeClassWithALongName::Constructor(\n"
4895 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4896 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
4897 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
4898 Style);
4899
4900 Style.AllowAllConstructorInitializersOnNextLine = true;
4901 verifyFormat("SomeClassWithALongName::Constructor(\n"
4902 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4903 " int bbbbbbbbbbbbb,\n"
4904 " int cccccccccccccccc)\n"
4905 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4906 Style);
4907
4908 Style.AllowAllParametersOfDeclarationOnNextLine = false;
4909 Style.AllowAllConstructorInitializersOnNextLine = false;
4910 verifyFormat("SomeClassWithALongName::Constructor(\n"
4911 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4912 " int bbbbbbbbbbbbb)\n"
4913 " : aaaaaaaaaaaaaaaaaaaa(a),\n"
4914 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
4915 Style);
4916
4917 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4918 Style.AllowAllParametersOfDeclarationOnNextLine = true;
4919 verifyFormat("SomeClassWithALongName::Constructor(\n"
4920 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
4921 " aaaaaaaaaaaaaaaaaaaa(a),\n"
4922 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
4923 Style);
4924
4925 Style.AllowAllConstructorInitializersOnNextLine = true;
4926 verifyFormat("SomeClassWithALongName::Constructor(\n"
4927 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4928 " int bbbbbbbbbbbbb,\n"
4929 " int cccccccccccccccc) :\n"
4930 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4931 Style);
4932
4933 Style.AllowAllParametersOfDeclarationOnNextLine = false;
4934 Style.AllowAllConstructorInitializersOnNextLine = false;
4935 verifyFormat("SomeClassWithALongName::Constructor(\n"
4936 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4937 " int bbbbbbbbbbbbb) :\n"
4938 " aaaaaaaaaaaaaaaaaaaa(a),\n"
4939 " bbbbbbbbbbbbbbbbbbbbb(b) {}",
4940 Style);
4941 }
4942
TEST_F(FormatTest,AllowAllArgumentsOnNextLine)4943 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
4944 FormatStyle Style = getLLVMStyle();
4945 Style.ColumnLimit = 60;
4946 Style.BinPackArguments = false;
4947 for (int i = 0; i < 4; ++i) {
4948 // Test all combinations of parameters that should not have an effect.
4949 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4950 Style.AllowAllConstructorInitializersOnNextLine = i & 2;
4951
4952 Style.AllowAllArgumentsOnNextLine = true;
4953 verifyFormat("void foo() {\n"
4954 " FunctionCallWithReallyLongName(\n"
4955 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
4956 "}",
4957 Style);
4958 Style.AllowAllArgumentsOnNextLine = false;
4959 verifyFormat("void foo() {\n"
4960 " FunctionCallWithReallyLongName(\n"
4961 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4962 " bbbbbbbbbbbb);\n"
4963 "}",
4964 Style);
4965
4966 Style.AllowAllArgumentsOnNextLine = true;
4967 verifyFormat("void foo() {\n"
4968 " auto VariableWithReallyLongName = {\n"
4969 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
4970 "}",
4971 Style);
4972 Style.AllowAllArgumentsOnNextLine = false;
4973 verifyFormat("void foo() {\n"
4974 " auto VariableWithReallyLongName = {\n"
4975 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4976 " bbbbbbbbbbbb};\n"
4977 "}",
4978 Style);
4979 }
4980
4981 // This parameter should not affect declarations.
4982 Style.BinPackParameters = false;
4983 Style.AllowAllArgumentsOnNextLine = false;
4984 Style.AllowAllParametersOfDeclarationOnNextLine = true;
4985 verifyFormat("void FunctionCallWithReallyLongName(\n"
4986 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
4987 Style);
4988 Style.AllowAllParametersOfDeclarationOnNextLine = false;
4989 verifyFormat("void FunctionCallWithReallyLongName(\n"
4990 " int aaaaaaaaaaaaaaaaaaaaaaa,\n"
4991 " int bbbbbbbbbbbb);",
4992 Style);
4993 }
4994
TEST_F(FormatTest,AllowAllArgumentsOnNextLineDontAlign)4995 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
4996 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
4997 // and BAS_Align.
4998 auto Style = getLLVMStyle();
4999 Style.ColumnLimit = 35;
5000 StringRef Input = "functionCall(paramA, paramB, paramC);\n"
5001 "void functionDecl(int A, int B, int C);";
5002 Style.AllowAllArgumentsOnNextLine = false;
5003 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5004 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5005 " paramC);\n"
5006 "void functionDecl(int A, int B,\n"
5007 " int C);"),
5008 format(Input, Style));
5009 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5010 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5011 " paramC);\n"
5012 "void functionDecl(int A, int B,\n"
5013 " int C);"),
5014 format(Input, Style));
5015 // However, BAS_AlwaysBreak should take precedence over
5016 // AllowAllArgumentsOnNextLine.
5017 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5018 EXPECT_EQ(StringRef("functionCall(\n"
5019 " paramA, paramB, paramC);\n"
5020 "void functionDecl(\n"
5021 " int A, int B, int C);"),
5022 format(Input, Style));
5023
5024 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
5025 // first argument.
5026 Style.AllowAllArgumentsOnNextLine = true;
5027 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5028 EXPECT_EQ(StringRef("functionCall(\n"
5029 " paramA, paramB, paramC);\n"
5030 "void functionDecl(\n"
5031 " int A, int B, int C);"),
5032 format(Input, Style));
5033 // It wouldn't fit on one line with aligned parameters so this setting
5034 // doesn't change anything for BAS_Align.
5035 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5036 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5037 " paramC);\n"
5038 "void functionDecl(int A, int B,\n"
5039 " int C);"),
5040 format(Input, Style));
5041 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5042 EXPECT_EQ(StringRef("functionCall(\n"
5043 " paramA, paramB, paramC);\n"
5044 "void functionDecl(\n"
5045 " int A, int B, int C);"),
5046 format(Input, Style));
5047 }
5048
TEST_F(FormatTest,BreakConstructorInitializersAfterColon)5049 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
5050 FormatStyle Style = getLLVMStyle();
5051 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
5052
5053 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5054 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
5055 getStyleWithColumns(Style, 45));
5056 verifyFormat("Constructor() :\n"
5057 " Initializer(FitsOnTheLine) {}",
5058 getStyleWithColumns(Style, 44));
5059 verifyFormat("Constructor() :\n"
5060 " Initializer(FitsOnTheLine) {}",
5061 getStyleWithColumns(Style, 43));
5062
5063 verifyFormat("template <typename T>\n"
5064 "Constructor() : Initializer(FitsOnTheLine) {}",
5065 getStyleWithColumns(Style, 50));
5066 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5067 verifyFormat(
5068 "SomeClass::Constructor() :\n"
5069 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5070 Style);
5071
5072 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
5073 verifyFormat(
5074 "SomeClass::Constructor() :\n"
5075 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5076 Style);
5077
5078 verifyFormat(
5079 "SomeClass::Constructor() :\n"
5080 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5081 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5082 Style);
5083 verifyFormat(
5084 "SomeClass::Constructor() :\n"
5085 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5086 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5087 Style);
5088 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5089 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
5090 " aaaaaaaaaa(aaaaaa) {}",
5091 Style);
5092
5093 verifyFormat("Constructor() :\n"
5094 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5095 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5096 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5097 " aaaaaaaaaaaaaaaaaaaaaaa() {}",
5098 Style);
5099
5100 verifyFormat("Constructor() :\n"
5101 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5102 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5103 Style);
5104
5105 verifyFormat("Constructor(int Parameter = 0) :\n"
5106 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5107 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
5108 Style);
5109 verifyFormat("Constructor() :\n"
5110 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5111 "}",
5112 getStyleWithColumns(Style, 60));
5113 verifyFormat("Constructor() :\n"
5114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5115 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
5116 Style);
5117
5118 // Here a line could be saved by splitting the second initializer onto two
5119 // lines, but that is not desirable.
5120 verifyFormat("Constructor() :\n"
5121 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5122 " aaaaaaaaaaa(aaaaaaaaaaa),\n"
5123 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5124 Style);
5125
5126 FormatStyle OnePerLine = Style;
5127 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5128 OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
5129 verifyFormat("SomeClass::Constructor() :\n"
5130 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5131 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5132 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5133 OnePerLine);
5134 verifyFormat("SomeClass::Constructor() :\n"
5135 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5136 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5137 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5138 OnePerLine);
5139 verifyFormat("MyClass::MyClass(int var) :\n"
5140 " some_var_(var), // 4 space indent\n"
5141 " some_other_var_(var + 1) { // lined up\n"
5142 "}",
5143 OnePerLine);
5144 verifyFormat("Constructor() :\n"
5145 " aaaaa(aaaaaa),\n"
5146 " aaaaa(aaaaaa),\n"
5147 " aaaaa(aaaaaa),\n"
5148 " aaaaa(aaaaaa),\n"
5149 " aaaaa(aaaaaa) {}",
5150 OnePerLine);
5151 verifyFormat("Constructor() :\n"
5152 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
5153 " aaaaaaaaaaaaaaaaaaaaaa) {}",
5154 OnePerLine);
5155 OnePerLine.BinPackParameters = false;
5156 verifyFormat("Constructor() :\n"
5157 " aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5158 " aaaaaaaaaaa().aaa(),\n"
5159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5160 OnePerLine);
5161 OnePerLine.ColumnLimit = 60;
5162 verifyFormat("Constructor() :\n"
5163 " aaaaaaaaaaaaaaaaaaaa(a),\n"
5164 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
5165 OnePerLine);
5166
5167 EXPECT_EQ("Constructor() :\n"
5168 " // Comment forcing unwanted break.\n"
5169 " aaaa(aaaa) {}",
5170 format("Constructor() :\n"
5171 " // Comment forcing unwanted break.\n"
5172 " aaaa(aaaa) {}",
5173 Style));
5174
5175 Style.ColumnLimit = 0;
5176 verifyFormat("SomeClass::Constructor() :\n"
5177 " a(a) {}",
5178 Style);
5179 verifyFormat("SomeClass::Constructor() noexcept :\n"
5180 " a(a) {}",
5181 Style);
5182 verifyFormat("SomeClass::Constructor() :\n"
5183 " a(a), b(b), c(c) {}",
5184 Style);
5185 verifyFormat("SomeClass::Constructor() :\n"
5186 " a(a) {\n"
5187 " foo();\n"
5188 " bar();\n"
5189 "}",
5190 Style);
5191
5192 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
5193 verifyFormat("SomeClass::Constructor() :\n"
5194 " a(a), b(b), c(c) {\n"
5195 "}",
5196 Style);
5197 verifyFormat("SomeClass::Constructor() :\n"
5198 " a(a) {\n"
5199 "}",
5200 Style);
5201
5202 Style.ColumnLimit = 80;
5203 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
5204 Style.ConstructorInitializerIndentWidth = 2;
5205 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
5206 verifyFormat("SomeClass::Constructor() :\n"
5207 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5208 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
5209 Style);
5210
5211 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
5212 // well
5213 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
5214 verifyFormat(
5215 "class SomeClass\n"
5216 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5217 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5218 Style);
5219 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
5220 verifyFormat(
5221 "class SomeClass\n"
5222 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5223 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5224 Style);
5225 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
5226 verifyFormat(
5227 "class SomeClass :\n"
5228 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5229 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5230 Style);
5231 }
5232
5233 #ifndef EXPENSIVE_CHECKS
5234 // Expensive checks enables libstdc++ checking which includes validating the
5235 // state of ranges used in std::priority_queue - this blows out the
5236 // runtime/scalability of the function and makes this test unacceptably slow.
TEST_F(FormatTest,MemoizationTests)5237 TEST_F(FormatTest, MemoizationTests) {
5238 // This breaks if the memoization lookup does not take \c Indent and
5239 // \c LastSpace into account.
5240 verifyFormat(
5241 "extern CFRunLoopTimerRef\n"
5242 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
5243 " CFTimeInterval interval, CFOptionFlags flags,\n"
5244 " CFIndex order, CFRunLoopTimerCallBack callout,\n"
5245 " CFRunLoopTimerContext *context) {}");
5246
5247 // Deep nesting somewhat works around our memoization.
5248 verifyFormat(
5249 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5250 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5251 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5252 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5253 " aaaaa())))))))))))))))))))))))))))))))))))))));",
5254 getLLVMStyleWithColumns(65));
5255 verifyFormat(
5256 "aaaaa(\n"
5257 " aaaaa,\n"
5258 " aaaaa(\n"
5259 " aaaaa,\n"
5260 " aaaaa(\n"
5261 " aaaaa,\n"
5262 " aaaaa(\n"
5263 " aaaaa,\n"
5264 " aaaaa(\n"
5265 " aaaaa,\n"
5266 " aaaaa(\n"
5267 " aaaaa,\n"
5268 " aaaaa(\n"
5269 " aaaaa,\n"
5270 " aaaaa(\n"
5271 " aaaaa,\n"
5272 " aaaaa(\n"
5273 " aaaaa,\n"
5274 " aaaaa(\n"
5275 " aaaaa,\n"
5276 " aaaaa(\n"
5277 " aaaaa,\n"
5278 " aaaaa(\n"
5279 " aaaaa,\n"
5280 " aaaaa))))))))))));",
5281 getLLVMStyleWithColumns(65));
5282 verifyFormat(
5283 "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"
5284 " a),\n"
5285 " a),\n"
5286 " a),\n"
5287 " a),\n"
5288 " a),\n"
5289 " a),\n"
5290 " a),\n"
5291 " a),\n"
5292 " a),\n"
5293 " a),\n"
5294 " a),\n"
5295 " a),\n"
5296 " a),\n"
5297 " a),\n"
5298 " a),\n"
5299 " a),\n"
5300 " a)",
5301 getLLVMStyleWithColumns(65));
5302
5303 // This test takes VERY long when memoization is broken.
5304 FormatStyle OnePerLine = getLLVMStyle();
5305 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5306 OnePerLine.BinPackParameters = false;
5307 std::string input = "Constructor()\n"
5308 " : aaaa(a,\n";
5309 for (unsigned i = 0, e = 80; i != e; ++i) {
5310 input += " a,\n";
5311 }
5312 input += " a) {}";
5313 verifyFormat(input, OnePerLine);
5314 }
5315 #endif
5316
TEST_F(FormatTest,BreaksAsHighAsPossible)5317 TEST_F(FormatTest, BreaksAsHighAsPossible) {
5318 verifyFormat(
5319 "void f() {\n"
5320 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
5321 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
5322 " f();\n"
5323 "}");
5324 verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
5325 " Intervals[i - 1].getRange().getLast()) {\n}");
5326 }
5327
TEST_F(FormatTest,BreaksFunctionDeclarations)5328 TEST_F(FormatTest, BreaksFunctionDeclarations) {
5329 // Principially, we break function declarations in a certain order:
5330 // 1) break amongst arguments.
5331 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
5332 " Cccccccccccccc cccccccccccccc);");
5333 verifyFormat("template <class TemplateIt>\n"
5334 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
5335 " TemplateIt *stop) {}");
5336
5337 // 2) break after return type.
5338 verifyFormat(
5339 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5340 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
5341 getGoogleStyle());
5342
5343 // 3) break after (.
5344 verifyFormat(
5345 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
5346 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
5347 getGoogleStyle());
5348
5349 // 4) break before after nested name specifiers.
5350 verifyFormat(
5351 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5352 "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
5353 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
5354 getGoogleStyle());
5355
5356 // However, there are exceptions, if a sufficient amount of lines can be
5357 // saved.
5358 // FIXME: The precise cut-offs wrt. the number of saved lines might need some
5359 // more adjusting.
5360 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5361 " Cccccccccccccc cccccccccc,\n"
5362 " Cccccccccccccc cccccccccc,\n"
5363 " Cccccccccccccc cccccccccc,\n"
5364 " Cccccccccccccc cccccccccc);");
5365 verifyFormat(
5366 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5367 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5368 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5369 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
5370 getGoogleStyle());
5371 verifyFormat(
5372 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5373 " Cccccccccccccc cccccccccc,\n"
5374 " Cccccccccccccc cccccccccc,\n"
5375 " Cccccccccccccc cccccccccc,\n"
5376 " Cccccccccccccc cccccccccc,\n"
5377 " Cccccccccccccc cccccccccc,\n"
5378 " Cccccccccccccc cccccccccc);");
5379 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5380 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5381 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5382 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5383 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
5384
5385 // Break after multi-line parameters.
5386 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5387 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5388 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5389 " bbbb bbbb);");
5390 verifyFormat("void SomeLoooooooooooongFunction(\n"
5391 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
5392 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5393 " int bbbbbbbbbbbbb);");
5394
5395 // Treat overloaded operators like other functions.
5396 verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5397 "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
5398 verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5399 "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
5400 verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5401 "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
5402 verifyGoogleFormat(
5403 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
5404 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5405 verifyGoogleFormat(
5406 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
5407 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5408 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5409 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5410 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
5411 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5412 verifyGoogleFormat(
5413 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
5414 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5415 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
5416 verifyGoogleFormat("template <typename T>\n"
5417 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5418 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
5419 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
5420
5421 FormatStyle Style = getLLVMStyle();
5422 Style.PointerAlignment = FormatStyle::PAS_Left;
5423 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5424 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
5425 Style);
5426 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
5427 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5428 Style);
5429 }
5430
TEST_F(FormatTest,DontBreakBeforeQualifiedOperator)5431 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
5432 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
5433 // Prefer keeping `::` followed by `operator` together.
5434 EXPECT_EQ("const aaaa::bbbbbbb &\n"
5435 "ccccccccc::operator++() {\n"
5436 " stuff();\n"
5437 "}",
5438 format("const aaaa::bbbbbbb\n"
5439 "&ccccccccc::operator++() { stuff(); }",
5440 getLLVMStyleWithColumns(40)));
5441 }
5442
TEST_F(FormatTest,TrailingReturnType)5443 TEST_F(FormatTest, TrailingReturnType) {
5444 verifyFormat("auto foo() -> int;\n");
5445 // correct trailing return type spacing
5446 verifyFormat("auto operator->() -> int;\n");
5447 verifyFormat("auto operator++(int) -> int;\n");
5448
5449 verifyFormat("struct S {\n"
5450 " auto bar() const -> int;\n"
5451 "};");
5452 verifyFormat("template <size_t Order, typename T>\n"
5453 "auto load_img(const std::string &filename)\n"
5454 " -> alias::tensor<Order, T, mem::tag::cpu> {}");
5455 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
5456 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
5457 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
5458 verifyFormat("template <typename T>\n"
5459 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
5460 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
5461
5462 // Not trailing return types.
5463 verifyFormat("void f() { auto a = b->c(); }");
5464 }
5465
TEST_F(FormatTest,DeductionGuides)5466 TEST_F(FormatTest, DeductionGuides) {
5467 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
5468 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
5469 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
5470 verifyFormat(
5471 "template <class... T>\n"
5472 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
5473 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
5474 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
5475 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
5476 verifyFormat("template <class T> A() -> A<(3 < 2)>;");
5477 verifyFormat("template <class T> A() -> A<((3) < (2))>;");
5478 verifyFormat("template <class T> x() -> x<1>;");
5479 verifyFormat("template <class T> explicit x(T &) -> x<1>;");
5480
5481 // Ensure not deduction guides.
5482 verifyFormat("c()->f<int>();");
5483 verifyFormat("x()->foo<1>;");
5484 verifyFormat("x = p->foo<3>();");
5485 verifyFormat("x()->x<1>();");
5486 verifyFormat("x()->x<1>;");
5487 }
5488
TEST_F(FormatTest,BreaksFunctionDeclarationsWithTrailingTokens)5489 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
5490 // Avoid breaking before trailing 'const' or other trailing annotations, if
5491 // they are not function-like.
5492 FormatStyle Style = getGoogleStyle();
5493 Style.ColumnLimit = 47;
5494 verifyFormat("void someLongFunction(\n"
5495 " int someLoooooooooooooongParameter) const {\n}",
5496 getLLVMStyleWithColumns(47));
5497 verifyFormat("LoooooongReturnType\n"
5498 "someLoooooooongFunction() const {}",
5499 getLLVMStyleWithColumns(47));
5500 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
5501 " const {}",
5502 Style);
5503 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5504 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
5505 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5506 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
5507 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5508 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
5509 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
5510 " aaaaaaaaaaa aaaaa) const override;");
5511 verifyGoogleFormat(
5512 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5513 " const override;");
5514
5515 // Even if the first parameter has to be wrapped.
5516 verifyFormat("void someLongFunction(\n"
5517 " int someLongParameter) const {}",
5518 getLLVMStyleWithColumns(46));
5519 verifyFormat("void someLongFunction(\n"
5520 " int someLongParameter) const {}",
5521 Style);
5522 verifyFormat("void someLongFunction(\n"
5523 " int someLongParameter) override {}",
5524 Style);
5525 verifyFormat("void someLongFunction(\n"
5526 " int someLongParameter) OVERRIDE {}",
5527 Style);
5528 verifyFormat("void someLongFunction(\n"
5529 " int someLongParameter) final {}",
5530 Style);
5531 verifyFormat("void someLongFunction(\n"
5532 " int someLongParameter) FINAL {}",
5533 Style);
5534 verifyFormat("void someLongFunction(\n"
5535 " int parameter) const override {}",
5536 Style);
5537
5538 Style.BreakBeforeBraces = FormatStyle::BS_Allman;
5539 verifyFormat("void someLongFunction(\n"
5540 " int someLongParameter) const\n"
5541 "{\n"
5542 "}",
5543 Style);
5544
5545 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
5546 verifyFormat("void someLongFunction(\n"
5547 " int someLongParameter) const\n"
5548 " {\n"
5549 " }",
5550 Style);
5551
5552 // Unless these are unknown annotations.
5553 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
5554 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5555 " LONG_AND_UGLY_ANNOTATION;");
5556
5557 // Breaking before function-like trailing annotations is fine to keep them
5558 // close to their arguments.
5559 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5560 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5561 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5562 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5563 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5564 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
5565 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
5566 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
5567 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
5568
5569 verifyFormat(
5570 "void aaaaaaaaaaaaaaaaaa()\n"
5571 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
5572 " aaaaaaaaaaaaaaaaaaaaaaaaa));");
5573 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5574 " __attribute__((unused));");
5575 verifyGoogleFormat(
5576 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5577 " GUARDED_BY(aaaaaaaaaaaa);");
5578 verifyGoogleFormat(
5579 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5580 " GUARDED_BY(aaaaaaaaaaaa);");
5581 verifyGoogleFormat(
5582 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5583 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5584 verifyGoogleFormat(
5585 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5586 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
5587 }
5588
TEST_F(FormatTest,FunctionAnnotations)5589 TEST_F(FormatTest, FunctionAnnotations) {
5590 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5591 "int OldFunction(const string ¶meter) {}");
5592 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5593 "string OldFunction(const string ¶meter) {}");
5594 verifyFormat("template <typename T>\n"
5595 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5596 "string OldFunction(const string ¶meter) {}");
5597
5598 // Not function annotations.
5599 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5600 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
5601 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
5602 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
5603 verifyFormat("MACRO(abc).function() // wrap\n"
5604 " << abc;");
5605 verifyFormat("MACRO(abc)->function() // wrap\n"
5606 " << abc;");
5607 verifyFormat("MACRO(abc)::function() // wrap\n"
5608 " << abc;");
5609 }
5610
TEST_F(FormatTest,BreaksDesireably)5611 TEST_F(FormatTest, BreaksDesireably) {
5612 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5613 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5614 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
5615 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5616 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
5617 "}");
5618
5619 verifyFormat(
5620 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5621 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5622
5623 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5624 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5625 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5626
5627 verifyFormat(
5628 "aaaaaaaa(aaaaaaaaaaaaa,\n"
5629 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5630 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5631 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5632 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
5633
5634 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5635 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5636
5637 verifyFormat(
5638 "void f() {\n"
5639 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
5640 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5641 "}");
5642 verifyFormat(
5643 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5644 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5645 verifyFormat(
5646 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5647 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5648 verifyFormat(
5649 "aaaaaa(aaa,\n"
5650 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5651 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5652 " aaaa);");
5653 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5654 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5655 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5656
5657 // Indent consistently independent of call expression and unary operator.
5658 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5659 " dddddddddddddddddddddddddddddd));");
5660 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5661 " dddddddddddddddddddddddddddddd));");
5662 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
5663 " dddddddddddddddddddddddddddddd));");
5664
5665 // This test case breaks on an incorrect memoization, i.e. an optimization not
5666 // taking into account the StopAt value.
5667 verifyFormat(
5668 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5669 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5670 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5671 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5672
5673 verifyFormat("{\n {\n {\n"
5674 " Annotation.SpaceRequiredBefore =\n"
5675 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
5676 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
5677 " }\n }\n}");
5678
5679 // Break on an outer level if there was a break on an inner level.
5680 EXPECT_EQ("f(g(h(a, // comment\n"
5681 " b, c),\n"
5682 " d, e),\n"
5683 " x, y);",
5684 format("f(g(h(a, // comment\n"
5685 " b, c), d, e), x, y);"));
5686
5687 // Prefer breaking similar line breaks.
5688 verifyFormat(
5689 "const int kTrackingOptions = NSTrackingMouseMoved |\n"
5690 " NSTrackingMouseEnteredAndExited |\n"
5691 " NSTrackingActiveAlways;");
5692 }
5693
TEST_F(FormatTest,FormatsDeclarationsOnePerLine)5694 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
5695 FormatStyle NoBinPacking = getGoogleStyle();
5696 NoBinPacking.BinPackParameters = false;
5697 NoBinPacking.BinPackArguments = true;
5698 verifyFormat("void f() {\n"
5699 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
5700 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5701 "}",
5702 NoBinPacking);
5703 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
5704 " int aaaaaaaaaaaaaaaaaaaa,\n"
5705 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5706 NoBinPacking);
5707
5708 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5709 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5710 " vector<int> bbbbbbbbbbbbbbb);",
5711 NoBinPacking);
5712 // FIXME: This behavior difference is probably not wanted. However, currently
5713 // we cannot distinguish BreakBeforeParameter being set because of the wrapped
5714 // template arguments from BreakBeforeParameter being set because of the
5715 // one-per-line formatting.
5716 verifyFormat(
5717 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5718 " aaaaaaaaaa> aaaaaaaaaa);",
5719 NoBinPacking);
5720 verifyFormat(
5721 "void fffffffffff(\n"
5722 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
5723 " aaaaaaaaaa);");
5724 }
5725
TEST_F(FormatTest,FormatsOneParameterPerLineIfNecessary)5726 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
5727 FormatStyle NoBinPacking = getGoogleStyle();
5728 NoBinPacking.BinPackParameters = false;
5729 NoBinPacking.BinPackArguments = false;
5730 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
5731 " aaaaaaaaaaaaaaaaaaaa,\n"
5732 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
5733 NoBinPacking);
5734 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
5735 " aaaaaaaaaaaaa,\n"
5736 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
5737 NoBinPacking);
5738 verifyFormat(
5739 "aaaaaaaa(aaaaaaaaaaaaa,\n"
5740 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5741 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5742 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5743 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
5744 NoBinPacking);
5745 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5746 " .aaaaaaaaaaaaaaaaaa();",
5747 NoBinPacking);
5748 verifyFormat("void f() {\n"
5749 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5750 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
5751 "}",
5752 NoBinPacking);
5753
5754 verifyFormat(
5755 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5756 " aaaaaaaaaaaa,\n"
5757 " aaaaaaaaaaaa);",
5758 NoBinPacking);
5759 verifyFormat(
5760 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
5761 " ddddddddddddddddddddddddddddd),\n"
5762 " test);",
5763 NoBinPacking);
5764
5765 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5766 " aaaaaaaaaaaaaaaaaaaaaaa,\n"
5767 " aaaaaaaaaaaaaaaaaaaaaaa>\n"
5768 " aaaaaaaaaaaaaaaaaa;",
5769 NoBinPacking);
5770 verifyFormat("a(\"a\"\n"
5771 " \"a\",\n"
5772 " a);");
5773
5774 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5775 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
5776 " aaaaaaaaa,\n"
5777 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5778 NoBinPacking);
5779 verifyFormat(
5780 "void f() {\n"
5781 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5782 " .aaaaaaa();\n"
5783 "}",
5784 NoBinPacking);
5785 verifyFormat(
5786 "template <class SomeType, class SomeOtherType>\n"
5787 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
5788 NoBinPacking);
5789 }
5790
TEST_F(FormatTest,AdaptiveOnePerLineFormatting)5791 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
5792 FormatStyle Style = getLLVMStyleWithColumns(15);
5793 Style.ExperimentalAutoDetectBinPacking = true;
5794 EXPECT_EQ("aaa(aaaa,\n"
5795 " aaaa,\n"
5796 " aaaa);\n"
5797 "aaa(aaaa,\n"
5798 " aaaa,\n"
5799 " aaaa);",
5800 format("aaa(aaaa,\n" // one-per-line
5801 " aaaa,\n"
5802 " aaaa );\n"
5803 "aaa(aaaa, aaaa, aaaa);", // inconclusive
5804 Style));
5805 EXPECT_EQ("aaa(aaaa, aaaa,\n"
5806 " aaaa);\n"
5807 "aaa(aaaa, aaaa,\n"
5808 " aaaa);",
5809 format("aaa(aaaa, aaaa,\n" // bin-packed
5810 " aaaa );\n"
5811 "aaa(aaaa, aaaa, aaaa);", // inconclusive
5812 Style));
5813 }
5814
TEST_F(FormatTest,FormatsBuilderPattern)5815 TEST_F(FormatTest, FormatsBuilderPattern) {
5816 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
5817 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
5818 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
5819 " .StartsWith(\".init\", ORDER_INIT)\n"
5820 " .StartsWith(\".fini\", ORDER_FINI)\n"
5821 " .StartsWith(\".hash\", ORDER_HASH)\n"
5822 " .Default(ORDER_TEXT);\n");
5823
5824 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
5825 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
5826 verifyFormat("aaaaaaa->aaaaaaa\n"
5827 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5828 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5829 " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5830 verifyFormat(
5831 "aaaaaaa->aaaaaaa\n"
5832 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5833 " ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5834 verifyFormat(
5835 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
5836 " aaaaaaaaaaaaaa);");
5837 verifyFormat(
5838 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
5839 " aaaaaa->aaaaaaaaaaaa()\n"
5840 " ->aaaaaaaaaaaaaaaa(\n"
5841 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5842 " ->aaaaaaaaaaaaaaaaa();");
5843 verifyGoogleFormat(
5844 "void f() {\n"
5845 " someo->Add((new util::filetools::Handler(dir))\n"
5846 " ->OnEvent1(NewPermanentCallback(\n"
5847 " this, &HandlerHolderClass::EventHandlerCBA))\n"
5848 " ->OnEvent2(NewPermanentCallback(\n"
5849 " this, &HandlerHolderClass::EventHandlerCBB))\n"
5850 " ->OnEvent3(NewPermanentCallback(\n"
5851 " this, &HandlerHolderClass::EventHandlerCBC))\n"
5852 " ->OnEvent5(NewPermanentCallback(\n"
5853 " this, &HandlerHolderClass::EventHandlerCBD))\n"
5854 " ->OnEvent6(NewPermanentCallback(\n"
5855 " this, &HandlerHolderClass::EventHandlerCBE)));\n"
5856 "}");
5857
5858 verifyFormat(
5859 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
5860 verifyFormat("aaaaaaaaaaaaaaa()\n"
5861 " .aaaaaaaaaaaaaaa()\n"
5862 " .aaaaaaaaaaaaaaa()\n"
5863 " .aaaaaaaaaaaaaaa()\n"
5864 " .aaaaaaaaaaaaaaa();");
5865 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5866 " .aaaaaaaaaaaaaaa()\n"
5867 " .aaaaaaaaaaaaaaa()\n"
5868 " .aaaaaaaaaaaaaaa();");
5869 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5870 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5871 " .aaaaaaaaaaaaaaa();");
5872 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
5873 " ->aaaaaaaaaaaaaae(0)\n"
5874 " ->aaaaaaaaaaaaaaa();");
5875
5876 // Don't linewrap after very short segments.
5877 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5878 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5879 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5880 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5881 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5882 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5883 verifyFormat("aaa()\n"
5884 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5885 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5886 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5887
5888 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5889 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5890 " .has<bbbbbbbbbbbbbbbbbbbbb>();");
5891 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5892 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5893 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
5894
5895 // Prefer not to break after empty parentheses.
5896 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
5897 " First->LastNewlineOffset);");
5898
5899 // Prefer not to create "hanging" indents.
5900 verifyFormat(
5901 "return !soooooooooooooome_map\n"
5902 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5903 " .second;");
5904 verifyFormat(
5905 "return aaaaaaaaaaaaaaaa\n"
5906 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
5907 " .aaaa(aaaaaaaaaaaaaa);");
5908 // No hanging indent here.
5909 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
5910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5911 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
5912 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5913 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5914 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5915 getLLVMStyleWithColumns(60));
5916 verifyFormat("aaaaaaaaaaaaaaaaaa\n"
5917 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5918 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5919 getLLVMStyleWithColumns(59));
5920 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5921 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5922 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5923
5924 // Dont break if only closing statements before member call
5925 verifyFormat("test() {\n"
5926 " ([]() -> {\n"
5927 " int b = 32;\n"
5928 " return 3;\n"
5929 " }).foo();\n"
5930 "}");
5931 verifyFormat("test() {\n"
5932 " (\n"
5933 " []() -> {\n"
5934 " int b = 32;\n"
5935 " return 3;\n"
5936 " },\n"
5937 " foo, bar)\n"
5938 " .foo();\n"
5939 "}");
5940 verifyFormat("test() {\n"
5941 " ([]() -> {\n"
5942 " int b = 32;\n"
5943 " return 3;\n"
5944 " })\n"
5945 " .foo()\n"
5946 " .bar();\n"
5947 "}");
5948 verifyFormat("test() {\n"
5949 " ([]() -> {\n"
5950 " int b = 32;\n"
5951 " return 3;\n"
5952 " })\n"
5953 " .foo(\"aaaaaaaaaaaaaaaaa\"\n"
5954 " \"bbbb\");\n"
5955 "}",
5956 getLLVMStyleWithColumns(30));
5957 }
5958
TEST_F(FormatTest,BreaksAccordingToOperatorPrecedence)5959 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
5960 verifyFormat(
5961 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5962 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
5963 verifyFormat(
5964 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
5965 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
5966
5967 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5968 " ccccccccccccccccccccccccc) {\n}");
5969 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
5970 " ccccccccccccccccccccccccc) {\n}");
5971
5972 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5973 " ccccccccccccccccccccccccc) {\n}");
5974 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
5975 " ccccccccccccccccccccccccc) {\n}");
5976
5977 verifyFormat(
5978 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
5979 " ccccccccccccccccccccccccc) {\n}");
5980 verifyFormat(
5981 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
5982 " ccccccccccccccccccccccccc) {\n}");
5983
5984 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
5985 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
5986 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
5987 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
5988 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
5989 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
5990 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
5991 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
5992
5993 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
5994 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
5995 " aaaaaaaaaaaaaaa != aa) {\n}");
5996 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
5997 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
5998 " aaaaaaaaaaaaaaa != aa) {\n}");
5999 }
6000
TEST_F(FormatTest,BreaksAfterAssignments)6001 TEST_F(FormatTest, BreaksAfterAssignments) {
6002 verifyFormat(
6003 "unsigned Cost =\n"
6004 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
6005 " SI->getPointerAddressSpaceee());\n");
6006 verifyFormat(
6007 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
6008 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
6009
6010 verifyFormat(
6011 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
6012 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
6013 verifyFormat("unsigned OriginalStartColumn =\n"
6014 " SourceMgr.getSpellingColumnNumber(\n"
6015 " Current.FormatTok.getStartOfNonWhitespace()) -\n"
6016 " 1;");
6017 }
6018
TEST_F(FormatTest,ConfigurableBreakAssignmentPenalty)6019 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
6020 FormatStyle Style = getLLVMStyle();
6021 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6022 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
6023 Style);
6024
6025 Style.PenaltyBreakAssignment = 20;
6026 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6027 " cccccccccccccccccccccccccc;",
6028 Style);
6029 }
6030
TEST_F(FormatTest,AlignsAfterAssignments)6031 TEST_F(FormatTest, AlignsAfterAssignments) {
6032 verifyFormat(
6033 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6034 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
6035 verifyFormat(
6036 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6037 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
6038 verifyFormat(
6039 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6040 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
6041 verifyFormat(
6042 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6043 " aaaaaaaaaaaaaaaaaaaaaaaaa);");
6044 verifyFormat(
6045 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6046 " aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6047 " aaaaaaaaaaaaaaaaaaaaaaaa;");
6048 }
6049
TEST_F(FormatTest,AlignsAfterReturn)6050 TEST_F(FormatTest, AlignsAfterReturn) {
6051 verifyFormat(
6052 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6053 " aaaaaaaaaaaaaaaaaaaaaaaaa;");
6054 verifyFormat(
6055 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6056 " aaaaaaaaaaaaaaaaaaaaaaaaa);");
6057 verifyFormat(
6058 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6059 " aaaaaaaaaaaaaaaaaaaaaa();");
6060 verifyFormat(
6061 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6062 " aaaaaaaaaaaaaaaaaaaaaa());");
6063 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6064 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6065 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6066 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
6067 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6068 verifyFormat("return\n"
6069 " // true if code is one of a or b.\n"
6070 " code == a || code == b;");
6071 }
6072
TEST_F(FormatTest,AlignsAfterOpenBracket)6073 TEST_F(FormatTest, AlignsAfterOpenBracket) {
6074 verifyFormat(
6075 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6076 " aaaaaaaaa aaaaaaa) {}");
6077 verifyFormat(
6078 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6079 " aaaaaaaaaaa aaaaaaaaa);");
6080 verifyFormat(
6081 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6082 " aaaaaaaaaaaaaaaaaaaaa));");
6083 FormatStyle Style = getLLVMStyle();
6084 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6085 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6086 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
6087 Style);
6088 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6089 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
6090 Style);
6091 verifyFormat("SomeLongVariableName->someFunction(\n"
6092 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
6093 Style);
6094 verifyFormat(
6095 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6096 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6097 Style);
6098 verifyFormat(
6099 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6100 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6101 Style);
6102 verifyFormat(
6103 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6104 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6105 Style);
6106
6107 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
6108 " ccccccc(aaaaaaaaaaaaaaaaa, //\n"
6109 " b));",
6110 Style);
6111
6112 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6113 Style.BinPackArguments = false;
6114 Style.BinPackParameters = false;
6115 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6116 " aaaaaaaaaaa aaaaaaaa,\n"
6117 " aaaaaaaaa aaaaaaa,\n"
6118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6119 Style);
6120 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6121 " aaaaaaaaaaa aaaaaaaaa,\n"
6122 " aaaaaaaaaaa aaaaaaaaa,\n"
6123 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6124 Style);
6125 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
6126 " aaaaaaaaaaaaaaa,\n"
6127 " aaaaaaaaaaaaaaaaaaaaa,\n"
6128 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6129 Style);
6130 verifyFormat(
6131 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
6132 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6133 Style);
6134 verifyFormat(
6135 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
6136 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6137 Style);
6138 verifyFormat(
6139 "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6140 " aaaaaaaaaaaaaaaaaaaaa(\n"
6141 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
6142 " aaaaaaaaaaaaaaaa);",
6143 Style);
6144 verifyFormat(
6145 "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6146 " aaaaaaaaaaaaaaaaaaaaa(\n"
6147 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
6148 " aaaaaaaaaaaaaaaa);",
6149 Style);
6150 }
6151
TEST_F(FormatTest,ParenthesesAndOperandAlignment)6152 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
6153 FormatStyle Style = getLLVMStyleWithColumns(40);
6154 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6155 " bbbbbbbbbbbbbbbbbbbbbb);",
6156 Style);
6157 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6158 Style.AlignOperands = FormatStyle::OAS_DontAlign;
6159 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6160 " bbbbbbbbbbbbbbbbbbbbbb);",
6161 Style);
6162 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6163 Style.AlignOperands = FormatStyle::OAS_Align;
6164 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6165 " bbbbbbbbbbbbbbbbbbbbbb);",
6166 Style);
6167 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6168 Style.AlignOperands = FormatStyle::OAS_DontAlign;
6169 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6170 " bbbbbbbbbbbbbbbbbbbbbb);",
6171 Style);
6172 }
6173
TEST_F(FormatTest,BreaksConditionalExpressions)6174 TEST_F(FormatTest, BreaksConditionalExpressions) {
6175 verifyFormat(
6176 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6177 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6178 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6179 verifyFormat(
6180 "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6181 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6182 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6183 verifyFormat(
6184 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6185 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6186 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
6187 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6188 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6189 verifyFormat(
6190 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
6191 " : aaaaaaaaaaaaa);");
6192 verifyFormat(
6193 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6194 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6195 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6196 " aaaaaaaaaaaaa);");
6197 verifyFormat(
6198 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6199 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6200 " aaaaaaaaaaaaa);");
6201 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6202 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6203 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6204 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6205 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6206 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6207 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6208 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6209 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6210 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6211 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6212 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6213 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6214 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6215 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6216 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6217 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6218 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6219 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6220 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6221 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6222 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6223 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6224 " : aaaaaaaaaaaaaaaa;");
6225 verifyFormat(
6226 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6227 " ? aaaaaaaaaaaaaaa\n"
6228 " : aaaaaaaaaaaaaaa;");
6229 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6230 " aaaaaaaaa\n"
6231 " ? b\n"
6232 " : c);");
6233 verifyFormat("return aaaa == bbbb\n"
6234 " // comment\n"
6235 " ? aaaa\n"
6236 " : bbbb;");
6237 verifyFormat("unsigned Indent =\n"
6238 " format(TheLine.First,\n"
6239 " IndentForLevel[TheLine.Level] >= 0\n"
6240 " ? IndentForLevel[TheLine.Level]\n"
6241 " : TheLine * 2,\n"
6242 " TheLine.InPPDirective, PreviousEndOfLineColumn);",
6243 getLLVMStyleWithColumns(60));
6244 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6245 " ? aaaaaaaaaaaaaaa\n"
6246 " : bbbbbbbbbbbbbbb //\n"
6247 " ? ccccccccccccccc\n"
6248 " : ddddddddddddddd;");
6249 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6250 " ? aaaaaaaaaaaaaaa\n"
6251 " : (bbbbbbbbbbbbbbb //\n"
6252 " ? ccccccccccccccc\n"
6253 " : ddddddddddddddd);");
6254 verifyFormat(
6255 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6256 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6257 " aaaaaaaaaaaaaaaaaaaaa +\n"
6258 " aaaaaaaaaaaaaaaaaaaaa\n"
6259 " : aaaaaaaaaa;");
6260 verifyFormat(
6261 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6262 " : aaaaaaaaaaaaaaaaaaaaaa\n"
6263 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6264
6265 FormatStyle NoBinPacking = getLLVMStyle();
6266 NoBinPacking.BinPackArguments = false;
6267 verifyFormat(
6268 "void f() {\n"
6269 " g(aaa,\n"
6270 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6271 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6272 " ? aaaaaaaaaaaaaaa\n"
6273 " : aaaaaaaaaaaaaaa);\n"
6274 "}",
6275 NoBinPacking);
6276 verifyFormat(
6277 "void f() {\n"
6278 " g(aaa,\n"
6279 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6280 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6281 " ?: aaaaaaaaaaaaaaa);\n"
6282 "}",
6283 NoBinPacking);
6284
6285 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
6286 " // comment.\n"
6287 " ccccccccccccccccccccccccccccccccccccccc\n"
6288 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6289 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
6290
6291 // Assignments in conditional expressions. Apparently not uncommon :-(.
6292 verifyFormat("return a != b\n"
6293 " // comment\n"
6294 " ? a = b\n"
6295 " : a = b;");
6296 verifyFormat("return a != b\n"
6297 " // comment\n"
6298 " ? a = a != b\n"
6299 " // comment\n"
6300 " ? a = b\n"
6301 " : a\n"
6302 " : a;\n");
6303 verifyFormat("return a != b\n"
6304 " // comment\n"
6305 " ? a\n"
6306 " : a = a != b\n"
6307 " // comment\n"
6308 " ? a = b\n"
6309 " : a;");
6310
6311 // Chained conditionals
6312 FormatStyle Style = getLLVMStyle();
6313 Style.ColumnLimit = 70;
6314 Style.AlignOperands = FormatStyle::OAS_Align;
6315 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6316 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6317 " : 3333333333333333;",
6318 Style);
6319 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6320 " : bbbbbbbbbb ? 2222222222222222\n"
6321 " : 3333333333333333;",
6322 Style);
6323 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n"
6324 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6325 " : 3333333333333333;",
6326 Style);
6327 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6328 " : bbbbbbbbbbbbbb ? 222222\n"
6329 " : 333333;",
6330 Style);
6331 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6332 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6333 " : cccccccccccccc ? 3333333333333333\n"
6334 " : 4444444444444444;",
6335 Style);
6336 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
6337 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6338 " : 3333333333333333;",
6339 Style);
6340 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6341 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6342 " : (aaa ? bbb : ccc);",
6343 Style);
6344 verifyFormat(
6345 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6346 " : cccccccccccccccccc)\n"
6347 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6348 " : 3333333333333333;",
6349 Style);
6350 verifyFormat(
6351 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6352 " : cccccccccccccccccc)\n"
6353 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6354 " : 3333333333333333;",
6355 Style);
6356 verifyFormat(
6357 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6358 " : dddddddddddddddddd)\n"
6359 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6360 " : 3333333333333333;",
6361 Style);
6362 verifyFormat(
6363 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6364 " : dddddddddddddddddd)\n"
6365 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6366 " : 3333333333333333;",
6367 Style);
6368 verifyFormat(
6369 "return aaaaaaaaa ? 1111111111111111\n"
6370 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6371 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6372 " : dddddddddddddddddd)\n",
6373 Style);
6374 verifyFormat(
6375 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6376 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6377 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6378 " : cccccccccccccccccc);",
6379 Style);
6380 verifyFormat(
6381 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6382 " : ccccccccccccccc ? dddddddddddddddddd\n"
6383 " : eeeeeeeeeeeeeeeeee)\n"
6384 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6385 " : 3333333333333333;",
6386 Style);
6387 verifyFormat(
6388 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6389 " : ccccccccccccccc ? dddddddddddddddddd\n"
6390 " : eeeeeeeeeeeeeeeeee)\n"
6391 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6392 " : 3333333333333333;",
6393 Style);
6394 verifyFormat(
6395 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6396 " : cccccccccccc ? dddddddddddddddddd\n"
6397 " : eeeeeeeeeeeeeeeeee)\n"
6398 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6399 " : 3333333333333333;",
6400 Style);
6401 verifyFormat(
6402 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6403 " : cccccccccccccccccc\n"
6404 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6405 " : 3333333333333333;",
6406 Style);
6407 verifyFormat(
6408 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6409 " : cccccccccccccccc ? dddddddddddddddddd\n"
6410 " : eeeeeeeeeeeeeeeeee\n"
6411 " : bbbbbbbbbbbbbb ? 2222222222222222\n"
6412 " : 3333333333333333;",
6413 Style);
6414 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
6415 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6416 " : cccccccccccccccccc ? dddddddddddddddddd\n"
6417 " : eeeeeeeeeeeeeeeeee)\n"
6418 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6419 " : 3333333333333333;",
6420 Style);
6421 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
6422 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6423 " : cccccccccccccccc ? dddddddddddddddddd\n"
6424 " : eeeeeeeeeeeeeeeeee\n"
6425 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6426 " : 3333333333333333;",
6427 Style);
6428
6429 Style.AlignOperands = FormatStyle::OAS_DontAlign;
6430 Style.BreakBeforeTernaryOperators = false;
6431 // FIXME: Aligning the question marks is weird given DontAlign.
6432 // Consider disabling this alignment in this case. Also check whether this
6433 // will render the adjustment from https://reviews.llvm.org/D82199
6434 // unnecessary.
6435 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
6436 " bbbb ? cccccccccccccccccc :\n"
6437 " ddddd;\n",
6438 Style);
6439 }
6440
TEST_F(FormatTest,BreaksConditionalExpressionsAfterOperator)6441 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
6442 FormatStyle Style = getLLVMStyle();
6443 Style.BreakBeforeTernaryOperators = false;
6444 Style.ColumnLimit = 70;
6445 verifyFormat(
6446 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6447 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6448 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6449 Style);
6450 verifyFormat(
6451 "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6452 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6453 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6454 Style);
6455 verifyFormat(
6456 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6457 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6458 Style);
6459 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
6460 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6461 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6462 Style);
6463 verifyFormat(
6464 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
6465 " aaaaaaaaaaaaa);",
6466 Style);
6467 verifyFormat(
6468 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6469 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6470 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6471 " aaaaaaaaaaaaa);",
6472 Style);
6473 verifyFormat(
6474 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6475 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6476 " aaaaaaaaaaaaa);",
6477 Style);
6478 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6481 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6482 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6483 Style);
6484 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6485 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6486 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6487 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6488 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6489 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6490 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6491 Style);
6492 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
6494 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6495 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6496 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6497 Style);
6498 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6499 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6500 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6501 Style);
6502 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6503 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6504 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6505 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6506 Style);
6507 verifyFormat(
6508 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6509 " aaaaaaaaaaaaaaa :\n"
6510 " aaaaaaaaaaaaaaa;",
6511 Style);
6512 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6513 " aaaaaaaaa ?\n"
6514 " b :\n"
6515 " c);",
6516 Style);
6517 verifyFormat("unsigned Indent =\n"
6518 " format(TheLine.First,\n"
6519 " IndentForLevel[TheLine.Level] >= 0 ?\n"
6520 " IndentForLevel[TheLine.Level] :\n"
6521 " TheLine * 2,\n"
6522 " TheLine.InPPDirective, PreviousEndOfLineColumn);",
6523 Style);
6524 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6525 " aaaaaaaaaaaaaaa :\n"
6526 " bbbbbbbbbbbbbbb ? //\n"
6527 " ccccccccccccccc :\n"
6528 " ddddddddddddddd;",
6529 Style);
6530 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6531 " aaaaaaaaaaaaaaa :\n"
6532 " (bbbbbbbbbbbbbbb ? //\n"
6533 " ccccccccccccccc :\n"
6534 " ddddddddddddddd);",
6535 Style);
6536 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6537 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
6538 " ccccccccccccccccccccccccccc;",
6539 Style);
6540 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6541 " aaaaa :\n"
6542 " bbbbbbbbbbbbbbb + cccccccccccccccc;",
6543 Style);
6544
6545 // Chained conditionals
6546 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6547 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6548 " 3333333333333333;",
6549 Style);
6550 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6551 " bbbbbbbbbb ? 2222222222222222 :\n"
6552 " 3333333333333333;",
6553 Style);
6554 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n"
6555 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6556 " 3333333333333333;",
6557 Style);
6558 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6559 " bbbbbbbbbbbbbbbb ? 222222 :\n"
6560 " 333333;",
6561 Style);
6562 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6563 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6564 " cccccccccccccccc ? 3333333333333333 :\n"
6565 " 4444444444444444;",
6566 Style);
6567 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
6568 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6569 " 3333333333333333;",
6570 Style);
6571 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6572 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6573 " (aaa ? bbb : ccc);",
6574 Style);
6575 verifyFormat(
6576 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6577 " cccccccccccccccccc) :\n"
6578 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6579 " 3333333333333333;",
6580 Style);
6581 verifyFormat(
6582 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6583 " cccccccccccccccccc) :\n"
6584 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6585 " 3333333333333333;",
6586 Style);
6587 verifyFormat(
6588 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6589 " dddddddddddddddddd) :\n"
6590 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6591 " 3333333333333333;",
6592 Style);
6593 verifyFormat(
6594 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6595 " dddddddddddddddddd) :\n"
6596 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6597 " 3333333333333333;",
6598 Style);
6599 verifyFormat(
6600 "return aaaaaaaaa ? 1111111111111111 :\n"
6601 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6602 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6603 " dddddddddddddddddd)\n",
6604 Style);
6605 verifyFormat(
6606 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6607 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6608 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6609 " cccccccccccccccccc);",
6610 Style);
6611 verifyFormat(
6612 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6613 " ccccccccccccccccc ? dddddddddddddddddd :\n"
6614 " eeeeeeeeeeeeeeeeee) :\n"
6615 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6616 " 3333333333333333;",
6617 Style);
6618 verifyFormat(
6619 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6620 " ccccccccccccc ? dddddddddddddddddd :\n"
6621 " eeeeeeeeeeeeeeeeee) :\n"
6622 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6623 " 3333333333333333;",
6624 Style);
6625 verifyFormat(
6626 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6627 " ccccccccccccccccc ? dddddddddddddddddd :\n"
6628 " eeeeeeeeeeeeeeeeee) :\n"
6629 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6630 " 3333333333333333;",
6631 Style);
6632 verifyFormat(
6633 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6634 " cccccccccccccccccc :\n"
6635 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6636 " 3333333333333333;",
6637 Style);
6638 verifyFormat(
6639 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6640 " cccccccccccccccccc ? dddddddddddddddddd :\n"
6641 " eeeeeeeeeeeeeeeeee :\n"
6642 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6643 " 3333333333333333;",
6644 Style);
6645 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6646 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6647 " cccccccccccccccccc ? dddddddddddddddddd :\n"
6648 " eeeeeeeeeeeeeeeeee) :\n"
6649 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6650 " 3333333333333333;",
6651 Style);
6652 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6653 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6654 " cccccccccccccccccccc ? dddddddddddddddddd :\n"
6655 " eeeeeeeeeeeeeeeeee :\n"
6656 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6657 " 3333333333333333;",
6658 Style);
6659 }
6660
TEST_F(FormatTest,DeclarationsOfMultipleVariables)6661 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
6662 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
6663 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
6664 verifyFormat("bool a = true, b = false;");
6665
6666 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6667 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
6668 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
6669 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
6670 verifyFormat(
6671 "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6672 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
6673 " d = e && f;");
6674 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
6675 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
6676 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6677 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
6678 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
6679 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
6680
6681 FormatStyle Style = getGoogleStyle();
6682 Style.PointerAlignment = FormatStyle::PAS_Left;
6683 Style.DerivePointerAlignment = false;
6684 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6685 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
6686 " *b = bbbbbbbbbbbbbbbbbbb;",
6687 Style);
6688 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6689 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
6690 Style);
6691 verifyFormat("vector<int*> a, b;", Style);
6692 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
6693 }
6694
TEST_F(FormatTest,ConditionalExpressionsInBrackets)6695 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
6696 verifyFormat("arr[foo ? bar : baz];");
6697 verifyFormat("f()[foo ? bar : baz];");
6698 verifyFormat("(a + b)[foo ? bar : baz];");
6699 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
6700 }
6701
TEST_F(FormatTest,AlignsStringLiterals)6702 TEST_F(FormatTest, AlignsStringLiterals) {
6703 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
6704 " \"short literal\");");
6705 verifyFormat(
6706 "looooooooooooooooooooooooongFunction(\n"
6707 " \"short literal\"\n"
6708 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
6709 verifyFormat("someFunction(\"Always break between multi-line\"\n"
6710 " \" string literals\",\n"
6711 " and, other, parameters);");
6712 EXPECT_EQ("fun + \"1243\" /* comment */\n"
6713 " \"5678\";",
6714 format("fun + \"1243\" /* comment */\n"
6715 " \"5678\";",
6716 getLLVMStyleWithColumns(28)));
6717 EXPECT_EQ(
6718 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
6719 " \"aaaaaaaaaaaaaaaaaaaaa\"\n"
6720 " \"aaaaaaaaaaaaaaaa\";",
6721 format("aaaaaa ="
6722 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
6723 "aaaaaaaaaaaaaaaaaaaaa\" "
6724 "\"aaaaaaaaaaaaaaaa\";"));
6725 verifyFormat("a = a + \"a\"\n"
6726 " \"a\"\n"
6727 " \"a\";");
6728 verifyFormat("f(\"a\", \"b\"\n"
6729 " \"c\");");
6730
6731 verifyFormat(
6732 "#define LL_FORMAT \"ll\"\n"
6733 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
6734 " \"d, ddddddddd: %\" LL_FORMAT \"d\");");
6735
6736 verifyFormat("#define A(X) \\\n"
6737 " \"aaaaa\" #X \"bbbbbb\" \\\n"
6738 " \"ccccc\"",
6739 getLLVMStyleWithColumns(23));
6740 verifyFormat("#define A \"def\"\n"
6741 "f(\"abc\" A \"ghi\"\n"
6742 " \"jkl\");");
6743
6744 verifyFormat("f(L\"a\"\n"
6745 " L\"b\");");
6746 verifyFormat("#define A(X) \\\n"
6747 " L\"aaaaa\" #X L\"bbbbbb\" \\\n"
6748 " L\"ccccc\"",
6749 getLLVMStyleWithColumns(25));
6750
6751 verifyFormat("f(@\"a\"\n"
6752 " @\"b\");");
6753 verifyFormat("NSString s = @\"a\"\n"
6754 " @\"b\"\n"
6755 " @\"c\";");
6756 verifyFormat("NSString s = @\"a\"\n"
6757 " \"b\"\n"
6758 " \"c\";");
6759 }
6760
TEST_F(FormatTest,ReturnTypeBreakingStyle)6761 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
6762 FormatStyle Style = getLLVMStyle();
6763 // No declarations or definitions should be moved to own line.
6764 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6765 verifyFormat("class A {\n"
6766 " int f() { return 1; }\n"
6767 " int g();\n"
6768 "};\n"
6769 "int f() { return 1; }\n"
6770 "int g();\n",
6771 Style);
6772
6773 // All declarations and definitions should have the return type moved to its
6774 // own line.
6775 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
6776 Style.TypenameMacros = {"LIST"};
6777 verifyFormat("SomeType\n"
6778 "funcdecl(LIST(uint64_t));",
6779 Style);
6780 verifyFormat("class E {\n"
6781 " int\n"
6782 " f() {\n"
6783 " return 1;\n"
6784 " }\n"
6785 " int\n"
6786 " g();\n"
6787 "};\n"
6788 "int\n"
6789 "f() {\n"
6790 " return 1;\n"
6791 "}\n"
6792 "int\n"
6793 "g();\n",
6794 Style);
6795
6796 // Top-level definitions, and no kinds of declarations should have the
6797 // return type moved to its own line.
6798 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
6799 verifyFormat("class B {\n"
6800 " int f() { return 1; }\n"
6801 " int g();\n"
6802 "};\n"
6803 "int\n"
6804 "f() {\n"
6805 " return 1;\n"
6806 "}\n"
6807 "int g();\n",
6808 Style);
6809
6810 // Top-level definitions and declarations should have the return type moved
6811 // to its own line.
6812 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
6813 verifyFormat("class C {\n"
6814 " int f() { return 1; }\n"
6815 " int g();\n"
6816 "};\n"
6817 "int\n"
6818 "f() {\n"
6819 " return 1;\n"
6820 "}\n"
6821 "int\n"
6822 "g();\n",
6823 Style);
6824
6825 // All definitions should have the return type moved to its own line, but no
6826 // kinds of declarations.
6827 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
6828 verifyFormat("class D {\n"
6829 " int\n"
6830 " f() {\n"
6831 " return 1;\n"
6832 " }\n"
6833 " int g();\n"
6834 "};\n"
6835 "int\n"
6836 "f() {\n"
6837 " return 1;\n"
6838 "}\n"
6839 "int g();\n",
6840 Style);
6841 verifyFormat("const char *\n"
6842 "f(void) {\n" // Break here.
6843 " return \"\";\n"
6844 "}\n"
6845 "const char *bar(void);\n", // No break here.
6846 Style);
6847 verifyFormat("template <class T>\n"
6848 "T *\n"
6849 "f(T &c) {\n" // Break here.
6850 " return NULL;\n"
6851 "}\n"
6852 "template <class T> T *f(T &c);\n", // No break here.
6853 Style);
6854 verifyFormat("class C {\n"
6855 " int\n"
6856 " operator+() {\n"
6857 " return 1;\n"
6858 " }\n"
6859 " int\n"
6860 " operator()() {\n"
6861 " return 1;\n"
6862 " }\n"
6863 "};\n",
6864 Style);
6865 verifyFormat("void\n"
6866 "A::operator()() {}\n"
6867 "void\n"
6868 "A::operator>>() {}\n"
6869 "void\n"
6870 "A::operator+() {}\n"
6871 "void\n"
6872 "A::operator*() {}\n"
6873 "void\n"
6874 "A::operator->() {}\n"
6875 "void\n"
6876 "A::operator void *() {}\n"
6877 "void\n"
6878 "A::operator void &() {}\n"
6879 "void\n"
6880 "A::operator void &&() {}\n"
6881 "void\n"
6882 "A::operator char *() {}\n"
6883 "void\n"
6884 "A::operator[]() {}\n"
6885 "void\n"
6886 "A::operator!() {}\n"
6887 "void\n"
6888 "A::operator**() {}\n"
6889 "void\n"
6890 "A::operator<Foo> *() {}\n"
6891 "void\n"
6892 "A::operator<Foo> **() {}\n"
6893 "void\n"
6894 "A::operator<Foo> &() {}\n"
6895 "void\n"
6896 "A::operator void **() {}\n",
6897 Style);
6898 verifyFormat("constexpr auto\n"
6899 "operator()() const -> reference {}\n"
6900 "constexpr auto\n"
6901 "operator>>() const -> reference {}\n"
6902 "constexpr auto\n"
6903 "operator+() const -> reference {}\n"
6904 "constexpr auto\n"
6905 "operator*() const -> reference {}\n"
6906 "constexpr auto\n"
6907 "operator->() const -> reference {}\n"
6908 "constexpr auto\n"
6909 "operator++() const -> reference {}\n"
6910 "constexpr auto\n"
6911 "operator void *() const -> reference {}\n"
6912 "constexpr auto\n"
6913 "operator void **() const -> reference {}\n"
6914 "constexpr auto\n"
6915 "operator void *() const -> reference {}\n"
6916 "constexpr auto\n"
6917 "operator void &() const -> reference {}\n"
6918 "constexpr auto\n"
6919 "operator void &&() const -> reference {}\n"
6920 "constexpr auto\n"
6921 "operator char *() const -> reference {}\n"
6922 "constexpr auto\n"
6923 "operator!() const -> reference {}\n"
6924 "constexpr auto\n"
6925 "operator[]() const -> reference {}\n",
6926 Style);
6927 verifyFormat("void *operator new(std::size_t s);", // No break here.
6928 Style);
6929 verifyFormat("void *\n"
6930 "operator new(std::size_t s) {}",
6931 Style);
6932 verifyFormat("void *\n"
6933 "operator delete[](void *ptr) {}",
6934 Style);
6935 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
6936 verifyFormat("const char *\n"
6937 "f(void)\n" // Break here.
6938 "{\n"
6939 " return \"\";\n"
6940 "}\n"
6941 "const char *bar(void);\n", // No break here.
6942 Style);
6943 verifyFormat("template <class T>\n"
6944 "T *\n" // Problem here: no line break
6945 "f(T &c)\n" // Break here.
6946 "{\n"
6947 " return NULL;\n"
6948 "}\n"
6949 "template <class T> T *f(T &c);\n", // No break here.
6950 Style);
6951 verifyFormat("int\n"
6952 "foo(A<bool> a)\n"
6953 "{\n"
6954 " return a;\n"
6955 "}\n",
6956 Style);
6957 verifyFormat("int\n"
6958 "foo(A<8> a)\n"
6959 "{\n"
6960 " return a;\n"
6961 "}\n",
6962 Style);
6963 verifyFormat("int\n"
6964 "foo(A<B<bool>, 8> a)\n"
6965 "{\n"
6966 " return a;\n"
6967 "}\n",
6968 Style);
6969 verifyFormat("int\n"
6970 "foo(A<B<8>, bool> a)\n"
6971 "{\n"
6972 " return a;\n"
6973 "}\n",
6974 Style);
6975 verifyFormat("int\n"
6976 "foo(A<B<bool>, bool> a)\n"
6977 "{\n"
6978 " return a;\n"
6979 "}\n",
6980 Style);
6981 verifyFormat("int\n"
6982 "foo(A<B<8>, 8> a)\n"
6983 "{\n"
6984 " return a;\n"
6985 "}\n",
6986 Style);
6987
6988 Style = getGNUStyle();
6989
6990 // Test for comments at the end of function declarations.
6991 verifyFormat("void\n"
6992 "foo (int a, /*abc*/ int b) // def\n"
6993 "{\n"
6994 "}\n",
6995 Style);
6996
6997 verifyFormat("void\n"
6998 "foo (int a, /* abc */ int b) /* def */\n"
6999 "{\n"
7000 "}\n",
7001 Style);
7002
7003 // Definitions that should not break after return type
7004 verifyFormat("void foo (int a, int b); // def\n", Style);
7005 verifyFormat("void foo (int a, int b); /* def */\n", Style);
7006 verifyFormat("void foo (int a, int b);\n", Style);
7007 }
7008
TEST_F(FormatTest,AlwaysBreakBeforeMultilineStrings)7009 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
7010 FormatStyle NoBreak = getLLVMStyle();
7011 NoBreak.AlwaysBreakBeforeMultilineStrings = false;
7012 FormatStyle Break = getLLVMStyle();
7013 Break.AlwaysBreakBeforeMultilineStrings = true;
7014 verifyFormat("aaaa = \"bbbb\"\n"
7015 " \"cccc\";",
7016 NoBreak);
7017 verifyFormat("aaaa =\n"
7018 " \"bbbb\"\n"
7019 " \"cccc\";",
7020 Break);
7021 verifyFormat("aaaa(\"bbbb\"\n"
7022 " \"cccc\");",
7023 NoBreak);
7024 verifyFormat("aaaa(\n"
7025 " \"bbbb\"\n"
7026 " \"cccc\");",
7027 Break);
7028 verifyFormat("aaaa(qqq, \"bbbb\"\n"
7029 " \"cccc\");",
7030 NoBreak);
7031 verifyFormat("aaaa(qqq,\n"
7032 " \"bbbb\"\n"
7033 " \"cccc\");",
7034 Break);
7035 verifyFormat("aaaa(qqq,\n"
7036 " L\"bbbb\"\n"
7037 " L\"cccc\");",
7038 Break);
7039 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
7040 " \"bbbb\"));",
7041 Break);
7042 verifyFormat("string s = someFunction(\n"
7043 " \"abc\"\n"
7044 " \"abc\");",
7045 Break);
7046
7047 // As we break before unary operators, breaking right after them is bad.
7048 verifyFormat("string foo = abc ? \"x\"\n"
7049 " \"blah blah blah blah blah blah\"\n"
7050 " : \"y\";",
7051 Break);
7052
7053 // Don't break if there is no column gain.
7054 verifyFormat("f(\"aaaa\"\n"
7055 " \"bbbb\");",
7056 Break);
7057
7058 // Treat literals with escaped newlines like multi-line string literals.
7059 EXPECT_EQ("x = \"a\\\n"
7060 "b\\\n"
7061 "c\";",
7062 format("x = \"a\\\n"
7063 "b\\\n"
7064 "c\";",
7065 NoBreak));
7066 EXPECT_EQ("xxxx =\n"
7067 " \"a\\\n"
7068 "b\\\n"
7069 "c\";",
7070 format("xxxx = \"a\\\n"
7071 "b\\\n"
7072 "c\";",
7073 Break));
7074
7075 EXPECT_EQ("NSString *const kString =\n"
7076 " @\"aaaa\"\n"
7077 " @\"bbbb\";",
7078 format("NSString *const kString = @\"aaaa\"\n"
7079 "@\"bbbb\";",
7080 Break));
7081
7082 Break.ColumnLimit = 0;
7083 verifyFormat("const char *hello = \"hello llvm\";", Break);
7084 }
7085
TEST_F(FormatTest,AlignsPipes)7086 TEST_F(FormatTest, AlignsPipes) {
7087 verifyFormat(
7088 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7089 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7090 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7091 verifyFormat(
7092 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
7093 " << aaaaaaaaaaaaaaaaaaaa;");
7094 verifyFormat(
7095 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7096 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7097 verifyFormat(
7098 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7099 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7100 verifyFormat(
7101 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
7102 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
7103 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
7104 verifyFormat(
7105 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7106 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7107 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7108 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7109 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7110 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7111 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7112 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
7113 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
7114 verifyFormat(
7115 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7116 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7117 verifyFormat(
7118 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
7119 " aaaaaaaaaaaaaaaaaaaaaaaaaa);");
7120
7121 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
7122 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
7123 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7125 " aaaaaaaaaaaaaaaaaaaaa)\n"
7126 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
7127 verifyFormat("LOG_IF(aaa == //\n"
7128 " bbb)\n"
7129 " << a << b;");
7130
7131 // But sometimes, breaking before the first "<<" is desirable.
7132 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7133 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
7134 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
7135 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7136 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7137 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
7138 " << BEF << IsTemplate << Description << E->getType();");
7139 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7140 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7141 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7142 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7143 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7144 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7145 " << aaa;");
7146
7147 verifyFormat(
7148 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7149 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7150
7151 // Incomplete string literal.
7152 EXPECT_EQ("llvm::errs() << \"\n"
7153 " << a;",
7154 format("llvm::errs() << \"\n<<a;"));
7155
7156 verifyFormat("void f() {\n"
7157 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
7158 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
7159 "}");
7160
7161 // Handle 'endl'.
7162 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
7163 " << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7164 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7165
7166 // Handle '\n'.
7167 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
7168 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7169 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
7170 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
7171 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
7172 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
7173 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7174 }
7175
TEST_F(FormatTest,KeepStringLabelValuePairsOnALine)7176 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
7177 verifyFormat("return out << \"somepacket = {\\n\"\n"
7178 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
7179 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
7180 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
7181 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
7182 " << \"}\";");
7183
7184 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7185 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7186 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
7187 verifyFormat(
7188 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
7189 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
7190 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
7191 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
7192 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
7193 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
7194 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7195 verifyFormat(
7196 "void f() {\n"
7197 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
7198 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7199 "}");
7200
7201 // Breaking before the first "<<" is generally not desirable.
7202 verifyFormat(
7203 "llvm::errs()\n"
7204 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7205 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7206 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7207 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7208 getLLVMStyleWithColumns(70));
7209 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7210 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7211 " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7212 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7213 " << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7214 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7215 getLLVMStyleWithColumns(70));
7216
7217 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7218 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7219 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
7220 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7221 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7222 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
7223 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
7224 " (aaaa + aaaa);",
7225 getLLVMStyleWithColumns(40));
7226 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
7227 " (aaaaaaa + aaaaa));",
7228 getLLVMStyleWithColumns(40));
7229 verifyFormat(
7230 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
7231 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
7232 " bbbbbbbbbbbbbbbbbbbbbbb);");
7233 }
7234
TEST_F(FormatTest,UnderstandsEquals)7235 TEST_F(FormatTest, UnderstandsEquals) {
7236 verifyFormat(
7237 "aaaaaaaaaaaaaaaaa =\n"
7238 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7239 verifyFormat(
7240 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7241 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7242 verifyFormat(
7243 "if (a) {\n"
7244 " f();\n"
7245 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7246 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
7247 "}");
7248
7249 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7250 " 100000000 + 10000000) {\n}");
7251 }
7252
TEST_F(FormatTest,WrapsAtFunctionCallsIfNecessary)7253 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
7254 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7255 " .looooooooooooooooooooooooooooooooooooooongFunction();");
7256
7257 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7258 " ->looooooooooooooooooooooooooooooooooooooongFunction();");
7259
7260 verifyFormat(
7261 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
7262 " Parameter2);");
7263
7264 verifyFormat(
7265 "ShortObject->shortFunction(\n"
7266 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
7267 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
7268
7269 verifyFormat("loooooooooooooongFunction(\n"
7270 " LoooooooooooooongObject->looooooooooooooooongFunction());");
7271
7272 verifyFormat(
7273 "function(LoooooooooooooooooooooooooooooooooooongObject\n"
7274 " ->loooooooooooooooooooooooooooooooooooooooongFunction());");
7275
7276 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7277 " .WillRepeatedly(Return(SomeValue));");
7278 verifyFormat("void f() {\n"
7279 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7280 " .Times(2)\n"
7281 " .WillRepeatedly(Return(SomeValue));\n"
7282 "}");
7283 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
7284 " ccccccccccccccccccccccc);");
7285 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7286 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7287 " .aaaaa(aaaaa),\n"
7288 " aaaaaaaaaaaaaaaaaaaaa);");
7289 verifyFormat("void f() {\n"
7290 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7291 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
7292 "}");
7293 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7294 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7295 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7296 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7297 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7298 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7299 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7300 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7301 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
7302 "}");
7303
7304 // Here, it is not necessary to wrap at "." or "->".
7305 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
7306 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7307 verifyFormat(
7308 "aaaaaaaaaaa->aaaaaaaaa(\n"
7309 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7310 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
7311
7312 verifyFormat(
7313 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7314 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
7315 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
7316 " aaaaaaaaa()->aaaaaa()->aaaaa());");
7317 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
7318 " aaaaaaaaa()->aaaaaa()->aaaaa());");
7319
7320 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7321 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7322 " .a();");
7323
7324 FormatStyle NoBinPacking = getLLVMStyle();
7325 NoBinPacking.BinPackParameters = false;
7326 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7327 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7328 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
7329 " aaaaaaaaaaaaaaaaaaa,\n"
7330 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7331 NoBinPacking);
7332
7333 // If there is a subsequent call, change to hanging indentation.
7334 verifyFormat(
7335 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7336 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
7337 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7338 verifyFormat(
7339 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7340 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
7341 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7342 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7343 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7344 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7345 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7346 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7347 }
7348
TEST_F(FormatTest,WrapsTemplateDeclarations)7349 TEST_F(FormatTest, WrapsTemplateDeclarations) {
7350 verifyFormat("template <typename T>\n"
7351 "virtual void loooooooooooongFunction(int Param1, int Param2);");
7352 verifyFormat("template <typename T>\n"
7353 "// T should be one of {A, B}.\n"
7354 "virtual void loooooooooooongFunction(int Param1, int Param2);");
7355 verifyFormat(
7356 "template <typename T>\n"
7357 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
7358 verifyFormat("template <typename T>\n"
7359 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
7360 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
7361 verifyFormat(
7362 "template <typename T>\n"
7363 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
7364 " int Paaaaaaaaaaaaaaaaaaaaram2);");
7365 verifyFormat(
7366 "template <typename T>\n"
7367 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
7368 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
7369 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7370 verifyFormat("template <typename T>\n"
7371 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7372 " int aaaaaaaaaaaaaaaaaaaaaa);");
7373 verifyFormat(
7374 "template <typename T1, typename T2 = char, typename T3 = char,\n"
7375 " typename T4 = char>\n"
7376 "void f();");
7377 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
7378 " template <typename> class cccccccccccccccccccccc,\n"
7379 " typename ddddddddddddd>\n"
7380 "class C {};");
7381 verifyFormat(
7382 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
7383 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7384
7385 verifyFormat("void f() {\n"
7386 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
7387 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
7388 "}");
7389
7390 verifyFormat("template <typename T> class C {};");
7391 verifyFormat("template <typename T> void f();");
7392 verifyFormat("template <typename T> void f() {}");
7393 verifyFormat(
7394 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7395 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7396 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
7397 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7398 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7399 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
7400 " bbbbbbbbbbbbbbbbbbbbbbbb);",
7401 getLLVMStyleWithColumns(72));
7402 EXPECT_EQ("static_cast<A< //\n"
7403 " B> *>(\n"
7404 "\n"
7405 ");",
7406 format("static_cast<A<//\n"
7407 " B>*>(\n"
7408 "\n"
7409 " );"));
7410 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7411 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
7412
7413 FormatStyle AlwaysBreak = getLLVMStyle();
7414 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7415 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
7416 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
7417 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
7418 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7419 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7420 " ccccccccccccccccccccccccccccccccccccccccccccccc);");
7421 verifyFormat("template <template <typename> class Fooooooo,\n"
7422 " template <typename> class Baaaaaaar>\n"
7423 "struct C {};",
7424 AlwaysBreak);
7425 verifyFormat("template <typename T> // T can be A, B or C.\n"
7426 "struct C {};",
7427 AlwaysBreak);
7428 verifyFormat("template <enum E> class A {\n"
7429 "public:\n"
7430 " E *f();\n"
7431 "};");
7432
7433 FormatStyle NeverBreak = getLLVMStyle();
7434 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
7435 verifyFormat("template <typename T> class C {};", NeverBreak);
7436 verifyFormat("template <typename T> void f();", NeverBreak);
7437 verifyFormat("template <typename T> void f() {}", NeverBreak);
7438 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7439 "bbbbbbbbbbbbbbbbbbbb) {}",
7440 NeverBreak);
7441 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7442 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7443 " ccccccccccccccccccccccccccccccccccccccccccccccc);",
7444 NeverBreak);
7445 verifyFormat("template <template <typename> class Fooooooo,\n"
7446 " template <typename> class Baaaaaaar>\n"
7447 "struct C {};",
7448 NeverBreak);
7449 verifyFormat("template <typename T> // T can be A, B or C.\n"
7450 "struct C {};",
7451 NeverBreak);
7452 verifyFormat("template <enum E> class A {\n"
7453 "public:\n"
7454 " E *f();\n"
7455 "};",
7456 NeverBreak);
7457 NeverBreak.PenaltyBreakTemplateDeclaration = 100;
7458 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7459 "bbbbbbbbbbbbbbbbbbbb) {}",
7460 NeverBreak);
7461 }
7462
TEST_F(FormatTest,WrapsTemplateDeclarationsWithComments)7463 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
7464 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
7465 Style.ColumnLimit = 60;
7466 EXPECT_EQ("// Baseline - no comments.\n"
7467 "template <\n"
7468 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7469 "void f() {}",
7470 format("// Baseline - no comments.\n"
7471 "template <\n"
7472 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7473 "void f() {}",
7474 Style));
7475
7476 EXPECT_EQ("template <\n"
7477 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7478 "void f() {}",
7479 format("template <\n"
7480 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7481 "void f() {}",
7482 Style));
7483
7484 EXPECT_EQ(
7485 "template <\n"
7486 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
7487 "void f() {}",
7488 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
7489 "void f() {}",
7490 Style));
7491
7492 EXPECT_EQ(
7493 "template <\n"
7494 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7495 " // multiline\n"
7496 "void f() {}",
7497 format("template <\n"
7498 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7499 " // multiline\n"
7500 "void f() {}",
7501 Style));
7502
7503 EXPECT_EQ(
7504 "template <typename aaaaaaaaaa<\n"
7505 " bbbbbbbbbbbb>::value> // trailing loooong\n"
7506 "void f() {}",
7507 format(
7508 "template <\n"
7509 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
7510 "void f() {}",
7511 Style));
7512 }
7513
TEST_F(FormatTest,WrapsTemplateParameters)7514 TEST_F(FormatTest, WrapsTemplateParameters) {
7515 FormatStyle Style = getLLVMStyle();
7516 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7517 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7518 verifyFormat(
7519 "template <typename... a> struct q {};\n"
7520 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7521 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7522 " y;",
7523 Style);
7524 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7525 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7526 verifyFormat(
7527 "template <typename... a> struct r {};\n"
7528 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7529 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7530 " y;",
7531 Style);
7532 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7533 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7534 verifyFormat("template <typename... a> struct s {};\n"
7535 "extern s<\n"
7536 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7537 "aaaaaaaaaaaaaaaaaaaaaa,\n"
7538 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7539 "aaaaaaaaaaaaaaaaaaaaaa>\n"
7540 " y;",
7541 Style);
7542 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7543 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7544 verifyFormat("template <typename... a> struct t {};\n"
7545 "extern t<\n"
7546 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7547 "aaaaaaaaaaaaaaaaaaaaaa,\n"
7548 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7549 "aaaaaaaaaaaaaaaaaaaaaa>\n"
7550 " y;",
7551 Style);
7552 }
7553
TEST_F(FormatTest,WrapsAtNestedNameSpecifiers)7554 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
7555 verifyFormat(
7556 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7557 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7558 verifyFormat(
7559 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7561 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7562
7563 // FIXME: Should we have the extra indent after the second break?
7564 verifyFormat(
7565 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7566 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7567 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7568
7569 verifyFormat(
7570 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
7571 " cccccccccccccccccccccccccccccccccccccccccccccc());");
7572
7573 // Breaking at nested name specifiers is generally not desirable.
7574 verifyFormat(
7575 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7576 " aaaaaaaaaaaaaaaaaaaaaaa);");
7577
7578 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
7579 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7580 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7581 " aaaaaaaaaaaaaaaaaaaaa);",
7582 getLLVMStyleWithColumns(74));
7583
7584 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7585 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7586 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7587 }
7588
TEST_F(FormatTest,UnderstandsTemplateParameters)7589 TEST_F(FormatTest, UnderstandsTemplateParameters) {
7590 verifyFormat("A<int> a;");
7591 verifyFormat("A<A<A<int>>> a;");
7592 verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
7593 verifyFormat("bool x = a < 1 || 2 > a;");
7594 verifyFormat("bool x = 5 < f<int>();");
7595 verifyFormat("bool x = f<int>() > 5;");
7596 verifyFormat("bool x = 5 < a<int>::x;");
7597 verifyFormat("bool x = a < 4 ? a > 2 : false;");
7598 verifyFormat("bool x = f() ? a < 2 : a > 2;");
7599
7600 verifyGoogleFormat("A<A<int>> a;");
7601 verifyGoogleFormat("A<A<A<int>>> a;");
7602 verifyGoogleFormat("A<A<A<A<int>>>> a;");
7603 verifyGoogleFormat("A<A<int> > a;");
7604 verifyGoogleFormat("A<A<A<int> > > a;");
7605 verifyGoogleFormat("A<A<A<A<int> > > > a;");
7606 verifyGoogleFormat("A<::A<int>> a;");
7607 verifyGoogleFormat("A<::A> a;");
7608 verifyGoogleFormat("A< ::A> a;");
7609 verifyGoogleFormat("A< ::A<int> > a;");
7610 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
7611 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
7612 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
7613 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
7614 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
7615 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
7616
7617 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
7618
7619 // template closer followed by a token that starts with > or =
7620 verifyFormat("bool b = a<1> > 1;");
7621 verifyFormat("bool b = a<1> >= 1;");
7622 verifyFormat("int i = a<1> >> 1;");
7623 FormatStyle Style = getLLVMStyle();
7624 Style.SpaceBeforeAssignmentOperators = false;
7625 verifyFormat("bool b= a<1> == 1;", Style);
7626 verifyFormat("a<int> = 1;", Style);
7627 verifyFormat("a<int> >>= 1;", Style);
7628
7629 verifyFormat("test >> a >> b;");
7630 verifyFormat("test << a >> b;");
7631
7632 verifyFormat("f<int>();");
7633 verifyFormat("template <typename T> void f() {}");
7634 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
7635 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
7636 "sizeof(char)>::type>;");
7637 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
7638 verifyFormat("f(a.operator()<A>());");
7639 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7640 " .template operator()<A>());",
7641 getLLVMStyleWithColumns(35));
7642
7643 // Not template parameters.
7644 verifyFormat("return a < b && c > d;");
7645 verifyFormat("void f() {\n"
7646 " while (a < b && c > d) {\n"
7647 " }\n"
7648 "}");
7649 verifyFormat("template <typename... Types>\n"
7650 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
7651
7652 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7653 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
7654 getLLVMStyleWithColumns(60));
7655 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
7656 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
7657 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
7658 verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
7659 }
7660
TEST_F(FormatTest,UnderstandsShiftOperators)7661 TEST_F(FormatTest, UnderstandsShiftOperators) {
7662 verifyFormat("if (i < x >> 1)");
7663 verifyFormat("while (i < x >> 1)");
7664 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
7665 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
7666 verifyFormat(
7667 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
7668 verifyFormat("Foo.call<Bar<Function>>()");
7669 verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
7670 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
7671 "++i, v = v >> 1)");
7672 verifyFormat("if (w<u<v<x>>, 1>::t)");
7673 }
7674
TEST_F(FormatTest,BitshiftOperatorWidth)7675 TEST_F(FormatTest, BitshiftOperatorWidth) {
7676 EXPECT_EQ("int a = 1 << 2; /* foo\n"
7677 " bar */",
7678 format("int a=1<<2; /* foo\n"
7679 " bar */"));
7680
7681 EXPECT_EQ("int b = 256 >> 1; /* foo\n"
7682 " bar */",
7683 format("int b =256>>1 ; /* foo\n"
7684 " bar */"));
7685 }
7686
TEST_F(FormatTest,UnderstandsBinaryOperators)7687 TEST_F(FormatTest, UnderstandsBinaryOperators) {
7688 verifyFormat("COMPARE(a, ==, b);");
7689 verifyFormat("auto s = sizeof...(Ts) - 1;");
7690 }
7691
TEST_F(FormatTest,UnderstandsPointersToMembers)7692 TEST_F(FormatTest, UnderstandsPointersToMembers) {
7693 verifyFormat("int A::*x;");
7694 verifyFormat("int (S::*func)(void *);");
7695 verifyFormat("void f() { int (S::*func)(void *); }");
7696 verifyFormat("typedef bool *(Class::*Member)() const;");
7697 verifyFormat("void f() {\n"
7698 " (a->*f)();\n"
7699 " a->*x;\n"
7700 " (a.*f)();\n"
7701 " ((*a).*f)();\n"
7702 " a.*x;\n"
7703 "}");
7704 verifyFormat("void f() {\n"
7705 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
7706 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
7707 "}");
7708 verifyFormat(
7709 "(aaaaaaaaaa->*bbbbbbb)(\n"
7710 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7711 FormatStyle Style = getLLVMStyle();
7712 Style.PointerAlignment = FormatStyle::PAS_Left;
7713 verifyFormat("typedef bool* (Class::*Member)() const;", Style);
7714 }
7715
TEST_F(FormatTest,UnderstandsUnaryOperators)7716 TEST_F(FormatTest, UnderstandsUnaryOperators) {
7717 verifyFormat("int a = -2;");
7718 verifyFormat("f(-1, -2, -3);");
7719 verifyFormat("a[-1] = 5;");
7720 verifyFormat("int a = 5 + -2;");
7721 verifyFormat("if (i == -1) {\n}");
7722 verifyFormat("if (i != -1) {\n}");
7723 verifyFormat("if (i > -1) {\n}");
7724 verifyFormat("if (i < -1) {\n}");
7725 verifyFormat("++(a->f());");
7726 verifyFormat("--(a->f());");
7727 verifyFormat("(a->f())++;");
7728 verifyFormat("a[42]++;");
7729 verifyFormat("if (!(a->f())) {\n}");
7730 verifyFormat("if (!+i) {\n}");
7731 verifyFormat("~&a;");
7732
7733 verifyFormat("a-- > b;");
7734 verifyFormat("b ? -a : c;");
7735 verifyFormat("n * sizeof char16;");
7736 verifyFormat("n * alignof char16;", getGoogleStyle());
7737 verifyFormat("sizeof(char);");
7738 verifyFormat("alignof(char);", getGoogleStyle());
7739
7740 verifyFormat("return -1;");
7741 verifyFormat("throw -1;");
7742 verifyFormat("switch (a) {\n"
7743 "case -1:\n"
7744 " break;\n"
7745 "}");
7746 verifyFormat("#define X -1");
7747 verifyFormat("#define X -kConstant");
7748
7749 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
7750 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
7751
7752 verifyFormat("int a = /* confusing comment */ -1;");
7753 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
7754 verifyFormat("int a = i /* confusing comment */++;");
7755
7756 verifyFormat("co_yield -1;");
7757 verifyFormat("co_return -1;");
7758 }
7759
TEST_F(FormatTest,DoesNotIndentRelativeToUnaryOperators)7760 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
7761 verifyFormat("if (!aaaaaaaaaa( // break\n"
7762 " aaaaa)) {\n"
7763 "}");
7764 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
7765 " aaaaa));");
7766 verifyFormat("*aaa = aaaaaaa( // break\n"
7767 " bbbbbb);");
7768 }
7769
TEST_F(FormatTest,UnderstandsOverloadedOperators)7770 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
7771 verifyFormat("bool operator<();");
7772 verifyFormat("bool operator>();");
7773 verifyFormat("bool operator=();");
7774 verifyFormat("bool operator==();");
7775 verifyFormat("bool operator!=();");
7776 verifyFormat("int operator+();");
7777 verifyFormat("int operator++();");
7778 verifyFormat("int operator++(int) volatile noexcept;");
7779 verifyFormat("bool operator,();");
7780 verifyFormat("bool operator();");
7781 verifyFormat("bool operator()();");
7782 verifyFormat("bool operator[]();");
7783 verifyFormat("operator bool();");
7784 verifyFormat("operator int();");
7785 verifyFormat("operator void *();");
7786 verifyFormat("operator SomeType<int>();");
7787 verifyFormat("operator SomeType<int, int>();");
7788 verifyFormat("operator SomeType<SomeType<int>>();");
7789 verifyFormat("void *operator new(std::size_t size);");
7790 verifyFormat("void *operator new[](std::size_t size);");
7791 verifyFormat("void operator delete(void *ptr);");
7792 verifyFormat("void operator delete[](void *ptr);");
7793 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
7794 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
7795 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
7796 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
7797
7798 verifyFormat(
7799 "ostream &operator<<(ostream &OutputStream,\n"
7800 " SomeReallyLongType WithSomeReallyLongValue);");
7801 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
7802 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
7803 " return left.group < right.group;\n"
7804 "}");
7805 verifyFormat("SomeType &operator=(const SomeType &S);");
7806 verifyFormat("f.template operator()<int>();");
7807
7808 verifyGoogleFormat("operator void*();");
7809 verifyGoogleFormat("operator SomeType<SomeType<int>>();");
7810 verifyGoogleFormat("operator ::A();");
7811
7812 verifyFormat("using A::operator+;");
7813 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
7814 "int i;");
7815 }
7816
TEST_F(FormatTest,UnderstandsFunctionRefQualification)7817 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
7818 verifyFormat("Deleted &operator=(const Deleted &) & = default;");
7819 verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
7820 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
7821 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
7822 verifyFormat("Deleted &operator=(const Deleted &) &;");
7823 verifyFormat("Deleted &operator=(const Deleted &) &&;");
7824 verifyFormat("SomeType MemberFunction(const Deleted &) &;");
7825 verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
7826 verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
7827 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
7828 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
7829 verifyFormat("void Fn(T const &) const &;");
7830 verifyFormat("void Fn(T const volatile &&) const volatile &&;");
7831 verifyFormat("template <typename T>\n"
7832 "void F(T) && = delete;",
7833 getGoogleStyle());
7834
7835 FormatStyle AlignLeft = getLLVMStyle();
7836 AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
7837 verifyFormat("void A::b() && {}", AlignLeft);
7838 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
7839 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
7840 AlignLeft);
7841 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
7842 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
7843 verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
7844 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
7845 verifyFormat("auto Function(T) & -> void {}", AlignLeft);
7846 verifyFormat("auto Function(T) & -> void;", AlignLeft);
7847 verifyFormat("void Fn(T const&) const&;", AlignLeft);
7848 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
7849
7850 FormatStyle Spaces = getLLVMStyle();
7851 Spaces.SpacesInCStyleCastParentheses = true;
7852 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
7853 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
7854 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
7855 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
7856
7857 Spaces.SpacesInCStyleCastParentheses = false;
7858 Spaces.SpacesInParentheses = true;
7859 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
7860 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
7861 Spaces);
7862 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
7863 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
7864
7865 FormatStyle BreakTemplate = getLLVMStyle();
7866 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7867
7868 verifyFormat("struct f {\n"
7869 " template <class T>\n"
7870 " int &foo(const std::string &str) &noexcept {}\n"
7871 "};",
7872 BreakTemplate);
7873
7874 verifyFormat("struct f {\n"
7875 " template <class T>\n"
7876 " int &foo(const std::string &str) &&noexcept {}\n"
7877 "};",
7878 BreakTemplate);
7879
7880 verifyFormat("struct f {\n"
7881 " template <class T>\n"
7882 " int &foo(const std::string &str) const &noexcept {}\n"
7883 "};",
7884 BreakTemplate);
7885
7886 verifyFormat("struct f {\n"
7887 " template <class T>\n"
7888 " int &foo(const std::string &str) const &noexcept {}\n"
7889 "};",
7890 BreakTemplate);
7891
7892 verifyFormat("struct f {\n"
7893 " template <class T>\n"
7894 " auto foo(const std::string &str) &&noexcept -> int & {}\n"
7895 "};",
7896 BreakTemplate);
7897
7898 FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
7899 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
7900 FormatStyle::BTDS_Yes;
7901 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
7902
7903 verifyFormat("struct f {\n"
7904 " template <class T>\n"
7905 " int& foo(const std::string& str) & noexcept {}\n"
7906 "};",
7907 AlignLeftBreakTemplate);
7908
7909 verifyFormat("struct f {\n"
7910 " template <class T>\n"
7911 " int& foo(const std::string& str) && noexcept {}\n"
7912 "};",
7913 AlignLeftBreakTemplate);
7914
7915 verifyFormat("struct f {\n"
7916 " template <class T>\n"
7917 " int& foo(const std::string& str) const& noexcept {}\n"
7918 "};",
7919 AlignLeftBreakTemplate);
7920
7921 verifyFormat("struct f {\n"
7922 " template <class T>\n"
7923 " int& foo(const std::string& str) const&& noexcept {}\n"
7924 "};",
7925 AlignLeftBreakTemplate);
7926
7927 verifyFormat("struct f {\n"
7928 " template <class T>\n"
7929 " auto foo(const std::string& str) && noexcept -> int& {}\n"
7930 "};",
7931 AlignLeftBreakTemplate);
7932
7933 // The `&` in `Type&` should not be confused with a trailing `&` of
7934 // DEPRECATED(reason) member function.
7935 verifyFormat("struct f {\n"
7936 " template <class T>\n"
7937 " DEPRECATED(reason)\n"
7938 " Type &foo(arguments) {}\n"
7939 "};",
7940 BreakTemplate);
7941
7942 verifyFormat("struct f {\n"
7943 " template <class T>\n"
7944 " DEPRECATED(reason)\n"
7945 " Type& foo(arguments) {}\n"
7946 "};",
7947 AlignLeftBreakTemplate);
7948
7949 verifyFormat("void (*foopt)(int) = &func;");
7950 }
7951
TEST_F(FormatTest,UnderstandsNewAndDelete)7952 TEST_F(FormatTest, UnderstandsNewAndDelete) {
7953 verifyFormat("void f() {\n"
7954 " A *a = new A;\n"
7955 " A *a = new (placement) A;\n"
7956 " delete a;\n"
7957 " delete (A *)a;\n"
7958 "}");
7959 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7960 " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7961 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7962 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7963 " typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7964 verifyFormat("delete[] h->p;");
7965 }
7966
TEST_F(FormatTest,UnderstandsUsesOfStarAndAmp)7967 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
7968 verifyFormat("int *f(int *a) {}");
7969 verifyFormat("int main(int argc, char **argv) {}");
7970 verifyFormat("Test::Test(int b) : a(b * b) {}");
7971 verifyIndependentOfContext("f(a, *a);");
7972 verifyFormat("void g() { f(*a); }");
7973 verifyIndependentOfContext("int a = b * 10;");
7974 verifyIndependentOfContext("int a = 10 * b;");
7975 verifyIndependentOfContext("int a = b * c;");
7976 verifyIndependentOfContext("int a += b * c;");
7977 verifyIndependentOfContext("int a -= b * c;");
7978 verifyIndependentOfContext("int a *= b * c;");
7979 verifyIndependentOfContext("int a /= b * c;");
7980 verifyIndependentOfContext("int a = *b;");
7981 verifyIndependentOfContext("int a = *b * c;");
7982 verifyIndependentOfContext("int a = b * *c;");
7983 verifyIndependentOfContext("int a = b * (10);");
7984 verifyIndependentOfContext("S << b * (10);");
7985 verifyIndependentOfContext("return 10 * b;");
7986 verifyIndependentOfContext("return *b * *c;");
7987 verifyIndependentOfContext("return a & ~b;");
7988 verifyIndependentOfContext("f(b ? *c : *d);");
7989 verifyIndependentOfContext("int a = b ? *c : *d;");
7990 verifyIndependentOfContext("*b = a;");
7991 verifyIndependentOfContext("a * ~b;");
7992 verifyIndependentOfContext("a * !b;");
7993 verifyIndependentOfContext("a * +b;");
7994 verifyIndependentOfContext("a * -b;");
7995 verifyIndependentOfContext("a * ++b;");
7996 verifyIndependentOfContext("a * --b;");
7997 verifyIndependentOfContext("a[4] * b;");
7998 verifyIndependentOfContext("a[a * a] = 1;");
7999 verifyIndependentOfContext("f() * b;");
8000 verifyIndependentOfContext("a * [self dostuff];");
8001 verifyIndependentOfContext("int x = a * (a + b);");
8002 verifyIndependentOfContext("(a *)(a + b);");
8003 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
8004 verifyIndependentOfContext("int *pa = (int *)&a;");
8005 verifyIndependentOfContext("return sizeof(int **);");
8006 verifyIndependentOfContext("return sizeof(int ******);");
8007 verifyIndependentOfContext("return (int **&)a;");
8008 verifyIndependentOfContext("f((*PointerToArray)[10]);");
8009 verifyFormat("void f(Type (*parameter)[10]) {}");
8010 verifyFormat("void f(Type (¶meter)[10]) {}");
8011 verifyGoogleFormat("return sizeof(int**);");
8012 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
8013 verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
8014 verifyFormat("auto a = [](int **&, int ***) {};");
8015 verifyFormat("auto PointerBinding = [](const char *S) {};");
8016 verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
8017 verifyFormat("[](const decltype(*a) &value) {}");
8018 verifyFormat("[](const typeof(*a) &value) {}");
8019 verifyFormat("[](const _Atomic(a *) &value) {}");
8020 verifyFormat("[](const __underlying_type(a) &value) {}");
8021 verifyFormat("decltype(a * b) F();");
8022 verifyFormat("typeof(a * b) F();");
8023 verifyFormat("#define MACRO() [](A *a) { return 1; }");
8024 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
8025 verifyIndependentOfContext("typedef void (*f)(int *a);");
8026 verifyIndependentOfContext("int i{a * b};");
8027 verifyIndependentOfContext("aaa && aaa->f();");
8028 verifyIndependentOfContext("int x = ~*p;");
8029 verifyFormat("Constructor() : a(a), area(width * height) {}");
8030 verifyFormat("Constructor() : a(a), area(a, width * height) {}");
8031 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
8032 verifyFormat("void f() { f(a, c * d); }");
8033 verifyFormat("void f() { f(new a(), c * d); }");
8034 verifyFormat("void f(const MyOverride &override);");
8035 verifyFormat("void f(const MyFinal &final);");
8036 verifyIndependentOfContext("bool a = f() && override.f();");
8037 verifyIndependentOfContext("bool a = f() && final.f();");
8038
8039 verifyIndependentOfContext("InvalidRegions[*R] = 0;");
8040
8041 verifyIndependentOfContext("A<int *> a;");
8042 verifyIndependentOfContext("A<int **> a;");
8043 verifyIndependentOfContext("A<int *, int *> a;");
8044 verifyIndependentOfContext("A<int *[]> a;");
8045 verifyIndependentOfContext(
8046 "const char *const p = reinterpret_cast<const char *const>(q);");
8047 verifyIndependentOfContext("A<int **, int **> a;");
8048 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
8049 verifyFormat("for (char **a = b; *a; ++a) {\n}");
8050 verifyFormat("for (; a && b;) {\n}");
8051 verifyFormat("bool foo = true && [] { return false; }();");
8052
8053 verifyFormat(
8054 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8055 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8056
8057 verifyGoogleFormat("int const* a = &b;");
8058 verifyGoogleFormat("**outparam = 1;");
8059 verifyGoogleFormat("*outparam = a * b;");
8060 verifyGoogleFormat("int main(int argc, char** argv) {}");
8061 verifyGoogleFormat("A<int*> a;");
8062 verifyGoogleFormat("A<int**> a;");
8063 verifyGoogleFormat("A<int*, int*> a;");
8064 verifyGoogleFormat("A<int**, int**> a;");
8065 verifyGoogleFormat("f(b ? *c : *d);");
8066 verifyGoogleFormat("int a = b ? *c : *d;");
8067 verifyGoogleFormat("Type* t = **x;");
8068 verifyGoogleFormat("Type* t = *++*x;");
8069 verifyGoogleFormat("*++*x;");
8070 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
8071 verifyGoogleFormat("Type* t = x++ * y;");
8072 verifyGoogleFormat(
8073 "const char* const p = reinterpret_cast<const char* const>(q);");
8074 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
8075 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
8076 verifyGoogleFormat("template <typename T>\n"
8077 "void f(int i = 0, SomeType** temps = NULL);");
8078
8079 FormatStyle Left = getLLVMStyle();
8080 Left.PointerAlignment = FormatStyle::PAS_Left;
8081 verifyFormat("x = *a(x) = *a(y);", Left);
8082 verifyFormat("for (;; *a = b) {\n}", Left);
8083 verifyFormat("return *this += 1;", Left);
8084 verifyFormat("throw *x;", Left);
8085 verifyFormat("delete *x;", Left);
8086 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
8087 verifyFormat("[](const decltype(*a)* ptr) {}", Left);
8088 verifyFormat("[](const typeof(*a)* ptr) {}", Left);
8089 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
8090 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
8091 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
8092 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
8093 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
8094 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
8095
8096 verifyIndependentOfContext("a = *(x + y);");
8097 verifyIndependentOfContext("a = &(x + y);");
8098 verifyIndependentOfContext("*(x + y).call();");
8099 verifyIndependentOfContext("&(x + y)->call();");
8100 verifyFormat("void f() { &(*I).first; }");
8101
8102 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
8103 verifyFormat(
8104 "int *MyValues = {\n"
8105 " *A, // Operator detection might be confused by the '{'\n"
8106 " *BB // Operator detection might be confused by previous comment\n"
8107 "};");
8108
8109 verifyIndependentOfContext("if (int *a = &b)");
8110 verifyIndependentOfContext("if (int &a = *b)");
8111 verifyIndependentOfContext("if (a & b[i])");
8112 verifyIndependentOfContext("if constexpr (a & b[i])");
8113 verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
8114 verifyIndependentOfContext("if (a * (b * c))");
8115 verifyIndependentOfContext("if constexpr (a * (b * c))");
8116 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
8117 verifyIndependentOfContext("if (a::b::c::d & b[i])");
8118 verifyIndependentOfContext("if (*b[i])");
8119 verifyIndependentOfContext("if (int *a = (&b))");
8120 verifyIndependentOfContext("while (int *a = &b)");
8121 verifyIndependentOfContext("while (a * (b * c))");
8122 verifyIndependentOfContext("size = sizeof *a;");
8123 verifyIndependentOfContext("if (a && (b = c))");
8124 verifyFormat("void f() {\n"
8125 " for (const int &v : Values) {\n"
8126 " }\n"
8127 "}");
8128 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
8129 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
8130 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
8131
8132 verifyFormat("#define A (!a * b)");
8133 verifyFormat("#define MACRO \\\n"
8134 " int *i = a * b; \\\n"
8135 " void f(a *b);",
8136 getLLVMStyleWithColumns(19));
8137
8138 verifyIndependentOfContext("A = new SomeType *[Length];");
8139 verifyIndependentOfContext("A = new SomeType *[Length]();");
8140 verifyIndependentOfContext("T **t = new T *;");
8141 verifyIndependentOfContext("T **t = new T *();");
8142 verifyGoogleFormat("A = new SomeType*[Length]();");
8143 verifyGoogleFormat("A = new SomeType*[Length];");
8144 verifyGoogleFormat("T** t = new T*;");
8145 verifyGoogleFormat("T** t = new T*();");
8146
8147 verifyFormat("STATIC_ASSERT((a & b) == 0);");
8148 verifyFormat("STATIC_ASSERT(0 == (a & b));");
8149 verifyFormat("template <bool a, bool b> "
8150 "typename t::if<x && y>::type f() {}");
8151 verifyFormat("template <int *y> f() {}");
8152 verifyFormat("vector<int *> v;");
8153 verifyFormat("vector<int *const> v;");
8154 verifyFormat("vector<int *const **const *> v;");
8155 verifyFormat("vector<int *volatile> v;");
8156 verifyFormat("vector<a *_Nonnull> v;");
8157 verifyFormat("vector<a *_Nullable> v;");
8158 verifyFormat("vector<a *_Null_unspecified> v;");
8159 verifyFormat("vector<a *__ptr32> v;");
8160 verifyFormat("vector<a *__ptr64> v;");
8161 verifyFormat("vector<a *__capability> v;");
8162 FormatStyle TypeMacros = getLLVMStyle();
8163 TypeMacros.TypenameMacros = {"LIST"};
8164 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
8165 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
8166 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
8167 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
8168 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
8169
8170 FormatStyle CustomQualifier = getLLVMStyle();
8171 // Add indentifers that should not be parsed as a qualifier by default.
8172 CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8173 CustomQualifier.AttributeMacros.push_back("_My_qualifier");
8174 CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
8175 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
8176 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
8177 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
8178 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
8179 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
8180 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
8181 verifyFormat("vector<a * _NotAQualifier> v;");
8182 verifyFormat("vector<a * __not_a_qualifier> v;");
8183 verifyFormat("vector<a * b> v;");
8184 verifyFormat("foo<b && false>();");
8185 verifyFormat("foo<b & 1>();");
8186 verifyFormat("decltype(*::std::declval<const T &>()) void F();");
8187 verifyFormat("typeof(*::std::declval<const T &>()) void F();");
8188 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
8189 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
8190 verifyFormat(
8191 "template <class T, class = typename std::enable_if<\n"
8192 " std::is_integral<T>::value &&\n"
8193 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
8194 "void F();",
8195 getLLVMStyleWithColumns(70));
8196 verifyFormat("template <class T,\n"
8197 " class = typename std::enable_if<\n"
8198 " std::is_integral<T>::value &&\n"
8199 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
8200 " class U>\n"
8201 "void F();",
8202 getLLVMStyleWithColumns(70));
8203 verifyFormat(
8204 "template <class T,\n"
8205 " class = typename ::std::enable_if<\n"
8206 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
8207 "void F();",
8208 getGoogleStyleWithColumns(68));
8209
8210 verifyIndependentOfContext("MACRO(int *i);");
8211 verifyIndependentOfContext("MACRO(auto *a);");
8212 verifyIndependentOfContext("MACRO(const A *a);");
8213 verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
8214 verifyIndependentOfContext("MACRO(decltype(A) *a);");
8215 verifyIndependentOfContext("MACRO(typeof(A) *a);");
8216 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
8217 verifyIndependentOfContext("MACRO(A *const a);");
8218 verifyIndependentOfContext("MACRO(A *restrict a);");
8219 verifyIndependentOfContext("MACRO(A *__restrict__ a);");
8220 verifyIndependentOfContext("MACRO(A *__restrict a);");
8221 verifyIndependentOfContext("MACRO(A *volatile a);");
8222 verifyIndependentOfContext("MACRO(A *__volatile a);");
8223 verifyIndependentOfContext("MACRO(A *__volatile__ a);");
8224 verifyIndependentOfContext("MACRO(A *_Nonnull a);");
8225 verifyIndependentOfContext("MACRO(A *_Nullable a);");
8226 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
8227 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
8228 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
8229 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
8230 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
8231 verifyIndependentOfContext("MACRO(A *__ptr32 a);");
8232 verifyIndependentOfContext("MACRO(A *__ptr64 a);");
8233 verifyIndependentOfContext("MACRO(A *__capability);");
8234 verifyIndependentOfContext("MACRO(A &__capability);");
8235 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration
8236 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
8237 // If we add __my_qualifier to AttributeMacros it should always be parsed as
8238 // a type declaration:
8239 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
8240 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
8241 // Also check that TypenameMacros prevents parsing it as multiplication:
8242 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
8243 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
8244
8245 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
8246 verifyFormat("void f() { f(float{1}, a * a); }");
8247 // FIXME: Is there a way to make this work?
8248 // verifyIndependentOfContext("MACRO(A *a);");
8249 verifyFormat("MACRO(A &B);");
8250 verifyFormat("MACRO(A *B);");
8251 verifyFormat("void f() { MACRO(A * B); }");
8252 verifyFormat("void f() { MACRO(A & B); }");
8253
8254 // This lambda was mis-formatted after D88956 (treating it as a binop):
8255 verifyFormat("auto x = [](const decltype(x) &ptr) {};");
8256 verifyFormat("auto x = [](const decltype(x) *ptr) {};");
8257 verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
8258 verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
8259
8260 verifyFormat("DatumHandle const *operator->() const { return input_; }");
8261 verifyFormat("return options != nullptr && operator==(*options);");
8262
8263 EXPECT_EQ("#define OP(x) \\\n"
8264 " ostream &operator<<(ostream &s, const A &a) { \\\n"
8265 " return s << a.DebugString(); \\\n"
8266 " }",
8267 format("#define OP(x) \\\n"
8268 " ostream &operator<<(ostream &s, const A &a) { \\\n"
8269 " return s << a.DebugString(); \\\n"
8270 " }",
8271 getLLVMStyleWithColumns(50)));
8272
8273 // FIXME: We cannot handle this case yet; we might be able to figure out that
8274 // foo<x> d > v; doesn't make sense.
8275 verifyFormat("foo<a<b && c> d> v;");
8276
8277 FormatStyle PointerMiddle = getLLVMStyle();
8278 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
8279 verifyFormat("delete *x;", PointerMiddle);
8280 verifyFormat("int * x;", PointerMiddle);
8281 verifyFormat("int *[] x;", PointerMiddle);
8282 verifyFormat("template <int * y> f() {}", PointerMiddle);
8283 verifyFormat("int * f(int * a) {}", PointerMiddle);
8284 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
8285 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
8286 verifyFormat("A<int *> a;", PointerMiddle);
8287 verifyFormat("A<int **> a;", PointerMiddle);
8288 verifyFormat("A<int *, int *> a;", PointerMiddle);
8289 verifyFormat("A<int *[]> a;", PointerMiddle);
8290 verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
8291 verifyFormat("A = new SomeType *[Length];", PointerMiddle);
8292 verifyFormat("T ** t = new T *;", PointerMiddle);
8293
8294 // Member function reference qualifiers aren't binary operators.
8295 verifyFormat("string // break\n"
8296 "operator()() & {}");
8297 verifyFormat("string // break\n"
8298 "operator()() && {}");
8299 verifyGoogleFormat("template <typename T>\n"
8300 "auto x() & -> int {}");
8301 }
8302
TEST_F(FormatTest,UnderstandsAttributes)8303 TEST_F(FormatTest, UnderstandsAttributes) {
8304 verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
8305 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
8306 "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8307 FormatStyle AfterType = getLLVMStyle();
8308 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8309 verifyFormat("__attribute__((nodebug)) void\n"
8310 "foo() {}\n",
8311 AfterType);
8312 verifyFormat("__unused void\n"
8313 "foo() {}",
8314 AfterType);
8315
8316 FormatStyle CustomAttrs = getLLVMStyle();
8317 CustomAttrs.AttributeMacros.push_back("__unused");
8318 CustomAttrs.AttributeMacros.push_back("__attr1");
8319 CustomAttrs.AttributeMacros.push_back("__attr2");
8320 CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
8321 verifyFormat("vector<SomeType *__attribute((foo))> v;");
8322 verifyFormat("vector<SomeType *__attribute__((foo))> v;");
8323 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
8324 // Check that it is parsed as a multiplication without AttributeMacros and
8325 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
8326 verifyFormat("vector<SomeType * __attr1> v;");
8327 verifyFormat("vector<SomeType __attr1 *> v;");
8328 verifyFormat("vector<SomeType __attr1 *const> v;");
8329 verifyFormat("vector<SomeType __attr1 * __attr2> v;");
8330 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
8331 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
8332 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
8333 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
8334 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
8335 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
8336 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
8337
8338 // Check that these are not parsed as function declarations:
8339 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8340 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
8341 verifyFormat("SomeType s(InitValue);", CustomAttrs);
8342 verifyFormat("SomeType s{InitValue};", CustomAttrs);
8343 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
8344 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
8345 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
8346 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
8347 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
8348 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
8349 }
8350
TEST_F(FormatTest,UnderstandsPointerQualifiersInCast)8351 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
8352 // Check that qualifiers on pointers don't break parsing of casts.
8353 verifyFormat("x = (foo *const)*v;");
8354 verifyFormat("x = (foo *volatile)*v;");
8355 verifyFormat("x = (foo *restrict)*v;");
8356 verifyFormat("x = (foo *__attribute__((foo)))*v;");
8357 verifyFormat("x = (foo *_Nonnull)*v;");
8358 verifyFormat("x = (foo *_Nullable)*v;");
8359 verifyFormat("x = (foo *_Null_unspecified)*v;");
8360 verifyFormat("x = (foo *_Nonnull)*v;");
8361 verifyFormat("x = (foo *[[clang::attr]])*v;");
8362 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
8363 verifyFormat("x = (foo *__ptr32)*v;");
8364 verifyFormat("x = (foo *__ptr64)*v;");
8365 verifyFormat("x = (foo *__capability)*v;");
8366
8367 // Check that we handle multiple trailing qualifiers and skip them all to
8368 // determine that the expression is a cast to a pointer type.
8369 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
8370 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
8371 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
8372 StringRef AllQualifiers =
8373 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
8374 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
8375 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
8376 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
8377
8378 // Also check that address-of is not parsed as a binary bitwise-and:
8379 verifyFormat("x = (foo *const)&v;");
8380 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
8381 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
8382
8383 // Check custom qualifiers:
8384 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
8385 CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8386 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
8387 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
8388 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
8389 CustomQualifier);
8390 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
8391 CustomQualifier);
8392
8393 // Check that unknown identifiers result in binary operator parsing:
8394 verifyFormat("x = (foo * __unknown_qualifier) * v;");
8395 verifyFormat("x = (foo * __unknown_qualifier) & v;");
8396 }
8397
TEST_F(FormatTest,UnderstandsSquareAttributes)8398 TEST_F(FormatTest, UnderstandsSquareAttributes) {
8399 verifyFormat("SomeType s [[unused]] (InitValue);");
8400 verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
8401 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
8402 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
8403 verifyFormat("void f() [[deprecated(\"so sorry\")]];");
8404 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8405 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8406 verifyFormat("[[nodiscard]] bool f() { return false; }");
8407 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}");
8408 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}");
8409 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}");
8410
8411 // Make sure we do not mistake attributes for array subscripts.
8412 verifyFormat("int a() {}\n"
8413 "[[unused]] int b() {}\n");
8414 verifyFormat("NSArray *arr;\n"
8415 "arr[[Foo() bar]];");
8416
8417 // On the other hand, we still need to correctly find array subscripts.
8418 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
8419
8420 // Make sure that we do not mistake Objective-C method inside array literals
8421 // as attributes, even if those method names are also keywords.
8422 verifyFormat("@[ [foo bar] ];");
8423 verifyFormat("@[ [NSArray class] ];");
8424 verifyFormat("@[ [foo enum] ];");
8425
8426 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
8427
8428 // Make sure we do not parse attributes as lambda introducers.
8429 FormatStyle MultiLineFunctions = getLLVMStyle();
8430 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8431 verifyFormat("[[unused]] int b() {\n"
8432 " return 42;\n"
8433 "}\n",
8434 MultiLineFunctions);
8435 }
8436
TEST_F(FormatTest,AttributeClass)8437 TEST_F(FormatTest, AttributeClass) {
8438 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
8439 verifyFormat("class S {\n"
8440 " S(S&&) = default;\n"
8441 "};",
8442 Style);
8443 verifyFormat("class [[nodiscard]] S {\n"
8444 " S(S&&) = default;\n"
8445 "};",
8446 Style);
8447 verifyFormat("class __attribute((maybeunused)) S {\n"
8448 " S(S&&) = default;\n"
8449 "};",
8450 Style);
8451 verifyFormat("struct S {\n"
8452 " S(S&&) = default;\n"
8453 "};",
8454 Style);
8455 verifyFormat("struct [[nodiscard]] S {\n"
8456 " S(S&&) = default;\n"
8457 "};",
8458 Style);
8459 }
8460
TEST_F(FormatTest,AttributesAfterMacro)8461 TEST_F(FormatTest, AttributesAfterMacro) {
8462 FormatStyle Style = getLLVMStyle();
8463 verifyFormat("MACRO;\n"
8464 "__attribute__((maybe_unused)) int foo() {\n"
8465 " //...\n"
8466 "}");
8467
8468 verifyFormat("MACRO;\n"
8469 "[[nodiscard]] int foo() {\n"
8470 " //...\n"
8471 "}");
8472
8473 EXPECT_EQ("MACRO\n\n"
8474 "__attribute__((maybe_unused)) int foo() {\n"
8475 " //...\n"
8476 "}",
8477 format("MACRO\n\n"
8478 "__attribute__((maybe_unused)) int foo() {\n"
8479 " //...\n"
8480 "}"));
8481
8482 EXPECT_EQ("MACRO\n\n"
8483 "[[nodiscard]] int foo() {\n"
8484 " //...\n"
8485 "}",
8486 format("MACRO\n\n"
8487 "[[nodiscard]] int foo() {\n"
8488 " //...\n"
8489 "}"));
8490 }
8491
TEST_F(FormatTest,AttributePenaltyBreaking)8492 TEST_F(FormatTest, AttributePenaltyBreaking) {
8493 FormatStyle Style = getLLVMStyle();
8494 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
8495 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8496 Style);
8497 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
8498 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8499 Style);
8500 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
8501 "shared_ptr<ALongTypeName> &C d) {\n}",
8502 Style);
8503 }
8504
TEST_F(FormatTest,UnderstandsEllipsis)8505 TEST_F(FormatTest, UnderstandsEllipsis) {
8506 FormatStyle Style = getLLVMStyle();
8507 verifyFormat("int printf(const char *fmt, ...);");
8508 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
8509 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
8510
8511 verifyFormat("template <int *...PP> a;", Style);
8512
8513 Style.PointerAlignment = FormatStyle::PAS_Left;
8514 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
8515
8516 verifyFormat("template <int*... PP> a;", Style);
8517
8518 Style.PointerAlignment = FormatStyle::PAS_Middle;
8519 verifyFormat("template <int *... PP> a;", Style);
8520 }
8521
TEST_F(FormatTest,AdaptivelyFormatsPointersAndReferences)8522 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
8523 EXPECT_EQ("int *a;\n"
8524 "int *a;\n"
8525 "int *a;",
8526 format("int *a;\n"
8527 "int* a;\n"
8528 "int *a;",
8529 getGoogleStyle()));
8530 EXPECT_EQ("int* a;\n"
8531 "int* a;\n"
8532 "int* a;",
8533 format("int* a;\n"
8534 "int* a;\n"
8535 "int *a;",
8536 getGoogleStyle()));
8537 EXPECT_EQ("int *a;\n"
8538 "int *a;\n"
8539 "int *a;",
8540 format("int *a;\n"
8541 "int * a;\n"
8542 "int * a;",
8543 getGoogleStyle()));
8544 EXPECT_EQ("auto x = [] {\n"
8545 " int *a;\n"
8546 " int *a;\n"
8547 " int *a;\n"
8548 "};",
8549 format("auto x=[]{int *a;\n"
8550 "int * a;\n"
8551 "int * a;};",
8552 getGoogleStyle()));
8553 }
8554
TEST_F(FormatTest,UnderstandsRvalueReferences)8555 TEST_F(FormatTest, UnderstandsRvalueReferences) {
8556 verifyFormat("int f(int &&a) {}");
8557 verifyFormat("int f(int a, char &&b) {}");
8558 verifyFormat("void f() { int &&a = b; }");
8559 verifyGoogleFormat("int f(int a, char&& b) {}");
8560 verifyGoogleFormat("void f() { int&& a = b; }");
8561
8562 verifyIndependentOfContext("A<int &&> a;");
8563 verifyIndependentOfContext("A<int &&, int &&> a;");
8564 verifyGoogleFormat("A<int&&> a;");
8565 verifyGoogleFormat("A<int&&, int&&> a;");
8566
8567 // Not rvalue references:
8568 verifyFormat("template <bool B, bool C> class A {\n"
8569 " static_assert(B && C, \"Something is wrong\");\n"
8570 "};");
8571 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
8572 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
8573 verifyFormat("#define A(a, b) (a && b)");
8574 }
8575
TEST_F(FormatTest,FormatsBinaryOperatorsPrecedingEquals)8576 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
8577 verifyFormat("void f() {\n"
8578 " x[aaaaaaaaa -\n"
8579 " b] = 23;\n"
8580 "}",
8581 getLLVMStyleWithColumns(15));
8582 }
8583
TEST_F(FormatTest,FormatsCasts)8584 TEST_F(FormatTest, FormatsCasts) {
8585 verifyFormat("Type *A = static_cast<Type *>(P);");
8586 verifyFormat("Type *A = (Type *)P;");
8587 verifyFormat("Type *A = (vector<Type *, int *>)P;");
8588 verifyFormat("int a = (int)(2.0f);");
8589 verifyFormat("int a = (int)2.0f;");
8590 verifyFormat("x[(int32)y];");
8591 verifyFormat("x = (int32)y;");
8592 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
8593 verifyFormat("int a = (int)*b;");
8594 verifyFormat("int a = (int)2.0f;");
8595 verifyFormat("int a = (int)~0;");
8596 verifyFormat("int a = (int)++a;");
8597 verifyFormat("int a = (int)sizeof(int);");
8598 verifyFormat("int a = (int)+2;");
8599 verifyFormat("my_int a = (my_int)2.0f;");
8600 verifyFormat("my_int a = (my_int)sizeof(int);");
8601 verifyFormat("return (my_int)aaa;");
8602 verifyFormat("#define x ((int)-1)");
8603 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
8604 verifyFormat("#define p(q) ((int *)&q)");
8605 verifyFormat("fn(a)(b) + 1;");
8606
8607 verifyFormat("void f() { my_int a = (my_int)*b; }");
8608 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
8609 verifyFormat("my_int a = (my_int)~0;");
8610 verifyFormat("my_int a = (my_int)++a;");
8611 verifyFormat("my_int a = (my_int)-2;");
8612 verifyFormat("my_int a = (my_int)1;");
8613 verifyFormat("my_int a = (my_int *)1;");
8614 verifyFormat("my_int a = (const my_int)-1;");
8615 verifyFormat("my_int a = (const my_int *)-1;");
8616 verifyFormat("my_int a = (my_int)(my_int)-1;");
8617 verifyFormat("my_int a = (ns::my_int)-2;");
8618 verifyFormat("case (my_int)ONE:");
8619 verifyFormat("auto x = (X)this;");
8620 // Casts in Obj-C style calls used to not be recognized as such.
8621 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
8622
8623 // FIXME: single value wrapped with paren will be treated as cast.
8624 verifyFormat("void f(int i = (kValue)*kMask) {}");
8625
8626 verifyFormat("{ (void)F; }");
8627
8628 // Don't break after a cast's
8629 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8630 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
8631 " bbbbbbbbbbbbbbbbbbbbbb);");
8632
8633 // These are not casts.
8634 verifyFormat("void f(int *) {}");
8635 verifyFormat("f(foo)->b;");
8636 verifyFormat("f(foo).b;");
8637 verifyFormat("f(foo)(b);");
8638 verifyFormat("f(foo)[b];");
8639 verifyFormat("[](foo) { return 4; }(bar);");
8640 verifyFormat("(*funptr)(foo)[4];");
8641 verifyFormat("funptrs[4](foo)[4];");
8642 verifyFormat("void f(int *);");
8643 verifyFormat("void f(int *) = 0;");
8644 verifyFormat("void f(SmallVector<int>) {}");
8645 verifyFormat("void f(SmallVector<int>);");
8646 verifyFormat("void f(SmallVector<int>) = 0;");
8647 verifyFormat("void f(int i = (kA * kB) & kMask) {}");
8648 verifyFormat("int a = sizeof(int) * b;");
8649 verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
8650 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
8651 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
8652 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
8653
8654 // These are not casts, but at some point were confused with casts.
8655 verifyFormat("virtual void foo(int *) override;");
8656 verifyFormat("virtual void foo(char &) const;");
8657 verifyFormat("virtual void foo(int *a, char *) const;");
8658 verifyFormat("int a = sizeof(int *) + b;");
8659 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
8660 verifyFormat("bool b = f(g<int>) && c;");
8661 verifyFormat("typedef void (*f)(int i) func;");
8662 verifyFormat("void operator++(int) noexcept;");
8663 verifyFormat("void operator++(int &) noexcept;");
8664 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
8665 "&) noexcept;");
8666 verifyFormat(
8667 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
8668 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
8669 verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
8670 verifyFormat("void operator delete(nothrow_t &) noexcept;");
8671 verifyFormat("void operator delete(foo &) noexcept;");
8672 verifyFormat("void operator delete(foo) noexcept;");
8673 verifyFormat("void operator delete(int) noexcept;");
8674 verifyFormat("void operator delete(int &) noexcept;");
8675 verifyFormat("void operator delete(int &) volatile noexcept;");
8676 verifyFormat("void operator delete(int &) const");
8677 verifyFormat("void operator delete(int &) = default");
8678 verifyFormat("void operator delete(int &) = delete");
8679 verifyFormat("void operator delete(int &) [[noreturn]]");
8680 verifyFormat("void operator delete(int &) throw();");
8681 verifyFormat("void operator delete(int &) throw(int);");
8682 verifyFormat("auto operator delete(int &) -> int;");
8683 verifyFormat("auto operator delete(int &) override");
8684 verifyFormat("auto operator delete(int &) final");
8685
8686 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
8687 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8688 // FIXME: The indentation here is not ideal.
8689 verifyFormat(
8690 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8691 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
8692 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
8693 }
8694
TEST_F(FormatTest,FormatsFunctionTypes)8695 TEST_F(FormatTest, FormatsFunctionTypes) {
8696 verifyFormat("A<bool()> a;");
8697 verifyFormat("A<SomeType()> a;");
8698 verifyFormat("A<void (*)(int, std::string)> a;");
8699 verifyFormat("A<void *(int)>;");
8700 verifyFormat("void *(*a)(int *, SomeType *);");
8701 verifyFormat("int (*func)(void *);");
8702 verifyFormat("void f() { int (*func)(void *); }");
8703 verifyFormat("template <class CallbackClass>\n"
8704 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
8705
8706 verifyGoogleFormat("A<void*(int*, SomeType*)>;");
8707 verifyGoogleFormat("void* (*a)(int);");
8708 verifyGoogleFormat(
8709 "template <class CallbackClass>\n"
8710 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
8711
8712 // Other constructs can look somewhat like function types:
8713 verifyFormat("A<sizeof(*x)> a;");
8714 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
8715 verifyFormat("some_var = function(*some_pointer_var)[0];");
8716 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
8717 verifyFormat("int x = f(&h)();");
8718 verifyFormat("returnsFunction(¶m1, ¶m2)(param);");
8719 verifyFormat("std::function<\n"
8720 " LooooooooooongTemplatedType<\n"
8721 " SomeType>*(\n"
8722 " LooooooooooooooooongType type)>\n"
8723 " function;",
8724 getGoogleStyleWithColumns(40));
8725 }
8726
TEST_F(FormatTest,FormatsPointersToArrayTypes)8727 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
8728 verifyFormat("A (*foo_)[6];");
8729 verifyFormat("vector<int> (*foo_)[6];");
8730 }
8731
TEST_F(FormatTest,BreaksLongVariableDeclarations)8732 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
8733 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8734 " LoooooooooooooooooooooooooooooooooooooooongVariable;");
8735 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
8736 " LoooooooooooooooooooooooooooooooooooooooongVariable;");
8737 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8738 " *LoooooooooooooooooooooooooooooooooooooooongVariable;");
8739
8740 // Different ways of ()-initializiation.
8741 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8742 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
8743 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8744 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
8745 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8746 " LoooooooooooooooooooooooooooooooooooooooongVariable({});");
8747 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8748 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
8749
8750 // Lambdas should not confuse the variable declaration heuristic.
8751 verifyFormat("LooooooooooooooooongType\n"
8752 " variable(nullptr, [](A *a) {});",
8753 getLLVMStyleWithColumns(40));
8754 }
8755
TEST_F(FormatTest,BreaksLongDeclarations)8756 TEST_F(FormatTest, BreaksLongDeclarations) {
8757 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
8758 " AnotherNameForTheLongType;");
8759 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
8760 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8761 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8762 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8763 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
8764 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8765 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8766 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8767 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
8768 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8769 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8770 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8771 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8772 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8773 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
8774 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8775 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
8776 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8777 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
8778 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8779 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8780 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
8781 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8782 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
8783 FormatStyle Indented = getLLVMStyle();
8784 Indented.IndentWrappedFunctionNames = true;
8785 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8786 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
8787 Indented);
8788 verifyFormat(
8789 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8790 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8791 Indented);
8792 verifyFormat(
8793 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8794 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8795 Indented);
8796 verifyFormat(
8797 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8798 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8799 Indented);
8800
8801 // FIXME: Without the comment, this breaks after "(".
8802 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n"
8803 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
8804 getGoogleStyle());
8805
8806 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
8807 " int LoooooooooooooooooooongParam2) {}");
8808 verifyFormat(
8809 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
8810 " SourceLocation L, IdentifierIn *II,\n"
8811 " Type *T) {}");
8812 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
8813 "ReallyReaaallyLongFunctionName(\n"
8814 " const std::string &SomeParameter,\n"
8815 " const SomeType<string, SomeOtherTemplateParameter>\n"
8816 " &ReallyReallyLongParameterName,\n"
8817 " const SomeType<string, SomeOtherTemplateParameter>\n"
8818 " &AnotherLongParameterName) {}");
8819 verifyFormat("template <typename A>\n"
8820 "SomeLoooooooooooooooooooooongType<\n"
8821 " typename some_namespace::SomeOtherType<A>::Type>\n"
8822 "Function() {}");
8823
8824 verifyGoogleFormat(
8825 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
8826 " aaaaaaaaaaaaaaaaaaaaaaa;");
8827 verifyGoogleFormat(
8828 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
8829 " SourceLocation L) {}");
8830 verifyGoogleFormat(
8831 "some_namespace::LongReturnType\n"
8832 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
8833 " int first_long_parameter, int second_parameter) {}");
8834
8835 verifyGoogleFormat("template <typename T>\n"
8836 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8837 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
8838 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8839 " int aaaaaaaaaaaaaaaaaaaaaaa);");
8840
8841 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
8842 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8843 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8844 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8845 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8846 " aaaaaaaaaaaaaaaaaaaaaaaa);");
8847 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8848 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
8849 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
8850 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8851
8852 verifyFormat("template <typename T> // Templates on own line.\n"
8853 "static int // Some comment.\n"
8854 "MyFunction(int a);",
8855 getLLVMStyle());
8856 }
8857
TEST_F(FormatTest,FormatsArrays)8858 TEST_F(FormatTest, FormatsArrays) {
8859 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
8860 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
8861 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
8862 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
8863 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
8864 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
8865 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8866 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
8867 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8868 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
8869 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8870 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
8871 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
8872 verifyFormat(
8873 "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
8874 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
8875 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
8876 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
8877 " .aaaaaaaaaaaaaaaaaaaaaa();");
8878
8879 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
8880 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
8881 verifyFormat(
8882 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
8883 " .aaaaaaa[0]\n"
8884 " .aaaaaaaaaaaaaaaaaaaaaa();");
8885 verifyFormat("a[::b::c];");
8886
8887 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
8888
8889 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
8890 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
8891 }
8892
TEST_F(FormatTest,LineStartsWithSpecialCharacter)8893 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
8894 verifyFormat("(a)->b();");
8895 verifyFormat("--a;");
8896 }
8897
TEST_F(FormatTest,HandlesIncludeDirectives)8898 TEST_F(FormatTest, HandlesIncludeDirectives) {
8899 verifyFormat("#include <string>\n"
8900 "#include <a/b/c.h>\n"
8901 "#include \"a/b/string\"\n"
8902 "#include \"string.h\"\n"
8903 "#include \"string.h\"\n"
8904 "#include <a-a>\n"
8905 "#include < path with space >\n"
8906 "#include_next <test.h>"
8907 "#include \"abc.h\" // this is included for ABC\n"
8908 "#include \"some long include\" // with a comment\n"
8909 "#include \"some very long include path\"\n"
8910 "#include <some/very/long/include/path>\n",
8911 getLLVMStyleWithColumns(35));
8912 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\""));
8913 EXPECT_EQ("#include <a>", format("#include<a>"));
8914
8915 verifyFormat("#import <string>");
8916 verifyFormat("#import <a/b/c.h>");
8917 verifyFormat("#import \"a/b/string\"");
8918 verifyFormat("#import \"string.h\"");
8919 verifyFormat("#import \"string.h\"");
8920 verifyFormat("#if __has_include(<strstream>)\n"
8921 "#include <strstream>\n"
8922 "#endif");
8923
8924 verifyFormat("#define MY_IMPORT <a/b>");
8925
8926 verifyFormat("#if __has_include(<a/b>)");
8927 verifyFormat("#if __has_include_next(<a/b>)");
8928 verifyFormat("#define F __has_include(<a/b>)");
8929 verifyFormat("#define F __has_include_next(<a/b>)");
8930
8931 // Protocol buffer definition or missing "#".
8932 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
8933 getLLVMStyleWithColumns(30));
8934
8935 FormatStyle Style = getLLVMStyle();
8936 Style.AlwaysBreakBeforeMultilineStrings = true;
8937 Style.ColumnLimit = 0;
8938 verifyFormat("#import \"abc.h\"", Style);
8939
8940 // But 'import' might also be a regular C++ namespace.
8941 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8942 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8943 }
8944
8945 //===----------------------------------------------------------------------===//
8946 // Error recovery tests.
8947 //===----------------------------------------------------------------------===//
8948
TEST_F(FormatTest,IncompleteParameterLists)8949 TEST_F(FormatTest, IncompleteParameterLists) {
8950 FormatStyle NoBinPacking = getLLVMStyle();
8951 NoBinPacking.BinPackParameters = false;
8952 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
8953 " double *min_x,\n"
8954 " double *max_x,\n"
8955 " double *min_y,\n"
8956 " double *max_y,\n"
8957 " double *min_z,\n"
8958 " double *max_z, ) {}",
8959 NoBinPacking);
8960 }
8961
TEST_F(FormatTest,IncorrectCodeTrailingStuff)8962 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
8963 verifyFormat("void f() { return; }\n42");
8964 verifyFormat("void f() {\n"
8965 " if (0)\n"
8966 " return;\n"
8967 "}\n"
8968 "42");
8969 verifyFormat("void f() { return }\n42");
8970 verifyFormat("void f() {\n"
8971 " if (0)\n"
8972 " return\n"
8973 "}\n"
8974 "42");
8975 }
8976
TEST_F(FormatTest,IncorrectCodeMissingSemicolon)8977 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
8978 EXPECT_EQ("void f() { return }", format("void f ( ) { return }"));
8979 EXPECT_EQ("void f() {\n"
8980 " if (a)\n"
8981 " return\n"
8982 "}",
8983 format("void f ( ) { if ( a ) return }"));
8984 EXPECT_EQ("namespace N {\n"
8985 "void f()\n"
8986 "}",
8987 format("namespace N { void f() }"));
8988 EXPECT_EQ("namespace N {\n"
8989 "void f() {}\n"
8990 "void g()\n"
8991 "} // namespace N",
8992 format("namespace N { void f( ) { } void g( ) }"));
8993 }
8994
TEST_F(FormatTest,IndentationWithinColumnLimitNotPossible)8995 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
8996 verifyFormat("int aaaaaaaa =\n"
8997 " // Overlylongcomment\n"
8998 " b;",
8999 getLLVMStyleWithColumns(20));
9000 verifyFormat("function(\n"
9001 " ShortArgument,\n"
9002 " LoooooooooooongArgument);\n",
9003 getLLVMStyleWithColumns(20));
9004 }
9005
TEST_F(FormatTest,IncorrectAccessSpecifier)9006 TEST_F(FormatTest, IncorrectAccessSpecifier) {
9007 verifyFormat("public:");
9008 verifyFormat("class A {\n"
9009 "public\n"
9010 " void f() {}\n"
9011 "};");
9012 verifyFormat("public\n"
9013 "int qwerty;");
9014 verifyFormat("public\n"
9015 "B {}");
9016 verifyFormat("public\n"
9017 "{}");
9018 verifyFormat("public\n"
9019 "B { int x; }");
9020 }
9021
TEST_F(FormatTest,IncorrectCodeUnbalancedBraces)9022 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
9023 verifyFormat("{");
9024 verifyFormat("#})");
9025 verifyNoCrash("(/**/[:!] ?[).");
9026 }
9027
TEST_F(FormatTest,IncorrectUnbalancedBracesInMacrosWithUnicode)9028 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
9029 // Found by oss-fuzz:
9030 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
9031 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9032 Style.ColumnLimit = 60;
9033 verifyNoCrash(
9034 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
9035 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
9036 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
9037 Style);
9038 }
9039
TEST_F(FormatTest,IncorrectCodeDoNoWhile)9040 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
9041 verifyFormat("do {\n}");
9042 verifyFormat("do {\n}\n"
9043 "f();");
9044 verifyFormat("do {\n}\n"
9045 "wheeee(fun);");
9046 verifyFormat("do {\n"
9047 " f();\n"
9048 "}");
9049 }
9050
TEST_F(FormatTest,IncorrectCodeMissingParens)9051 TEST_F(FormatTest, IncorrectCodeMissingParens) {
9052 verifyFormat("if {\n foo;\n foo();\n}");
9053 verifyFormat("switch {\n foo;\n foo();\n}");
9054 verifyIncompleteFormat("for {\n foo;\n foo();\n}");
9055 verifyFormat("while {\n foo;\n foo();\n}");
9056 verifyFormat("do {\n foo;\n foo();\n} while;");
9057 }
9058
TEST_F(FormatTest,DoesNotTouchUnwrappedLinesWithErrors)9059 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
9060 verifyIncompleteFormat("namespace {\n"
9061 "class Foo { Foo (\n"
9062 "};\n"
9063 "} // namespace");
9064 }
9065
TEST_F(FormatTest,IncorrectCodeErrorDetection)9066 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
9067 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n"));
9068 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n"));
9069 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n"));
9070 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n"));
9071
9072 EXPECT_EQ("{\n"
9073 " {\n"
9074 " breakme(\n"
9075 " qwe);\n"
9076 " }\n",
9077 format("{\n"
9078 " {\n"
9079 " breakme(qwe);\n"
9080 "}\n",
9081 getLLVMStyleWithColumns(10)));
9082 }
9083
TEST_F(FormatTest,LayoutCallsInsideBraceInitializers)9084 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
9085 verifyFormat("int x = {\n"
9086 " avariable,\n"
9087 " b(alongervariable)};",
9088 getLLVMStyleWithColumns(25));
9089 }
9090
TEST_F(FormatTest,LayoutBraceInitializersInReturnStatement)9091 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
9092 verifyFormat("return (a)(b){1, 2, 3};");
9093 }
9094
TEST_F(FormatTest,LayoutCxx11BraceInitializers)9095 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
9096 verifyFormat("vector<int> x{1, 2, 3, 4};");
9097 verifyFormat("vector<int> x{\n"
9098 " 1,\n"
9099 " 2,\n"
9100 " 3,\n"
9101 " 4,\n"
9102 "};");
9103 verifyFormat("vector<T> x{{}, {}, {}, {}};");
9104 verifyFormat("f({1, 2});");
9105 verifyFormat("auto v = Foo{-1};");
9106 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
9107 verifyFormat("Class::Class : member{1, 2, 3} {}");
9108 verifyFormat("new vector<int>{1, 2, 3};");
9109 verifyFormat("new int[3]{1, 2, 3};");
9110 verifyFormat("new int{1};");
9111 verifyFormat("return {arg1, arg2};");
9112 verifyFormat("return {arg1, SomeType{parameter}};");
9113 verifyFormat("int count = set<int>{f(), g(), h()}.size();");
9114 verifyFormat("new T{arg1, arg2};");
9115 verifyFormat("f(MyMap[{composite, key}]);");
9116 verifyFormat("class Class {\n"
9117 " T member = {arg1, arg2};\n"
9118 "};");
9119 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
9120 verifyFormat("const struct A a = {.a = 1, .b = 2};");
9121 verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
9122 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
9123 verifyFormat("int a = std::is_integral<int>{} + 0;");
9124
9125 verifyFormat("int foo(int i) { return fo1{}(i); }");
9126 verifyFormat("int foo(int i) { return fo1{}(i); }");
9127 verifyFormat("auto i = decltype(x){};");
9128 verifyFormat("auto i = typeof(x){};");
9129 verifyFormat("auto i = _Atomic(x){};");
9130 verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
9131 verifyFormat("Node n{1, Node{1000}, //\n"
9132 " 2};");
9133 verifyFormat("Aaaa aaaaaaa{\n"
9134 " {\n"
9135 " aaaa,\n"
9136 " },\n"
9137 "};");
9138 verifyFormat("class C : public D {\n"
9139 " SomeClass SC{2};\n"
9140 "};");
9141 verifyFormat("class C : public A {\n"
9142 " class D : public B {\n"
9143 " void f() { int i{2}; }\n"
9144 " };\n"
9145 "};");
9146 verifyFormat("#define A {a, a},");
9147
9148 // Avoid breaking between equal sign and opening brace
9149 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
9150 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
9151 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
9152 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
9153 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
9154 " {\"ccccccccccccccccccccc\", 2}};",
9155 AvoidBreakingFirstArgument);
9156
9157 // Binpacking only if there is no trailing comma
9158 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
9159 " cccccccccc, dddddddddd};",
9160 getLLVMStyleWithColumns(50));
9161 verifyFormat("const Aaaaaa aaaaa = {\n"
9162 " aaaaaaaaaaa,\n"
9163 " bbbbbbbbbbb,\n"
9164 " ccccccccccc,\n"
9165 " ddddddddddd,\n"
9166 "};",
9167 getLLVMStyleWithColumns(50));
9168
9169 // Cases where distinguising braced lists and blocks is hard.
9170 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
9171 verifyFormat("void f() {\n"
9172 " return; // comment\n"
9173 "}\n"
9174 "SomeType t;");
9175 verifyFormat("void f() {\n"
9176 " if (a) {\n"
9177 " f();\n"
9178 " }\n"
9179 "}\n"
9180 "SomeType t;");
9181
9182 // In combination with BinPackArguments = false.
9183 FormatStyle NoBinPacking = getLLVMStyle();
9184 NoBinPacking.BinPackArguments = false;
9185 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
9186 " bbbbb,\n"
9187 " ccccc,\n"
9188 " ddddd,\n"
9189 " eeeee,\n"
9190 " ffffff,\n"
9191 " ggggg,\n"
9192 " hhhhhh,\n"
9193 " iiiiii,\n"
9194 " jjjjjj,\n"
9195 " kkkkkk};",
9196 NoBinPacking);
9197 verifyFormat("const Aaaaaa aaaaa = {\n"
9198 " aaaaa,\n"
9199 " bbbbb,\n"
9200 " ccccc,\n"
9201 " ddddd,\n"
9202 " eeeee,\n"
9203 " ffffff,\n"
9204 " ggggg,\n"
9205 " hhhhhh,\n"
9206 " iiiiii,\n"
9207 " jjjjjj,\n"
9208 " kkkkkk,\n"
9209 "};",
9210 NoBinPacking);
9211 verifyFormat(
9212 "const Aaaaaa aaaaa = {\n"
9213 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n"
9214 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n"
9215 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
9216 "};",
9217 NoBinPacking);
9218
9219 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9220 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
9221 " CDDDP83848_BMCR_REGISTER,\n"
9222 " CDDDP83848_BMSR_REGISTER,\n"
9223 " CDDDP83848_RBR_REGISTER};",
9224 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
9225 " CDDDP83848_BMSR_REGISTER,\n"
9226 " CDDDP83848_RBR_REGISTER};",
9227 NoBinPacking));
9228
9229 // FIXME: The alignment of these trailing comments might be bad. Then again,
9230 // this might be utterly useless in real code.
9231 verifyFormat("Constructor::Constructor()\n"
9232 " : some_value{ //\n"
9233 " aaaaaaa, //\n"
9234 " bbbbbbb} {}");
9235
9236 // In braced lists, the first comment is always assumed to belong to the
9237 // first element. Thus, it can be moved to the next or previous line as
9238 // appropriate.
9239 EXPECT_EQ("function({// First element:\n"
9240 " 1,\n"
9241 " // Second element:\n"
9242 " 2});",
9243 format("function({\n"
9244 " // First element:\n"
9245 " 1,\n"
9246 " // Second element:\n"
9247 " 2});"));
9248 EXPECT_EQ("std::vector<int> MyNumbers{\n"
9249 " // First element:\n"
9250 " 1,\n"
9251 " // Second element:\n"
9252 " 2};",
9253 format("std::vector<int> MyNumbers{// First element:\n"
9254 " 1,\n"
9255 " // Second element:\n"
9256 " 2};",
9257 getLLVMStyleWithColumns(30)));
9258 // A trailing comma should still lead to an enforced line break and no
9259 // binpacking.
9260 EXPECT_EQ("vector<int> SomeVector = {\n"
9261 " // aaa\n"
9262 " 1,\n"
9263 " 2,\n"
9264 "};",
9265 format("vector<int> SomeVector = { // aaa\n"
9266 " 1, 2, };"));
9267
9268 // C++11 brace initializer list l-braces should not be treated any differently
9269 // when breaking before lambda bodies is enabled
9270 FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
9271 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
9272 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
9273 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
9274 verifyFormat(
9275 "std::runtime_error{\n"
9276 " \"Long string which will force a break onto the next line...\"};",
9277 BreakBeforeLambdaBody);
9278
9279 FormatStyle ExtraSpaces = getLLVMStyle();
9280 ExtraSpaces.Cpp11BracedListStyle = false;
9281 ExtraSpaces.ColumnLimit = 75;
9282 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
9283 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
9284 verifyFormat("f({ 1, 2 });", ExtraSpaces);
9285 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
9286 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
9287 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
9288 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
9289 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
9290 verifyFormat("return { arg1, arg2 };", ExtraSpaces);
9291 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
9292 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
9293 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
9294 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
9295 verifyFormat("class Class {\n"
9296 " T member = { arg1, arg2 };\n"
9297 "};",
9298 ExtraSpaces);
9299 verifyFormat(
9300 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9301 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
9302 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
9303 " bbbbbbbbbbbbbbbbbbbb, bbbbb };",
9304 ExtraSpaces);
9305 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
9306 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
9307 ExtraSpaces);
9308 verifyFormat(
9309 "someFunction(OtherParam,\n"
9310 " BracedList{ // comment 1 (Forcing interesting break)\n"
9311 " param1, param2,\n"
9312 " // comment 2\n"
9313 " param3, param4 });",
9314 ExtraSpaces);
9315 verifyFormat(
9316 "std::this_thread::sleep_for(\n"
9317 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
9318 ExtraSpaces);
9319 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
9320 " aaaaaaa,\n"
9321 " aaaaaaaaaa,\n"
9322 " aaaaa,\n"
9323 " aaaaaaaaaaaaaaa,\n"
9324 " aaa,\n"
9325 " aaaaaaaaaa,\n"
9326 " a,\n"
9327 " aaaaaaaaaaaaaaaaaaaaa,\n"
9328 " aaaaaaaaaaaa,\n"
9329 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
9330 " aaaaaaa,\n"
9331 " a};");
9332 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
9333 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
9334 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
9335
9336 // Avoid breaking between initializer/equal sign and opening brace
9337 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
9338 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
9339 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
9340 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
9341 " { \"ccccccccccccccccccccc\", 2 }\n"
9342 "};",
9343 ExtraSpaces);
9344 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
9345 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
9346 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
9347 " { \"ccccccccccccccccccccc\", 2 }\n"
9348 "};",
9349 ExtraSpaces);
9350
9351 FormatStyle SpaceBeforeBrace = getLLVMStyle();
9352 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
9353 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
9354 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
9355
9356 FormatStyle SpaceBetweenBraces = getLLVMStyle();
9357 SpaceBetweenBraces.SpacesInAngles = true;
9358 SpaceBetweenBraces.SpacesInParentheses = true;
9359 SpaceBetweenBraces.SpacesInSquareBrackets = true;
9360 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
9361 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
9362 verifyFormat("vector< int > x{ // comment 1\n"
9363 " 1, 2, 3, 4 };",
9364 SpaceBetweenBraces);
9365 SpaceBetweenBraces.ColumnLimit = 20;
9366 EXPECT_EQ("vector< int > x{\n"
9367 " 1, 2, 3, 4 };",
9368 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
9369 SpaceBetweenBraces.ColumnLimit = 24;
9370 EXPECT_EQ("vector< int > x{ 1, 2,\n"
9371 " 3, 4 };",
9372 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
9373 EXPECT_EQ("vector< int > x{\n"
9374 " 1,\n"
9375 " 2,\n"
9376 " 3,\n"
9377 " 4,\n"
9378 "};",
9379 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
9380 verifyFormat("vector< int > x{};", SpaceBetweenBraces);
9381 SpaceBetweenBraces.SpaceInEmptyParentheses = true;
9382 verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
9383 }
9384
TEST_F(FormatTest,FormatSpacesInAngles)9385 TEST_F(FormatTest, FormatSpacesInAngles) {
9386 FormatStyle SpaceInAngles = getLLVMStyle();
9387 SpaceInAngles.SpacesInAngles = true;
9388 verifyFormat("vector< ::std::string > x1;", SpaceInAngles);
9389 verifyFormat("Foo< int, Bar > x2;", SpaceInAngles);
9390 verifyFormat("Foo< ::int, ::Bar > x3;", SpaceInAngles);
9391
9392 SpaceInAngles.SpacesInAngles = false;
9393 verifyFormat("vector<::std::string> x4;", SpaceInAngles);
9394 verifyFormat("vector<int> x5;", SpaceInAngles);
9395 verifyFormat("Foo<int, Bar> x6;", SpaceInAngles);
9396 verifyFormat("Foo<::int, ::Bar> x7;", SpaceInAngles);
9397 }
9398
TEST_F(FormatTest,FormatsBracedListsInColumnLayout)9399 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
9400 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9401 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9402 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9403 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9404 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9405 " 1, 22, 333, 4444, 55555, 666666, 7777777};");
9406 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
9407 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9408 " 1, 22, 333, 4444, 55555, //\n"
9409 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9410 " 1, 22, 333, 4444, 55555, 666666, 7777777};");
9411 verifyFormat(
9412 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9413 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9414 " 1, 22, 333, 4444, 55555, 666666, // comment\n"
9415 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
9416 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
9417 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n"
9418 " 7777777};");
9419 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
9420 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
9421 " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
9422 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
9423 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
9424 " // Separating comment.\n"
9425 " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
9426 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
9427 " // Leading comment\n"
9428 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
9429 " X86::R8, X86::R9, X86::R10, X86::R11, 0};");
9430 verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
9431 " 1, 1, 1, 1};",
9432 getLLVMStyleWithColumns(39));
9433 verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
9434 " 1, 1, 1, 1};",
9435 getLLVMStyleWithColumns(38));
9436 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
9437 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
9438 getLLVMStyleWithColumns(43));
9439 verifyFormat(
9440 "static unsigned SomeValues[10][3] = {\n"
9441 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n"
9442 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
9443 verifyFormat("static auto fields = new vector<string>{\n"
9444 " \"aaaaaaaaaaaaa\",\n"
9445 " \"aaaaaaaaaaaaa\",\n"
9446 " \"aaaaaaaaaaaa\",\n"
9447 " \"aaaaaaaaaaaaaa\",\n"
9448 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
9449 " \"aaaaaaaaaaaa\",\n"
9450 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
9451 "};");
9452 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
9453 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
9454 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
9455 " 3, cccccccccccccccccccccc};",
9456 getLLVMStyleWithColumns(60));
9457
9458 // Trailing commas.
9459 verifyFormat("vector<int> x = {\n"
9460 " 1, 1, 1, 1, 1, 1, 1, 1,\n"
9461 "};",
9462 getLLVMStyleWithColumns(39));
9463 verifyFormat("vector<int> x = {\n"
9464 " 1, 1, 1, 1, 1, 1, 1, 1, //\n"
9465 "};",
9466 getLLVMStyleWithColumns(39));
9467 verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
9468 " 1, 1, 1, 1,\n"
9469 " /**/ /**/};",
9470 getLLVMStyleWithColumns(39));
9471
9472 // Trailing comment in the first line.
9473 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n"
9474 " 1111111111, 2222222222, 33333333333, 4444444444, //\n"
9475 " 111111111, 222222222, 3333333333, 444444444, //\n"
9476 " 11111111, 22222222, 333333333, 44444444};");
9477 // Trailing comment in the last line.
9478 verifyFormat("int aaaaa[] = {\n"
9479 " 1, 2, 3, // comment\n"
9480 " 4, 5, 6 // comment\n"
9481 "};");
9482
9483 // With nested lists, we should either format one item per line or all nested
9484 // lists one on line.
9485 // FIXME: For some nested lists, we can do better.
9486 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
9487 " {aaaaaaaaaaaaaaaaaaa},\n"
9488 " {aaaaaaaaaaaaaaaaaaaaa},\n"
9489 " {aaaaaaaaaaaaaaaaa}};",
9490 getLLVMStyleWithColumns(60));
9491 verifyFormat(
9492 "SomeStruct my_struct_array = {\n"
9493 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
9494 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
9495 " {aaa, aaa},\n"
9496 " {aaa, aaa},\n"
9497 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
9498 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
9499 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
9500
9501 // No column layout should be used here.
9502 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
9503 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
9504
9505 verifyNoCrash("a<,");
9506
9507 // No braced initializer here.
9508 verifyFormat("void f() {\n"
9509 " struct Dummy {};\n"
9510 " f(v);\n"
9511 "}");
9512
9513 // Long lists should be formatted in columns even if they are nested.
9514 verifyFormat(
9515 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9516 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9517 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9518 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9519 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9520 " 1, 22, 333, 4444, 55555, 666666, 7777777});");
9521
9522 // Allow "single-column" layout even if that violates the column limit. There
9523 // isn't going to be a better way.
9524 verifyFormat("std::vector<int> a = {\n"
9525 " aaaaaaaa,\n"
9526 " aaaaaaaa,\n"
9527 " aaaaaaaa,\n"
9528 " aaaaaaaa,\n"
9529 " aaaaaaaaaa,\n"
9530 " aaaaaaaa,\n"
9531 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
9532 getLLVMStyleWithColumns(30));
9533 verifyFormat("vector<int> aaaa = {\n"
9534 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9535 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9536 " aaaaaa.aaaaaaa,\n"
9537 " aaaaaa.aaaaaaa,\n"
9538 " aaaaaa.aaaaaaa,\n"
9539 " aaaaaa.aaaaaaa,\n"
9540 "};");
9541
9542 // Don't create hanging lists.
9543 verifyFormat("someFunction(Param, {List1, List2,\n"
9544 " List3});",
9545 getLLVMStyleWithColumns(35));
9546 verifyFormat("someFunction(Param, Param,\n"
9547 " {List1, List2,\n"
9548 " List3});",
9549 getLLVMStyleWithColumns(35));
9550 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
9551 " aaaaaaaaaaaaaaaaaaaaaaa);");
9552 }
9553
TEST_F(FormatTest,PullTrivialFunctionDefinitionsIntoSingleLine)9554 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
9555 FormatStyle DoNotMerge = getLLVMStyle();
9556 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9557
9558 verifyFormat("void f() { return 42; }");
9559 verifyFormat("void f() {\n"
9560 " return 42;\n"
9561 "}",
9562 DoNotMerge);
9563 verifyFormat("void f() {\n"
9564 " // Comment\n"
9565 "}");
9566 verifyFormat("{\n"
9567 "#error {\n"
9568 " int a;\n"
9569 "}");
9570 verifyFormat("{\n"
9571 " int a;\n"
9572 "#error {\n"
9573 "}");
9574 verifyFormat("void f() {} // comment");
9575 verifyFormat("void f() { int a; } // comment");
9576 verifyFormat("void f() {\n"
9577 "} // comment",
9578 DoNotMerge);
9579 verifyFormat("void f() {\n"
9580 " int a;\n"
9581 "} // comment",
9582 DoNotMerge);
9583 verifyFormat("void f() {\n"
9584 "} // comment",
9585 getLLVMStyleWithColumns(15));
9586
9587 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
9588 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22));
9589
9590 verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
9591 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
9592 verifyFormat("class C {\n"
9593 " C()\n"
9594 " : iiiiiiii(nullptr),\n"
9595 " kkkkkkk(nullptr),\n"
9596 " mmmmmmm(nullptr),\n"
9597 " nnnnnnn(nullptr) {}\n"
9598 "};",
9599 getGoogleStyle());
9600
9601 FormatStyle NoColumnLimit = getLLVMStyle();
9602 NoColumnLimit.ColumnLimit = 0;
9603 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
9604 EXPECT_EQ("class C {\n"
9605 " A() : b(0) {}\n"
9606 "};",
9607 format("class C{A():b(0){}};", NoColumnLimit));
9608 EXPECT_EQ("A()\n"
9609 " : b(0) {\n"
9610 "}",
9611 format("A()\n:b(0)\n{\n}", NoColumnLimit));
9612
9613 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
9614 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
9615 FormatStyle::SFS_None;
9616 EXPECT_EQ("A()\n"
9617 " : b(0) {\n"
9618 "}",
9619 format("A():b(0){}", DoNotMergeNoColumnLimit));
9620 EXPECT_EQ("A()\n"
9621 " : b(0) {\n"
9622 "}",
9623 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
9624
9625 verifyFormat("#define A \\\n"
9626 " void f() { \\\n"
9627 " int i; \\\n"
9628 " }",
9629 getLLVMStyleWithColumns(20));
9630 verifyFormat("#define A \\\n"
9631 " void f() { int i; }",
9632 getLLVMStyleWithColumns(21));
9633 verifyFormat("#define A \\\n"
9634 " void f() { \\\n"
9635 " int i; \\\n"
9636 " } \\\n"
9637 " int j;",
9638 getLLVMStyleWithColumns(22));
9639 verifyFormat("#define A \\\n"
9640 " void f() { int i; } \\\n"
9641 " int j;",
9642 getLLVMStyleWithColumns(23));
9643 }
9644
TEST_F(FormatTest,PullEmptyFunctionDefinitionsIntoSingleLine)9645 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
9646 FormatStyle MergeEmptyOnly = getLLVMStyle();
9647 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
9648 verifyFormat("class C {\n"
9649 " int f() {}\n"
9650 "};",
9651 MergeEmptyOnly);
9652 verifyFormat("class C {\n"
9653 " int f() {\n"
9654 " return 42;\n"
9655 " }\n"
9656 "};",
9657 MergeEmptyOnly);
9658 verifyFormat("int f() {}", MergeEmptyOnly);
9659 verifyFormat("int f() {\n"
9660 " return 42;\n"
9661 "}",
9662 MergeEmptyOnly);
9663
9664 // Also verify behavior when BraceWrapping.AfterFunction = true
9665 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
9666 MergeEmptyOnly.BraceWrapping.AfterFunction = true;
9667 verifyFormat("int f() {}", MergeEmptyOnly);
9668 verifyFormat("class C {\n"
9669 " int f() {}\n"
9670 "};",
9671 MergeEmptyOnly);
9672 }
9673
TEST_F(FormatTest,PullInlineFunctionDefinitionsIntoSingleLine)9674 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
9675 FormatStyle MergeInlineOnly = getLLVMStyle();
9676 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
9677 verifyFormat("class C {\n"
9678 " int f() { return 42; }\n"
9679 "};",
9680 MergeInlineOnly);
9681 verifyFormat("int f() {\n"
9682 " return 42;\n"
9683 "}",
9684 MergeInlineOnly);
9685
9686 // SFS_Inline implies SFS_Empty
9687 verifyFormat("class C {\n"
9688 " int f() {}\n"
9689 "};",
9690 MergeInlineOnly);
9691 verifyFormat("int f() {}", MergeInlineOnly);
9692
9693 // Also verify behavior when BraceWrapping.AfterFunction = true
9694 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
9695 MergeInlineOnly.BraceWrapping.AfterFunction = true;
9696 verifyFormat("class C {\n"
9697 " int f() { return 42; }\n"
9698 "};",
9699 MergeInlineOnly);
9700 verifyFormat("int f()\n"
9701 "{\n"
9702 " return 42;\n"
9703 "}",
9704 MergeInlineOnly);
9705
9706 // SFS_Inline implies SFS_Empty
9707 verifyFormat("int f() {}", MergeInlineOnly);
9708 verifyFormat("class C {\n"
9709 " int f() {}\n"
9710 "};",
9711 MergeInlineOnly);
9712 }
9713
TEST_F(FormatTest,PullInlineOnlyFunctionDefinitionsIntoSingleLine)9714 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
9715 FormatStyle MergeInlineOnly = getLLVMStyle();
9716 MergeInlineOnly.AllowShortFunctionsOnASingleLine =
9717 FormatStyle::SFS_InlineOnly;
9718 verifyFormat("class C {\n"
9719 " int f() { return 42; }\n"
9720 "};",
9721 MergeInlineOnly);
9722 verifyFormat("int f() {\n"
9723 " return 42;\n"
9724 "}",
9725 MergeInlineOnly);
9726
9727 // SFS_InlineOnly does not imply SFS_Empty
9728 verifyFormat("class C {\n"
9729 " int f() {}\n"
9730 "};",
9731 MergeInlineOnly);
9732 verifyFormat("int f() {\n"
9733 "}",
9734 MergeInlineOnly);
9735
9736 // Also verify behavior when BraceWrapping.AfterFunction = true
9737 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
9738 MergeInlineOnly.BraceWrapping.AfterFunction = true;
9739 verifyFormat("class C {\n"
9740 " int f() { return 42; }\n"
9741 "};",
9742 MergeInlineOnly);
9743 verifyFormat("int f()\n"
9744 "{\n"
9745 " return 42;\n"
9746 "}",
9747 MergeInlineOnly);
9748
9749 // SFS_InlineOnly does not imply SFS_Empty
9750 verifyFormat("int f()\n"
9751 "{\n"
9752 "}",
9753 MergeInlineOnly);
9754 verifyFormat("class C {\n"
9755 " int f() {}\n"
9756 "};",
9757 MergeInlineOnly);
9758 }
9759
TEST_F(FormatTest,SplitEmptyFunction)9760 TEST_F(FormatTest, SplitEmptyFunction) {
9761 FormatStyle Style = getLLVMStyle();
9762 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9763 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9764 Style.BraceWrapping.AfterFunction = true;
9765 Style.BraceWrapping.SplitEmptyFunction = false;
9766 Style.ColumnLimit = 40;
9767
9768 verifyFormat("int f()\n"
9769 "{}",
9770 Style);
9771 verifyFormat("int f()\n"
9772 "{\n"
9773 " return 42;\n"
9774 "}",
9775 Style);
9776 verifyFormat("int f()\n"
9777 "{\n"
9778 " // some comment\n"
9779 "}",
9780 Style);
9781
9782 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
9783 verifyFormat("int f() {}", Style);
9784 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
9785 "{}",
9786 Style);
9787 verifyFormat("int f()\n"
9788 "{\n"
9789 " return 0;\n"
9790 "}",
9791 Style);
9792
9793 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
9794 verifyFormat("class Foo {\n"
9795 " int f() {}\n"
9796 "};\n",
9797 Style);
9798 verifyFormat("class Foo {\n"
9799 " int f() { return 0; }\n"
9800 "};\n",
9801 Style);
9802 verifyFormat("class Foo {\n"
9803 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
9804 " {}\n"
9805 "};\n",
9806 Style);
9807 verifyFormat("class Foo {\n"
9808 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
9809 " {\n"
9810 " return 0;\n"
9811 " }\n"
9812 "};\n",
9813 Style);
9814
9815 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
9816 verifyFormat("int f() {}", Style);
9817 verifyFormat("int f() { return 0; }", Style);
9818 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
9819 "{}",
9820 Style);
9821 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
9822 "{\n"
9823 " return 0;\n"
9824 "}",
9825 Style);
9826 }
TEST_F(FormatTest,KeepShortFunctionAfterPPElse)9827 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
9828 FormatStyle Style = getLLVMStyle();
9829 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
9830 verifyFormat("#ifdef A\n"
9831 "int f() {}\n"
9832 "#else\n"
9833 "int g() {}\n"
9834 "#endif",
9835 Style);
9836 }
9837
TEST_F(FormatTest,SplitEmptyClass)9838 TEST_F(FormatTest, SplitEmptyClass) {
9839 FormatStyle Style = getLLVMStyle();
9840 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9841 Style.BraceWrapping.AfterClass = true;
9842 Style.BraceWrapping.SplitEmptyRecord = false;
9843
9844 verifyFormat("class Foo\n"
9845 "{};",
9846 Style);
9847 verifyFormat("/* something */ class Foo\n"
9848 "{};",
9849 Style);
9850 verifyFormat("template <typename X> class Foo\n"
9851 "{};",
9852 Style);
9853 verifyFormat("class Foo\n"
9854 "{\n"
9855 " Foo();\n"
9856 "};",
9857 Style);
9858 verifyFormat("typedef class Foo\n"
9859 "{\n"
9860 "} Foo_t;",
9861 Style);
9862 }
9863
TEST_F(FormatTest,SplitEmptyStruct)9864 TEST_F(FormatTest, SplitEmptyStruct) {
9865 FormatStyle Style = getLLVMStyle();
9866 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9867 Style.BraceWrapping.AfterStruct = true;
9868 Style.BraceWrapping.SplitEmptyRecord = false;
9869
9870 verifyFormat("struct Foo\n"
9871 "{};",
9872 Style);
9873 verifyFormat("/* something */ struct Foo\n"
9874 "{};",
9875 Style);
9876 verifyFormat("template <typename X> struct Foo\n"
9877 "{};",
9878 Style);
9879 verifyFormat("struct Foo\n"
9880 "{\n"
9881 " Foo();\n"
9882 "};",
9883 Style);
9884 verifyFormat("typedef struct Foo\n"
9885 "{\n"
9886 "} Foo_t;",
9887 Style);
9888 // typedef struct Bar {} Bar_t;
9889 }
9890
TEST_F(FormatTest,SplitEmptyUnion)9891 TEST_F(FormatTest, SplitEmptyUnion) {
9892 FormatStyle Style = getLLVMStyle();
9893 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9894 Style.BraceWrapping.AfterUnion = true;
9895 Style.BraceWrapping.SplitEmptyRecord = false;
9896
9897 verifyFormat("union Foo\n"
9898 "{};",
9899 Style);
9900 verifyFormat("/* something */ union Foo\n"
9901 "{};",
9902 Style);
9903 verifyFormat("union Foo\n"
9904 "{\n"
9905 " A,\n"
9906 "};",
9907 Style);
9908 verifyFormat("typedef union Foo\n"
9909 "{\n"
9910 "} Foo_t;",
9911 Style);
9912 }
9913
TEST_F(FormatTest,SplitEmptyNamespace)9914 TEST_F(FormatTest, SplitEmptyNamespace) {
9915 FormatStyle Style = getLLVMStyle();
9916 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9917 Style.BraceWrapping.AfterNamespace = true;
9918 Style.BraceWrapping.SplitEmptyNamespace = false;
9919
9920 verifyFormat("namespace Foo\n"
9921 "{};",
9922 Style);
9923 verifyFormat("/* something */ namespace Foo\n"
9924 "{};",
9925 Style);
9926 verifyFormat("inline namespace Foo\n"
9927 "{};",
9928 Style);
9929 verifyFormat("/* something */ inline namespace Foo\n"
9930 "{};",
9931 Style);
9932 verifyFormat("export namespace Foo\n"
9933 "{};",
9934 Style);
9935 verifyFormat("namespace Foo\n"
9936 "{\n"
9937 "void Bar();\n"
9938 "};",
9939 Style);
9940 }
9941
TEST_F(FormatTest,NeverMergeShortRecords)9942 TEST_F(FormatTest, NeverMergeShortRecords) {
9943 FormatStyle Style = getLLVMStyle();
9944
9945 verifyFormat("class Foo {\n"
9946 " Foo();\n"
9947 "};",
9948 Style);
9949 verifyFormat("typedef class Foo {\n"
9950 " Foo();\n"
9951 "} Foo_t;",
9952 Style);
9953 verifyFormat("struct Foo {\n"
9954 " Foo();\n"
9955 "};",
9956 Style);
9957 verifyFormat("typedef struct Foo {\n"
9958 " Foo();\n"
9959 "} Foo_t;",
9960 Style);
9961 verifyFormat("union Foo {\n"
9962 " A,\n"
9963 "};",
9964 Style);
9965 verifyFormat("typedef union Foo {\n"
9966 " A,\n"
9967 "} Foo_t;",
9968 Style);
9969 verifyFormat("namespace Foo {\n"
9970 "void Bar();\n"
9971 "};",
9972 Style);
9973
9974 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9975 Style.BraceWrapping.AfterClass = true;
9976 Style.BraceWrapping.AfterStruct = true;
9977 Style.BraceWrapping.AfterUnion = true;
9978 Style.BraceWrapping.AfterNamespace = true;
9979 verifyFormat("class Foo\n"
9980 "{\n"
9981 " Foo();\n"
9982 "};",
9983 Style);
9984 verifyFormat("typedef class Foo\n"
9985 "{\n"
9986 " Foo();\n"
9987 "} Foo_t;",
9988 Style);
9989 verifyFormat("struct Foo\n"
9990 "{\n"
9991 " Foo();\n"
9992 "};",
9993 Style);
9994 verifyFormat("typedef struct Foo\n"
9995 "{\n"
9996 " Foo();\n"
9997 "} Foo_t;",
9998 Style);
9999 verifyFormat("union Foo\n"
10000 "{\n"
10001 " A,\n"
10002 "};",
10003 Style);
10004 verifyFormat("typedef union Foo\n"
10005 "{\n"
10006 " A,\n"
10007 "} Foo_t;",
10008 Style);
10009 verifyFormat("namespace Foo\n"
10010 "{\n"
10011 "void Bar();\n"
10012 "};",
10013 Style);
10014 }
10015
TEST_F(FormatTest,UnderstandContextOfRecordTypeKeywords)10016 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
10017 // Elaborate type variable declarations.
10018 verifyFormat("struct foo a = {bar};\nint n;");
10019 verifyFormat("class foo a = {bar};\nint n;");
10020 verifyFormat("union foo a = {bar};\nint n;");
10021
10022 // Elaborate types inside function definitions.
10023 verifyFormat("struct foo f() {}\nint n;");
10024 verifyFormat("class foo f() {}\nint n;");
10025 verifyFormat("union foo f() {}\nint n;");
10026
10027 // Templates.
10028 verifyFormat("template <class X> void f() {}\nint n;");
10029 verifyFormat("template <struct X> void f() {}\nint n;");
10030 verifyFormat("template <union X> void f() {}\nint n;");
10031
10032 // Actual definitions...
10033 verifyFormat("struct {\n} n;");
10034 verifyFormat(
10035 "template <template <class T, class Y>, class Z> class X {\n} n;");
10036 verifyFormat("union Z {\n int n;\n} x;");
10037 verifyFormat("class MACRO Z {\n} n;");
10038 verifyFormat("class MACRO(X) Z {\n} n;");
10039 verifyFormat("class __attribute__(X) Z {\n} n;");
10040 verifyFormat("class __declspec(X) Z {\n} n;");
10041 verifyFormat("class A##B##C {\n} n;");
10042 verifyFormat("class alignas(16) Z {\n} n;");
10043 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
10044 verifyFormat("class MACROA MACRO(X) Z {\n} n;");
10045
10046 // Redefinition from nested context:
10047 verifyFormat("class A::B::C {\n} n;");
10048
10049 // Template definitions.
10050 verifyFormat(
10051 "template <typename F>\n"
10052 "Matcher(const Matcher<F> &Other,\n"
10053 " typename enable_if_c<is_base_of<F, T>::value &&\n"
10054 " !is_same<F, T>::value>::type * = 0)\n"
10055 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
10056
10057 // FIXME: This is still incorrectly handled at the formatter side.
10058 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
10059 verifyFormat("int i = SomeFunction(a<b, a> b);");
10060
10061 // FIXME:
10062 // This now gets parsed incorrectly as class definition.
10063 // verifyFormat("class A<int> f() {\n}\nint n;");
10064
10065 // Elaborate types where incorrectly parsing the structural element would
10066 // break the indent.
10067 verifyFormat("if (true)\n"
10068 " class X x;\n"
10069 "else\n"
10070 " f();\n");
10071
10072 // This is simply incomplete. Formatting is not important, but must not crash.
10073 verifyFormat("class A:");
10074 }
10075
TEST_F(FormatTest,DoNotInterfereWithErrorAndWarning)10076 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
10077 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n",
10078 format("#error Leave all white!!!!! space* alone!\n"));
10079 EXPECT_EQ(
10080 "#warning Leave all white!!!!! space* alone!\n",
10081 format("#warning Leave all white!!!!! space* alone!\n"));
10082 EXPECT_EQ("#error 1", format(" # error 1"));
10083 EXPECT_EQ("#warning 1", format(" # warning 1"));
10084 }
10085
TEST_F(FormatTest,FormatHashIfExpressions)10086 TEST_F(FormatTest, FormatHashIfExpressions) {
10087 verifyFormat("#if AAAA && BBBB");
10088 verifyFormat("#if (AAAA && BBBB)");
10089 verifyFormat("#elif (AAAA && BBBB)");
10090 // FIXME: Come up with a better indentation for #elif.
10091 verifyFormat(
10092 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n"
10093 " defined(BBBBBBBB)\n"
10094 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n"
10095 " defined(BBBBBBBB)\n"
10096 "#endif",
10097 getLLVMStyleWithColumns(65));
10098 }
10099
TEST_F(FormatTest,MergeHandlingInTheFaceOfPreprocessorDirectives)10100 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
10101 FormatStyle AllowsMergedIf = getGoogleStyle();
10102 AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
10103 FormatStyle::SIS_WithoutElse;
10104 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
10105 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
10106 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf);
10107 EXPECT_EQ("if (true) return 42;",
10108 format("if (true)\nreturn 42;", AllowsMergedIf));
10109 FormatStyle ShortMergedIf = AllowsMergedIf;
10110 ShortMergedIf.ColumnLimit = 25;
10111 verifyFormat("#define A \\\n"
10112 " if (true) return 42;",
10113 ShortMergedIf);
10114 verifyFormat("#define A \\\n"
10115 " f(); \\\n"
10116 " if (true)\n"
10117 "#define B",
10118 ShortMergedIf);
10119 verifyFormat("#define A \\\n"
10120 " f(); \\\n"
10121 " if (true)\n"
10122 "g();",
10123 ShortMergedIf);
10124 verifyFormat("{\n"
10125 "#ifdef A\n"
10126 " // Comment\n"
10127 " if (true) continue;\n"
10128 "#endif\n"
10129 " // Comment\n"
10130 " if (true) continue;\n"
10131 "}",
10132 ShortMergedIf);
10133 ShortMergedIf.ColumnLimit = 33;
10134 verifyFormat("#define A \\\n"
10135 " if constexpr (true) return 42;",
10136 ShortMergedIf);
10137 verifyFormat("#define A \\\n"
10138 " if CONSTEXPR (true) return 42;",
10139 ShortMergedIf);
10140 ShortMergedIf.ColumnLimit = 29;
10141 verifyFormat("#define A \\\n"
10142 " if (aaaaaaaaaa) return 1; \\\n"
10143 " return 2;",
10144 ShortMergedIf);
10145 ShortMergedIf.ColumnLimit = 28;
10146 verifyFormat("#define A \\\n"
10147 " if (aaaaaaaaaa) \\\n"
10148 " return 1; \\\n"
10149 " return 2;",
10150 ShortMergedIf);
10151 verifyFormat("#define A \\\n"
10152 " if constexpr (aaaaaaa) \\\n"
10153 " return 1; \\\n"
10154 " return 2;",
10155 ShortMergedIf);
10156 verifyFormat("#define A \\\n"
10157 " if CONSTEXPR (aaaaaaa) \\\n"
10158 " return 1; \\\n"
10159 " return 2;",
10160 ShortMergedIf);
10161 }
10162
TEST_F(FormatTest,FormatStarDependingOnContext)10163 TEST_F(FormatTest, FormatStarDependingOnContext) {
10164 verifyFormat("void f(int *a);");
10165 verifyFormat("void f() { f(fint * b); }");
10166 verifyFormat("class A {\n void f(int *a);\n};");
10167 verifyFormat("class A {\n int *a;\n};");
10168 verifyFormat("namespace a {\n"
10169 "namespace b {\n"
10170 "class A {\n"
10171 " void f() {}\n"
10172 " int *a;\n"
10173 "};\n"
10174 "} // namespace b\n"
10175 "} // namespace a");
10176 }
10177
TEST_F(FormatTest,SpecialTokensAtEndOfLine)10178 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
10179 verifyFormat("while");
10180 verifyFormat("operator");
10181 }
10182
TEST_F(FormatTest,SkipsDeeplyNestedLines)10183 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
10184 // This code would be painfully slow to format if we didn't skip it.
10185 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
10186 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10187 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10188 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10189 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10190 "A(1, 1)\n"
10191 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
10192 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10193 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10194 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10195 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10196 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10197 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10198 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10199 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10200 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
10201 // Deeply nested part is untouched, rest is formatted.
10202 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
10203 format(std::string("int i;\n") + Code + "int j;\n",
10204 getLLVMStyle(), SC_ExpectIncomplete));
10205 }
10206
10207 //===----------------------------------------------------------------------===//
10208 // Objective-C tests.
10209 //===----------------------------------------------------------------------===//
10210
TEST_F(FormatTest,FormatForObjectiveCMethodDecls)10211 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
10212 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
10213 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
10214 format("-(NSUInteger)indexOfObject:(id)anObject;"));
10215 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
10216 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
10217 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
10218 format("-(NSInteger)Method3:(id)anObject;"));
10219 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
10220 format("-(NSInteger)Method4:(id)anObject;"));
10221 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
10222 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
10223 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
10224 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
10225 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
10226 "forAllCells:(BOOL)flag;",
10227 format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
10228 "forAllCells:(BOOL)flag;"));
10229
10230 // Very long objectiveC method declaration.
10231 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
10232 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
10233 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
10234 " inRange:(NSRange)range\n"
10235 " outRange:(NSRange)out_range\n"
10236 " outRange1:(NSRange)out_range1\n"
10237 " outRange2:(NSRange)out_range2\n"
10238 " outRange3:(NSRange)out_range3\n"
10239 " outRange4:(NSRange)out_range4\n"
10240 " outRange5:(NSRange)out_range5\n"
10241 " outRange6:(NSRange)out_range6\n"
10242 " outRange7:(NSRange)out_range7\n"
10243 " outRange8:(NSRange)out_range8\n"
10244 " outRange9:(NSRange)out_range9;");
10245
10246 // When the function name has to be wrapped.
10247 FormatStyle Style = getLLVMStyle();
10248 // ObjC ignores IndentWrappedFunctionNames when wrapping methods
10249 // and always indents instead.
10250 Style.IndentWrappedFunctionNames = false;
10251 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
10252 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
10253 " anotherName:(NSString)bbbbbbbbbbbbbb {\n"
10254 "}",
10255 Style);
10256 Style.IndentWrappedFunctionNames = true;
10257 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
10258 " veryLooooooooooongName:(NSString)cccccccccccccc\n"
10259 " anotherName:(NSString)dddddddddddddd {\n"
10260 "}",
10261 Style);
10262
10263 verifyFormat("- (int)sum:(vector<int>)numbers;");
10264 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
10265 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
10266 // protocol lists (but not for template classes):
10267 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
10268
10269 verifyFormat("- (int (*)())foo:(int (*)())f;");
10270 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
10271
10272 // If there's no return type (very rare in practice!), LLVM and Google style
10273 // agree.
10274 verifyFormat("- foo;");
10275 verifyFormat("- foo:(int)f;");
10276 verifyGoogleFormat("- foo:(int)foo;");
10277 }
10278
TEST_F(FormatTest,BreaksStringLiterals)10279 TEST_F(FormatTest, BreaksStringLiterals) {
10280 EXPECT_EQ("\"some text \"\n"
10281 "\"other\";",
10282 format("\"some text other\";", getLLVMStyleWithColumns(12)));
10283 EXPECT_EQ("\"some text \"\n"
10284 "\"other\";",
10285 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
10286 EXPECT_EQ(
10287 "#define A \\\n"
10288 " \"some \" \\\n"
10289 " \"text \" \\\n"
10290 " \"other\";",
10291 format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
10292 EXPECT_EQ(
10293 "#define A \\\n"
10294 " \"so \" \\\n"
10295 " \"text \" \\\n"
10296 " \"other\";",
10297 format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
10298
10299 EXPECT_EQ("\"some text\"",
10300 format("\"some text\"", getLLVMStyleWithColumns(1)));
10301 EXPECT_EQ("\"some text\"",
10302 format("\"some text\"", getLLVMStyleWithColumns(11)));
10303 EXPECT_EQ("\"some \"\n"
10304 "\"text\"",
10305 format("\"some text\"", getLLVMStyleWithColumns(10)));
10306 EXPECT_EQ("\"some \"\n"
10307 "\"text\"",
10308 format("\"some text\"", getLLVMStyleWithColumns(7)));
10309 EXPECT_EQ("\"some\"\n"
10310 "\" tex\"\n"
10311 "\"t\"",
10312 format("\"some text\"", getLLVMStyleWithColumns(6)));
10313 EXPECT_EQ("\"some\"\n"
10314 "\" tex\"\n"
10315 "\" and\"",
10316 format("\"some tex and\"", getLLVMStyleWithColumns(6)));
10317 EXPECT_EQ("\"some\"\n"
10318 "\"/tex\"\n"
10319 "\"/and\"",
10320 format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
10321
10322 EXPECT_EQ("variable =\n"
10323 " \"long string \"\n"
10324 " \"literal\";",
10325 format("variable = \"long string literal\";",
10326 getLLVMStyleWithColumns(20)));
10327
10328 EXPECT_EQ("variable = f(\n"
10329 " \"long string \"\n"
10330 " \"literal\",\n"
10331 " short,\n"
10332 " loooooooooooooooooooong);",
10333 format("variable = f(\"long string literal\", short, "
10334 "loooooooooooooooooooong);",
10335 getLLVMStyleWithColumns(20)));
10336
10337 EXPECT_EQ(
10338 "f(g(\"long string \"\n"
10339 " \"literal\"),\n"
10340 " b);",
10341 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
10342 EXPECT_EQ("f(g(\"long string \"\n"
10343 " \"literal\",\n"
10344 " a),\n"
10345 " b);",
10346 format("f(g(\"long string literal\", a), b);",
10347 getLLVMStyleWithColumns(20)));
10348 EXPECT_EQ(
10349 "f(\"one two\".split(\n"
10350 " variable));",
10351 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
10352 EXPECT_EQ("f(\"one two three four five six \"\n"
10353 " \"seven\".split(\n"
10354 " really_looooong_variable));",
10355 format("f(\"one two three four five six seven\"."
10356 "split(really_looooong_variable));",
10357 getLLVMStyleWithColumns(33)));
10358
10359 EXPECT_EQ("f(\"some \"\n"
10360 " \"text\",\n"
10361 " other);",
10362 format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
10363
10364 // Only break as a last resort.
10365 verifyFormat(
10366 "aaaaaaaaaaaaaaaaaaaa(\n"
10367 " aaaaaaaaaaaaaaaaaaaa,\n"
10368 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
10369
10370 EXPECT_EQ("\"splitmea\"\n"
10371 "\"trandomp\"\n"
10372 "\"oint\"",
10373 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
10374
10375 EXPECT_EQ("\"split/\"\n"
10376 "\"pathat/\"\n"
10377 "\"slashes\"",
10378 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
10379
10380 EXPECT_EQ("\"split/\"\n"
10381 "\"pathat/\"\n"
10382 "\"slashes\"",
10383 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
10384 EXPECT_EQ("\"split at \"\n"
10385 "\"spaces/at/\"\n"
10386 "\"slashes.at.any$\"\n"
10387 "\"non-alphanumeric%\"\n"
10388 "\"1111111111characte\"\n"
10389 "\"rs\"",
10390 format("\"split at "
10391 "spaces/at/"
10392 "slashes.at."
10393 "any$non-"
10394 "alphanumeric%"
10395 "1111111111characte"
10396 "rs\"",
10397 getLLVMStyleWithColumns(20)));
10398
10399 // Verify that splitting the strings understands
10400 // Style::AlwaysBreakBeforeMultilineStrings.
10401 EXPECT_EQ("aaaaaaaaaaaa(\n"
10402 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
10403 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
10404 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
10405 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
10406 "aaaaaaaaaaaaaaaaaaaaaa\");",
10407 getGoogleStyle()));
10408 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
10409 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
10410 format("return \"aaaaaaaaaaaaaaaaaaaaaa "
10411 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
10412 "aaaaaaaaaaaaaaaaaaaaaa\";",
10413 getGoogleStyle()));
10414 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
10415 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
10416 format("llvm::outs() << "
10417 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
10418 "aaaaaaaaaaaaaaaaaaa\";"));
10419 EXPECT_EQ("ffff(\n"
10420 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
10421 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
10422 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
10423 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
10424 getGoogleStyle()));
10425
10426 FormatStyle Style = getLLVMStyleWithColumns(12);
10427 Style.BreakStringLiterals = false;
10428 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
10429
10430 FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
10431 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
10432 EXPECT_EQ("#define A \\\n"
10433 " \"some \" \\\n"
10434 " \"text \" \\\n"
10435 " \"other\";",
10436 format("#define A \"some text other\";", AlignLeft));
10437 }
10438
TEST_F(FormatTest,BreaksStringLiteralsAtColumnLimit)10439 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
10440 EXPECT_EQ("C a = \"some more \"\n"
10441 " \"text\";",
10442 format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
10443 }
10444
TEST_F(FormatTest,FullyRemoveEmptyLines)10445 TEST_F(FormatTest, FullyRemoveEmptyLines) {
10446 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
10447 NoEmptyLines.MaxEmptyLinesToKeep = 0;
10448 EXPECT_EQ("int i = a(b());",
10449 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
10450 }
10451
TEST_F(FormatTest,BreaksStringLiteralsWithTabs)10452 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
10453 EXPECT_EQ(
10454 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
10455 "(\n"
10456 " \"x\t\");",
10457 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
10458 "aaaaaaa("
10459 "\"x\t\");"));
10460 }
10461
TEST_F(FormatTest,BreaksWideAndNSStringLiterals)10462 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
10463 EXPECT_EQ(
10464 "u8\"utf8 string \"\n"
10465 "u8\"literal\";",
10466 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
10467 EXPECT_EQ(
10468 "u\"utf16 string \"\n"
10469 "u\"literal\";",
10470 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
10471 EXPECT_EQ(
10472 "U\"utf32 string \"\n"
10473 "U\"literal\";",
10474 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
10475 EXPECT_EQ("L\"wide string \"\n"
10476 "L\"literal\";",
10477 format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
10478 EXPECT_EQ("@\"NSString \"\n"
10479 "@\"literal\";",
10480 format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
10481 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
10482
10483 // This input makes clang-format try to split the incomplete unicode escape
10484 // sequence, which used to lead to a crasher.
10485 verifyNoCrash(
10486 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
10487 getLLVMStyleWithColumns(60));
10488 }
10489
TEST_F(FormatTest,DoesNotBreakRawStringLiterals)10490 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
10491 FormatStyle Style = getGoogleStyleWithColumns(15);
10492 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
10493 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
10494 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
10495 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
10496 EXPECT_EQ("u8R\"x(raw literal)x\";",
10497 format("u8R\"x(raw literal)x\";", Style));
10498 }
10499
TEST_F(FormatTest,BreaksStringLiteralsWithin_TMacro)10500 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
10501 FormatStyle Style = getLLVMStyleWithColumns(20);
10502 EXPECT_EQ(
10503 "_T(\"aaaaaaaaaaaaaa\")\n"
10504 "_T(\"aaaaaaaaaaaaaa\")\n"
10505 "_T(\"aaaaaaaaaaaa\")",
10506 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
10507 EXPECT_EQ("f(x,\n"
10508 " _T(\"aaaaaaaaaaaa\")\n"
10509 " _T(\"aaa\"),\n"
10510 " z);",
10511 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
10512
10513 // FIXME: Handle embedded spaces in one iteration.
10514 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
10515 // "_T(\"aaaaaaaaaaaaa\")\n"
10516 // "_T(\"aaaaaaaaaaaaa\")\n"
10517 // "_T(\"a\")",
10518 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
10519 // getLLVMStyleWithColumns(20)));
10520 EXPECT_EQ(
10521 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
10522 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
10523 EXPECT_EQ("f(\n"
10524 "#if !TEST\n"
10525 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
10526 "#endif\n"
10527 ");",
10528 format("f(\n"
10529 "#if !TEST\n"
10530 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
10531 "#endif\n"
10532 ");"));
10533 EXPECT_EQ("f(\n"
10534 "\n"
10535 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
10536 format("f(\n"
10537 "\n"
10538 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
10539 }
10540
TEST_F(FormatTest,BreaksStringLiteralOperands)10541 TEST_F(FormatTest, BreaksStringLiteralOperands) {
10542 // In a function call with two operands, the second can be broken with no line
10543 // break before it.
10544 EXPECT_EQ(
10545 "func(a, \"long long \"\n"
10546 " \"long long\");",
10547 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
10548 // In a function call with three operands, the second must be broken with a
10549 // line break before it.
10550 EXPECT_EQ("func(a,\n"
10551 " \"long long long \"\n"
10552 " \"long\",\n"
10553 " c);",
10554 format("func(a, \"long long long long\", c);",
10555 getLLVMStyleWithColumns(24)));
10556 // In a function call with three operands, the third must be broken with a
10557 // line break before it.
10558 EXPECT_EQ("func(a, b,\n"
10559 " \"long long long \"\n"
10560 " \"long\");",
10561 format("func(a, b, \"long long long long\");",
10562 getLLVMStyleWithColumns(24)));
10563 // In a function call with three operands, both the second and the third must
10564 // be broken with a line break before them.
10565 EXPECT_EQ("func(a,\n"
10566 " \"long long long \"\n"
10567 " \"long\",\n"
10568 " \"long long long \"\n"
10569 " \"long\");",
10570 format("func(a, \"long long long long\", \"long long long long\");",
10571 getLLVMStyleWithColumns(24)));
10572 // In a chain of << with two operands, the second can be broken with no line
10573 // break before it.
10574 EXPECT_EQ("a << \"line line \"\n"
10575 " \"line\";",
10576 format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
10577 // In a chain of << with three operands, the second can be broken with no line
10578 // break before it.
10579 EXPECT_EQ(
10580 "abcde << \"line \"\n"
10581 " \"line line\"\n"
10582 " << c;",
10583 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
10584 // In a chain of << with three operands, the third must be broken with a line
10585 // break before it.
10586 EXPECT_EQ(
10587 "a << b\n"
10588 " << \"line line \"\n"
10589 " \"line\";",
10590 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
10591 // In a chain of << with three operands, the second can be broken with no line
10592 // break before it and the third must be broken with a line break before it.
10593 EXPECT_EQ("abcd << \"line line \"\n"
10594 " \"line\"\n"
10595 " << \"line line \"\n"
10596 " \"line\";",
10597 format("abcd << \"line line line\" << \"line line line\";",
10598 getLLVMStyleWithColumns(20)));
10599 // In a chain of binary operators with two operands, the second can be broken
10600 // with no line break before it.
10601 EXPECT_EQ(
10602 "abcd + \"line line \"\n"
10603 " \"line line\";",
10604 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
10605 // In a chain of binary operators with three operands, the second must be
10606 // broken with a line break before it.
10607 EXPECT_EQ("abcd +\n"
10608 " \"line line \"\n"
10609 " \"line line\" +\n"
10610 " e;",
10611 format("abcd + \"line line line line\" + e;",
10612 getLLVMStyleWithColumns(20)));
10613 // In a function call with two operands, with AlignAfterOpenBracket enabled,
10614 // the first must be broken with a line break before it.
10615 FormatStyle Style = getLLVMStyleWithColumns(25);
10616 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
10617 EXPECT_EQ("someFunction(\n"
10618 " \"long long long \"\n"
10619 " \"long\",\n"
10620 " a);",
10621 format("someFunction(\"long long long long\", a);", Style));
10622 }
10623
TEST_F(FormatTest,DontSplitStringLiteralsWithEscapedNewlines)10624 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
10625 EXPECT_EQ(
10626 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
10627 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
10628 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
10629 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
10630 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
10631 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
10632 }
10633
TEST_F(FormatTest,CountsCharactersInMultilineRawStringLiterals)10634 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
10635 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
10636 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle()));
10637 EXPECT_EQ("fffffffffff(g(R\"x(\n"
10638 "multiline raw string literal xxxxxxxxxxxxxx\n"
10639 ")x\",\n"
10640 " a),\n"
10641 " b);",
10642 format("fffffffffff(g(R\"x(\n"
10643 "multiline raw string literal xxxxxxxxxxxxxx\n"
10644 ")x\", a), b);",
10645 getGoogleStyleWithColumns(20)));
10646 EXPECT_EQ("fffffffffff(\n"
10647 " g(R\"x(qqq\n"
10648 "multiline raw string literal xxxxxxxxxxxxxx\n"
10649 ")x\",\n"
10650 " a),\n"
10651 " b);",
10652 format("fffffffffff(g(R\"x(qqq\n"
10653 "multiline raw string literal xxxxxxxxxxxxxx\n"
10654 ")x\", a), b);",
10655 getGoogleStyleWithColumns(20)));
10656
10657 EXPECT_EQ("fffffffffff(R\"x(\n"
10658 "multiline raw string literal xxxxxxxxxxxxxx\n"
10659 ")x\");",
10660 format("fffffffffff(R\"x(\n"
10661 "multiline raw string literal xxxxxxxxxxxxxx\n"
10662 ")x\");",
10663 getGoogleStyleWithColumns(20)));
10664 EXPECT_EQ("fffffffffff(R\"x(\n"
10665 "multiline raw string literal xxxxxxxxxxxxxx\n"
10666 ")x\" + bbbbbb);",
10667 format("fffffffffff(R\"x(\n"
10668 "multiline raw string literal xxxxxxxxxxxxxx\n"
10669 ")x\" + bbbbbb);",
10670 getGoogleStyleWithColumns(20)));
10671 EXPECT_EQ("fffffffffff(\n"
10672 " R\"x(\n"
10673 "multiline raw string literal xxxxxxxxxxxxxx\n"
10674 ")x\" +\n"
10675 " bbbbbb);",
10676 format("fffffffffff(\n"
10677 " R\"x(\n"
10678 "multiline raw string literal xxxxxxxxxxxxxx\n"
10679 ")x\" + bbbbbb);",
10680 getGoogleStyleWithColumns(20)));
10681 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
10682 format("fffffffffff(\n"
10683 " R\"(single line raw string)\" + bbbbbb);"));
10684 }
10685
TEST_F(FormatTest,SkipsUnknownStringLiterals)10686 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
10687 verifyFormat("string a = \"unterminated;");
10688 EXPECT_EQ("function(\"unterminated,\n"
10689 " OtherParameter);",
10690 format("function( \"unterminated,\n"
10691 " OtherParameter);"));
10692 }
10693
TEST_F(FormatTest,DoesNotTryToParseUDLiteralsInPreCpp11Code)10694 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
10695 FormatStyle Style = getLLVMStyle();
10696 Style.Standard = FormatStyle::LS_Cpp03;
10697 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
10698 format("#define x(_a) printf(\"foo\"_a);", Style));
10699 }
10700
TEST_F(FormatTest,CppLexVersion)10701 TEST_F(FormatTest, CppLexVersion) {
10702 FormatStyle Style = getLLVMStyle();
10703 // Formatting of x * y differs if x is a type.
10704 verifyFormat("void foo() { MACRO(a * b); }", Style);
10705 verifyFormat("void foo() { MACRO(int *b); }", Style);
10706
10707 // LLVM style uses latest lexer.
10708 verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
10709 Style.Standard = FormatStyle::LS_Cpp17;
10710 // But in c++17, char8_t isn't a keyword.
10711 verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
10712 }
10713
TEST_F(FormatTest,UnderstandsCpp1y)10714 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
10715
TEST_F(FormatTest,BreakStringLiteralsBeforeUnbreakableTokenSequence)10716 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
10717 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
10718 " \"ddeeefff\");",
10719 format("someFunction(\"aaabbbcccdddeeefff\");",
10720 getLLVMStyleWithColumns(25)));
10721 EXPECT_EQ("someFunction1234567890(\n"
10722 " \"aaabbbcccdddeeefff\");",
10723 format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
10724 getLLVMStyleWithColumns(26)));
10725 EXPECT_EQ("someFunction1234567890(\n"
10726 " \"aaabbbcccdddeeeff\"\n"
10727 " \"f\");",
10728 format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
10729 getLLVMStyleWithColumns(25)));
10730 EXPECT_EQ("someFunction1234567890(\n"
10731 " \"aaabbbcccdddeeeff\"\n"
10732 " \"f\");",
10733 format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
10734 getLLVMStyleWithColumns(24)));
10735 EXPECT_EQ("someFunction(\n"
10736 " \"aaabbbcc ddde \"\n"
10737 " \"efff\");",
10738 format("someFunction(\"aaabbbcc ddde efff\");",
10739 getLLVMStyleWithColumns(25)));
10740 EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
10741 " \"ddeeefff\");",
10742 format("someFunction(\"aaabbbccc ddeeefff\");",
10743 getLLVMStyleWithColumns(25)));
10744 EXPECT_EQ("someFunction1234567890(\n"
10745 " \"aaabb \"\n"
10746 " \"cccdddeeefff\");",
10747 format("someFunction1234567890(\"aaabb cccdddeeefff\");",
10748 getLLVMStyleWithColumns(25)));
10749 EXPECT_EQ("#define A \\\n"
10750 " string s = \\\n"
10751 " \"123456789\" \\\n"
10752 " \"0\"; \\\n"
10753 " int i;",
10754 format("#define A string s = \"1234567890\"; int i;",
10755 getLLVMStyleWithColumns(20)));
10756 EXPECT_EQ("someFunction(\n"
10757 " \"aaabbbcc \"\n"
10758 " \"dddeeefff\");",
10759 format("someFunction(\"aaabbbcc dddeeefff\");",
10760 getLLVMStyleWithColumns(25)));
10761 }
10762
TEST_F(FormatTest,DoNotBreakStringLiteralsInEscapeSequence)10763 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
10764 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
10765 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
10766 EXPECT_EQ("\"test\"\n"
10767 "\"\\n\"",
10768 format("\"test\\n\"", getLLVMStyleWithColumns(7)));
10769 EXPECT_EQ("\"tes\\\\\"\n"
10770 "\"n\"",
10771 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
10772 EXPECT_EQ("\"\\\\\\\\\"\n"
10773 "\"\\n\"",
10774 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
10775 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
10776 EXPECT_EQ("\"\\uff01\"\n"
10777 "\"test\"",
10778 format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
10779 EXPECT_EQ("\"\\Uff01ff02\"",
10780 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
10781 EXPECT_EQ("\"\\x000000000001\"\n"
10782 "\"next\"",
10783 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
10784 EXPECT_EQ("\"\\x000000000001next\"",
10785 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
10786 EXPECT_EQ("\"\\x000000000001\"",
10787 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
10788 EXPECT_EQ("\"test\"\n"
10789 "\"\\000000\"\n"
10790 "\"000001\"",
10791 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
10792 EXPECT_EQ("\"test\\000\"\n"
10793 "\"00000000\"\n"
10794 "\"1\"",
10795 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
10796 }
10797
TEST_F(FormatTest,DoNotCreateUnreasonableUnwrappedLines)10798 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
10799 verifyFormat("void f() {\n"
10800 " return g() {}\n"
10801 " void h() {}");
10802 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
10803 "g();\n"
10804 "}");
10805 }
10806
TEST_F(FormatTest,DoNotPrematurelyEndUnwrappedLineForReturnStatements)10807 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
10808 verifyFormat(
10809 "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
10810 }
10811
TEST_F(FormatTest,FormatsClosingBracesInEmptyNestedBlocks)10812 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
10813 verifyFormat("class X {\n"
10814 " void f() {\n"
10815 " }\n"
10816 "};",
10817 getLLVMStyleWithColumns(12));
10818 }
10819
TEST_F(FormatTest,ConfigurableIndentWidth)10820 TEST_F(FormatTest, ConfigurableIndentWidth) {
10821 FormatStyle EightIndent = getLLVMStyleWithColumns(18);
10822 EightIndent.IndentWidth = 8;
10823 EightIndent.ContinuationIndentWidth = 8;
10824 verifyFormat("void f() {\n"
10825 " someFunction();\n"
10826 " if (true) {\n"
10827 " f();\n"
10828 " }\n"
10829 "}",
10830 EightIndent);
10831 verifyFormat("class X {\n"
10832 " void f() {\n"
10833 " }\n"
10834 "};",
10835 EightIndent);
10836 verifyFormat("int x[] = {\n"
10837 " call(),\n"
10838 " call()};",
10839 EightIndent);
10840 }
10841
TEST_F(FormatTest,ConfigurableFunctionDeclarationIndentAfterType)10842 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
10843 verifyFormat("double\n"
10844 "f();",
10845 getLLVMStyleWithColumns(8));
10846 }
10847
TEST_F(FormatTest,ConfigurableUseOfTab)10848 TEST_F(FormatTest, ConfigurableUseOfTab) {
10849 FormatStyle Tab = getLLVMStyleWithColumns(42);
10850 Tab.IndentWidth = 8;
10851 Tab.UseTab = FormatStyle::UT_Always;
10852 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
10853
10854 EXPECT_EQ("if (aaaaaaaa && // q\n"
10855 " bb)\t\t// w\n"
10856 "\t;",
10857 format("if (aaaaaaaa &&// q\n"
10858 "bb)// w\n"
10859 ";",
10860 Tab));
10861 EXPECT_EQ("if (aaa && bbb) // w\n"
10862 "\t;",
10863 format("if(aaa&&bbb)// w\n"
10864 ";",
10865 Tab));
10866
10867 verifyFormat("class X {\n"
10868 "\tvoid f() {\n"
10869 "\t\tsomeFunction(parameter1,\n"
10870 "\t\t\t parameter2);\n"
10871 "\t}\n"
10872 "};",
10873 Tab);
10874 verifyFormat("#define A \\\n"
10875 "\tvoid f() { \\\n"
10876 "\t\tsomeFunction( \\\n"
10877 "\t\t parameter1, \\\n"
10878 "\t\t parameter2); \\\n"
10879 "\t}",
10880 Tab);
10881 verifyFormat("int a;\t // x\n"
10882 "int bbbbbbbb; // x\n",
10883 Tab);
10884
10885 Tab.TabWidth = 4;
10886 Tab.IndentWidth = 8;
10887 verifyFormat("class TabWidth4Indent8 {\n"
10888 "\t\tvoid f() {\n"
10889 "\t\t\t\tsomeFunction(parameter1,\n"
10890 "\t\t\t\t\t\t\t parameter2);\n"
10891 "\t\t}\n"
10892 "};",
10893 Tab);
10894
10895 Tab.TabWidth = 4;
10896 Tab.IndentWidth = 4;
10897 verifyFormat("class TabWidth4Indent4 {\n"
10898 "\tvoid f() {\n"
10899 "\t\tsomeFunction(parameter1,\n"
10900 "\t\t\t\t\t parameter2);\n"
10901 "\t}\n"
10902 "};",
10903 Tab);
10904
10905 Tab.TabWidth = 8;
10906 Tab.IndentWidth = 4;
10907 verifyFormat("class TabWidth8Indent4 {\n"
10908 " void f() {\n"
10909 "\tsomeFunction(parameter1,\n"
10910 "\t\t parameter2);\n"
10911 " }\n"
10912 "};",
10913 Tab);
10914
10915 Tab.TabWidth = 8;
10916 Tab.IndentWidth = 8;
10917 EXPECT_EQ("/*\n"
10918 "\t a\t\tcomment\n"
10919 "\t in multiple lines\n"
10920 " */",
10921 format(" /*\t \t \n"
10922 " \t \t a\t\tcomment\t \t\n"
10923 " \t \t in multiple lines\t\n"
10924 " \t */",
10925 Tab));
10926
10927 Tab.UseTab = FormatStyle::UT_ForIndentation;
10928 verifyFormat("{\n"
10929 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10930 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10931 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10932 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10933 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10934 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10935 "};",
10936 Tab);
10937 verifyFormat("enum AA {\n"
10938 "\ta1, // Force multiple lines\n"
10939 "\ta2,\n"
10940 "\ta3\n"
10941 "};",
10942 Tab);
10943 EXPECT_EQ("if (aaaaaaaa && // q\n"
10944 " bb) // w\n"
10945 "\t;",
10946 format("if (aaaaaaaa &&// q\n"
10947 "bb)// w\n"
10948 ";",
10949 Tab));
10950 verifyFormat("class X {\n"
10951 "\tvoid f() {\n"
10952 "\t\tsomeFunction(parameter1,\n"
10953 "\t\t parameter2);\n"
10954 "\t}\n"
10955 "};",
10956 Tab);
10957 verifyFormat("{\n"
10958 "\tQ(\n"
10959 "\t {\n"
10960 "\t\t int a;\n"
10961 "\t\t someFunction(aaaaaaaa,\n"
10962 "\t\t bbbbbbb);\n"
10963 "\t },\n"
10964 "\t p);\n"
10965 "}",
10966 Tab);
10967 EXPECT_EQ("{\n"
10968 "\t/* aaaa\n"
10969 "\t bbbb */\n"
10970 "}",
10971 format("{\n"
10972 "/* aaaa\n"
10973 " bbbb */\n"
10974 "}",
10975 Tab));
10976 EXPECT_EQ("{\n"
10977 "\t/*\n"
10978 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10979 "\t bbbbbbbbbbbbb\n"
10980 "\t*/\n"
10981 "}",
10982 format("{\n"
10983 "/*\n"
10984 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10985 "*/\n"
10986 "}",
10987 Tab));
10988 EXPECT_EQ("{\n"
10989 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10990 "\t// bbbbbbbbbbbbb\n"
10991 "}",
10992 format("{\n"
10993 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10994 "}",
10995 Tab));
10996 EXPECT_EQ("{\n"
10997 "\t/*\n"
10998 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10999 "\t bbbbbbbbbbbbb\n"
11000 "\t*/\n"
11001 "}",
11002 format("{\n"
11003 "\t/*\n"
11004 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11005 "\t*/\n"
11006 "}",
11007 Tab));
11008 EXPECT_EQ("{\n"
11009 "\t/*\n"
11010 "\n"
11011 "\t*/\n"
11012 "}",
11013 format("{\n"
11014 "\t/*\n"
11015 "\n"
11016 "\t*/\n"
11017 "}",
11018 Tab));
11019 EXPECT_EQ("{\n"
11020 "\t/*\n"
11021 " asdf\n"
11022 "\t*/\n"
11023 "}",
11024 format("{\n"
11025 "\t/*\n"
11026 " asdf\n"
11027 "\t*/\n"
11028 "}",
11029 Tab));
11030
11031 Tab.UseTab = FormatStyle::UT_Never;
11032 EXPECT_EQ("/*\n"
11033 " a\t\tcomment\n"
11034 " in multiple lines\n"
11035 " */",
11036 format(" /*\t \t \n"
11037 " \t \t a\t\tcomment\t \t\n"
11038 " \t \t in multiple lines\t\n"
11039 " \t */",
11040 Tab));
11041 EXPECT_EQ("/* some\n"
11042 " comment */",
11043 format(" \t \t /* some\n"
11044 " \t \t comment */",
11045 Tab));
11046 EXPECT_EQ("int a; /* some\n"
11047 " comment */",
11048 format(" \t \t int a; /* some\n"
11049 " \t \t comment */",
11050 Tab));
11051
11052 EXPECT_EQ("int a; /* some\n"
11053 "comment */",
11054 format(" \t \t int\ta; /* some\n"
11055 " \t \t comment */",
11056 Tab));
11057 EXPECT_EQ("f(\"\t\t\"); /* some\n"
11058 " comment */",
11059 format(" \t \t f(\"\t\t\"); /* some\n"
11060 " \t \t comment */",
11061 Tab));
11062 EXPECT_EQ("{\n"
11063 " /*\n"
11064 " * Comment\n"
11065 " */\n"
11066 " int i;\n"
11067 "}",
11068 format("{\n"
11069 "\t/*\n"
11070 "\t * Comment\n"
11071 "\t */\n"
11072 "\t int i;\n"
11073 "}",
11074 Tab));
11075
11076 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
11077 Tab.TabWidth = 8;
11078 Tab.IndentWidth = 8;
11079 EXPECT_EQ("if (aaaaaaaa && // q\n"
11080 " bb) // w\n"
11081 "\t;",
11082 format("if (aaaaaaaa &&// q\n"
11083 "bb)// w\n"
11084 ";",
11085 Tab));
11086 EXPECT_EQ("if (aaa && bbb) // w\n"
11087 "\t;",
11088 format("if(aaa&&bbb)// w\n"
11089 ";",
11090 Tab));
11091 verifyFormat("class X {\n"
11092 "\tvoid f() {\n"
11093 "\t\tsomeFunction(parameter1,\n"
11094 "\t\t\t parameter2);\n"
11095 "\t}\n"
11096 "};",
11097 Tab);
11098 verifyFormat("#define A \\\n"
11099 "\tvoid f() { \\\n"
11100 "\t\tsomeFunction( \\\n"
11101 "\t\t parameter1, \\\n"
11102 "\t\t parameter2); \\\n"
11103 "\t}",
11104 Tab);
11105 Tab.TabWidth = 4;
11106 Tab.IndentWidth = 8;
11107 verifyFormat("class TabWidth4Indent8 {\n"
11108 "\t\tvoid f() {\n"
11109 "\t\t\t\tsomeFunction(parameter1,\n"
11110 "\t\t\t\t\t\t\t parameter2);\n"
11111 "\t\t}\n"
11112 "};",
11113 Tab);
11114 Tab.TabWidth = 4;
11115 Tab.IndentWidth = 4;
11116 verifyFormat("class TabWidth4Indent4 {\n"
11117 "\tvoid f() {\n"
11118 "\t\tsomeFunction(parameter1,\n"
11119 "\t\t\t\t\t parameter2);\n"
11120 "\t}\n"
11121 "};",
11122 Tab);
11123 Tab.TabWidth = 8;
11124 Tab.IndentWidth = 4;
11125 verifyFormat("class TabWidth8Indent4 {\n"
11126 " void f() {\n"
11127 "\tsomeFunction(parameter1,\n"
11128 "\t\t parameter2);\n"
11129 " }\n"
11130 "};",
11131 Tab);
11132 Tab.TabWidth = 8;
11133 Tab.IndentWidth = 8;
11134 EXPECT_EQ("/*\n"
11135 "\t a\t\tcomment\n"
11136 "\t in multiple lines\n"
11137 " */",
11138 format(" /*\t \t \n"
11139 " \t \t a\t\tcomment\t \t\n"
11140 " \t \t in multiple lines\t\n"
11141 " \t */",
11142 Tab));
11143 verifyFormat("{\n"
11144 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11145 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11146 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11147 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11148 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11149 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11150 "};",
11151 Tab);
11152 verifyFormat("enum AA {\n"
11153 "\ta1, // Force multiple lines\n"
11154 "\ta2,\n"
11155 "\ta3\n"
11156 "};",
11157 Tab);
11158 EXPECT_EQ("if (aaaaaaaa && // q\n"
11159 " bb) // w\n"
11160 "\t;",
11161 format("if (aaaaaaaa &&// q\n"
11162 "bb)// w\n"
11163 ";",
11164 Tab));
11165 verifyFormat("class X {\n"
11166 "\tvoid f() {\n"
11167 "\t\tsomeFunction(parameter1,\n"
11168 "\t\t\t parameter2);\n"
11169 "\t}\n"
11170 "};",
11171 Tab);
11172 verifyFormat("{\n"
11173 "\tQ(\n"
11174 "\t {\n"
11175 "\t\t int a;\n"
11176 "\t\t someFunction(aaaaaaaa,\n"
11177 "\t\t\t\t bbbbbbb);\n"
11178 "\t },\n"
11179 "\t p);\n"
11180 "}",
11181 Tab);
11182 EXPECT_EQ("{\n"
11183 "\t/* aaaa\n"
11184 "\t bbbb */\n"
11185 "}",
11186 format("{\n"
11187 "/* aaaa\n"
11188 " bbbb */\n"
11189 "}",
11190 Tab));
11191 EXPECT_EQ("{\n"
11192 "\t/*\n"
11193 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11194 "\t bbbbbbbbbbbbb\n"
11195 "\t*/\n"
11196 "}",
11197 format("{\n"
11198 "/*\n"
11199 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11200 "*/\n"
11201 "}",
11202 Tab));
11203 EXPECT_EQ("{\n"
11204 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11205 "\t// bbbbbbbbbbbbb\n"
11206 "}",
11207 format("{\n"
11208 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11209 "}",
11210 Tab));
11211 EXPECT_EQ("{\n"
11212 "\t/*\n"
11213 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11214 "\t bbbbbbbbbbbbb\n"
11215 "\t*/\n"
11216 "}",
11217 format("{\n"
11218 "\t/*\n"
11219 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11220 "\t*/\n"
11221 "}",
11222 Tab));
11223 EXPECT_EQ("{\n"
11224 "\t/*\n"
11225 "\n"
11226 "\t*/\n"
11227 "}",
11228 format("{\n"
11229 "\t/*\n"
11230 "\n"
11231 "\t*/\n"
11232 "}",
11233 Tab));
11234 EXPECT_EQ("{\n"
11235 "\t/*\n"
11236 " asdf\n"
11237 "\t*/\n"
11238 "}",
11239 format("{\n"
11240 "\t/*\n"
11241 " asdf\n"
11242 "\t*/\n"
11243 "}",
11244 Tab));
11245 EXPECT_EQ("/* some\n"
11246 " comment */",
11247 format(" \t \t /* some\n"
11248 " \t \t comment */",
11249 Tab));
11250 EXPECT_EQ("int a; /* some\n"
11251 " comment */",
11252 format(" \t \t int a; /* some\n"
11253 " \t \t comment */",
11254 Tab));
11255 EXPECT_EQ("int a; /* some\n"
11256 "comment */",
11257 format(" \t \t int\ta; /* some\n"
11258 " \t \t comment */",
11259 Tab));
11260 EXPECT_EQ("f(\"\t\t\"); /* some\n"
11261 " comment */",
11262 format(" \t \t f(\"\t\t\"); /* some\n"
11263 " \t \t comment */",
11264 Tab));
11265 EXPECT_EQ("{\n"
11266 "\t/*\n"
11267 "\t * Comment\n"
11268 "\t */\n"
11269 "\tint i;\n"
11270 "}",
11271 format("{\n"
11272 "\t/*\n"
11273 "\t * Comment\n"
11274 "\t */\n"
11275 "\t int i;\n"
11276 "}",
11277 Tab));
11278 Tab.TabWidth = 2;
11279 Tab.IndentWidth = 2;
11280 EXPECT_EQ("{\n"
11281 "\t/* aaaa\n"
11282 "\t\t bbbb */\n"
11283 "}",
11284 format("{\n"
11285 "/* aaaa\n"
11286 "\t bbbb */\n"
11287 "}",
11288 Tab));
11289 EXPECT_EQ("{\n"
11290 "\t/*\n"
11291 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11292 "\t\tbbbbbbbbbbbbb\n"
11293 "\t*/\n"
11294 "}",
11295 format("{\n"
11296 "/*\n"
11297 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11298 "*/\n"
11299 "}",
11300 Tab));
11301 Tab.AlignConsecutiveAssignments = true;
11302 Tab.AlignConsecutiveDeclarations = true;
11303 Tab.TabWidth = 4;
11304 Tab.IndentWidth = 4;
11305 verifyFormat("class Assign {\n"
11306 "\tvoid f() {\n"
11307 "\t\tint x = 123;\n"
11308 "\t\tint random = 4;\n"
11309 "\t\tstd::string alphabet =\n"
11310 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
11311 "\t}\n"
11312 "};",
11313 Tab);
11314
11315 Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
11316 Tab.TabWidth = 8;
11317 Tab.IndentWidth = 8;
11318 EXPECT_EQ("if (aaaaaaaa && // q\n"
11319 " bb) // w\n"
11320 "\t;",
11321 format("if (aaaaaaaa &&// q\n"
11322 "bb)// w\n"
11323 ";",
11324 Tab));
11325 EXPECT_EQ("if (aaa && bbb) // w\n"
11326 "\t;",
11327 format("if(aaa&&bbb)// w\n"
11328 ";",
11329 Tab));
11330 verifyFormat("class X {\n"
11331 "\tvoid f() {\n"
11332 "\t\tsomeFunction(parameter1,\n"
11333 "\t\t parameter2);\n"
11334 "\t}\n"
11335 "};",
11336 Tab);
11337 verifyFormat("#define A \\\n"
11338 "\tvoid f() { \\\n"
11339 "\t\tsomeFunction( \\\n"
11340 "\t\t parameter1, \\\n"
11341 "\t\t parameter2); \\\n"
11342 "\t}",
11343 Tab);
11344 Tab.TabWidth = 4;
11345 Tab.IndentWidth = 8;
11346 verifyFormat("class TabWidth4Indent8 {\n"
11347 "\t\tvoid f() {\n"
11348 "\t\t\t\tsomeFunction(parameter1,\n"
11349 "\t\t\t\t parameter2);\n"
11350 "\t\t}\n"
11351 "};",
11352 Tab);
11353 Tab.TabWidth = 4;
11354 Tab.IndentWidth = 4;
11355 verifyFormat("class TabWidth4Indent4 {\n"
11356 "\tvoid f() {\n"
11357 "\t\tsomeFunction(parameter1,\n"
11358 "\t\t parameter2);\n"
11359 "\t}\n"
11360 "};",
11361 Tab);
11362 Tab.TabWidth = 8;
11363 Tab.IndentWidth = 4;
11364 verifyFormat("class TabWidth8Indent4 {\n"
11365 " void f() {\n"
11366 "\tsomeFunction(parameter1,\n"
11367 "\t parameter2);\n"
11368 " }\n"
11369 "};",
11370 Tab);
11371 Tab.TabWidth = 8;
11372 Tab.IndentWidth = 8;
11373 EXPECT_EQ("/*\n"
11374 " a\t\tcomment\n"
11375 " in multiple lines\n"
11376 " */",
11377 format(" /*\t \t \n"
11378 " \t \t a\t\tcomment\t \t\n"
11379 " \t \t in multiple lines\t\n"
11380 " \t */",
11381 Tab));
11382 verifyFormat("{\n"
11383 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11384 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11385 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11386 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11387 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11388 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11389 "};",
11390 Tab);
11391 verifyFormat("enum AA {\n"
11392 "\ta1, // Force multiple lines\n"
11393 "\ta2,\n"
11394 "\ta3\n"
11395 "};",
11396 Tab);
11397 EXPECT_EQ("if (aaaaaaaa && // q\n"
11398 " bb) // w\n"
11399 "\t;",
11400 format("if (aaaaaaaa &&// q\n"
11401 "bb)// w\n"
11402 ";",
11403 Tab));
11404 verifyFormat("class X {\n"
11405 "\tvoid f() {\n"
11406 "\t\tsomeFunction(parameter1,\n"
11407 "\t\t parameter2);\n"
11408 "\t}\n"
11409 "};",
11410 Tab);
11411 verifyFormat("{\n"
11412 "\tQ(\n"
11413 "\t {\n"
11414 "\t\t int a;\n"
11415 "\t\t someFunction(aaaaaaaa,\n"
11416 "\t\t bbbbbbb);\n"
11417 "\t },\n"
11418 "\t p);\n"
11419 "}",
11420 Tab);
11421 EXPECT_EQ("{\n"
11422 "\t/* aaaa\n"
11423 "\t bbbb */\n"
11424 "}",
11425 format("{\n"
11426 "/* aaaa\n"
11427 " bbbb */\n"
11428 "}",
11429 Tab));
11430 EXPECT_EQ("{\n"
11431 "\t/*\n"
11432 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11433 "\t bbbbbbbbbbbbb\n"
11434 "\t*/\n"
11435 "}",
11436 format("{\n"
11437 "/*\n"
11438 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11439 "*/\n"
11440 "}",
11441 Tab));
11442 EXPECT_EQ("{\n"
11443 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11444 "\t// bbbbbbbbbbbbb\n"
11445 "}",
11446 format("{\n"
11447 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11448 "}",
11449 Tab));
11450 EXPECT_EQ("{\n"
11451 "\t/*\n"
11452 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11453 "\t bbbbbbbbbbbbb\n"
11454 "\t*/\n"
11455 "}",
11456 format("{\n"
11457 "\t/*\n"
11458 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11459 "\t*/\n"
11460 "}",
11461 Tab));
11462 EXPECT_EQ("{\n"
11463 "\t/*\n"
11464 "\n"
11465 "\t*/\n"
11466 "}",
11467 format("{\n"
11468 "\t/*\n"
11469 "\n"
11470 "\t*/\n"
11471 "}",
11472 Tab));
11473 EXPECT_EQ("{\n"
11474 "\t/*\n"
11475 " asdf\n"
11476 "\t*/\n"
11477 "}",
11478 format("{\n"
11479 "\t/*\n"
11480 " asdf\n"
11481 "\t*/\n"
11482 "}",
11483 Tab));
11484 EXPECT_EQ("/* some\n"
11485 " comment */",
11486 format(" \t \t /* some\n"
11487 " \t \t comment */",
11488 Tab));
11489 EXPECT_EQ("int a; /* some\n"
11490 " comment */",
11491 format(" \t \t int a; /* some\n"
11492 " \t \t comment */",
11493 Tab));
11494 EXPECT_EQ("int a; /* some\n"
11495 "comment */",
11496 format(" \t \t int\ta; /* some\n"
11497 " \t \t comment */",
11498 Tab));
11499 EXPECT_EQ("f(\"\t\t\"); /* some\n"
11500 " comment */",
11501 format(" \t \t f(\"\t\t\"); /* some\n"
11502 " \t \t comment */",
11503 Tab));
11504 EXPECT_EQ("{\n"
11505 "\t/*\n"
11506 "\t * Comment\n"
11507 "\t */\n"
11508 "\tint i;\n"
11509 "}",
11510 format("{\n"
11511 "\t/*\n"
11512 "\t * Comment\n"
11513 "\t */\n"
11514 "\t int i;\n"
11515 "}",
11516 Tab));
11517 Tab.TabWidth = 2;
11518 Tab.IndentWidth = 2;
11519 EXPECT_EQ("{\n"
11520 "\t/* aaaa\n"
11521 "\t bbbb */\n"
11522 "}",
11523 format("{\n"
11524 "/* aaaa\n"
11525 " bbbb */\n"
11526 "}",
11527 Tab));
11528 EXPECT_EQ("{\n"
11529 "\t/*\n"
11530 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11531 "\t bbbbbbbbbbbbb\n"
11532 "\t*/\n"
11533 "}",
11534 format("{\n"
11535 "/*\n"
11536 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11537 "*/\n"
11538 "}",
11539 Tab));
11540 Tab.AlignConsecutiveAssignments = true;
11541 Tab.AlignConsecutiveDeclarations = true;
11542 Tab.TabWidth = 4;
11543 Tab.IndentWidth = 4;
11544 verifyFormat("class Assign {\n"
11545 "\tvoid f() {\n"
11546 "\t\tint x = 123;\n"
11547 "\t\tint random = 4;\n"
11548 "\t\tstd::string alphabet =\n"
11549 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
11550 "\t}\n"
11551 "};",
11552 Tab);
11553 Tab.AlignOperands = FormatStyle::OAS_Align;
11554 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
11555 " cccccccccccccccccccc;",
11556 Tab);
11557 // no alignment
11558 verifyFormat("int aaaaaaaaaa =\n"
11559 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
11560 Tab);
11561 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
11562 " : bbbbbbbbbbbbbb ? 222222222222222\n"
11563 " : 333333333333333;",
11564 Tab);
11565 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
11566 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
11567 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
11568 " + cccccccccccccccccccc;",
11569 Tab);
11570 }
11571
TEST_F(FormatTest,ZeroTabWidth)11572 TEST_F(FormatTest, ZeroTabWidth) {
11573 FormatStyle Tab = getLLVMStyleWithColumns(42);
11574 Tab.IndentWidth = 8;
11575 Tab.UseTab = FormatStyle::UT_Never;
11576 Tab.TabWidth = 0;
11577 EXPECT_EQ("void a(){\n"
11578 " // line starts with '\t'\n"
11579 "};",
11580 format("void a(){\n"
11581 "\t// line starts with '\t'\n"
11582 "};",
11583 Tab));
11584
11585 EXPECT_EQ("void a(){\n"
11586 " // line starts with '\t'\n"
11587 "};",
11588 format("void a(){\n"
11589 "\t\t// line starts with '\t'\n"
11590 "};",
11591 Tab));
11592
11593 Tab.UseTab = FormatStyle::UT_ForIndentation;
11594 EXPECT_EQ("void a(){\n"
11595 " // line starts with '\t'\n"
11596 "};",
11597 format("void a(){\n"
11598 "\t// line starts with '\t'\n"
11599 "};",
11600 Tab));
11601
11602 EXPECT_EQ("void a(){\n"
11603 " // line starts with '\t'\n"
11604 "};",
11605 format("void a(){\n"
11606 "\t\t// line starts with '\t'\n"
11607 "};",
11608 Tab));
11609
11610 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
11611 EXPECT_EQ("void a(){\n"
11612 " // line starts with '\t'\n"
11613 "};",
11614 format("void a(){\n"
11615 "\t// line starts with '\t'\n"
11616 "};",
11617 Tab));
11618
11619 EXPECT_EQ("void a(){\n"
11620 " // line starts with '\t'\n"
11621 "};",
11622 format("void a(){\n"
11623 "\t\t// line starts with '\t'\n"
11624 "};",
11625 Tab));
11626
11627 Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
11628 EXPECT_EQ("void a(){\n"
11629 " // line starts with '\t'\n"
11630 "};",
11631 format("void a(){\n"
11632 "\t// line starts with '\t'\n"
11633 "};",
11634 Tab));
11635
11636 EXPECT_EQ("void a(){\n"
11637 " // line starts with '\t'\n"
11638 "};",
11639 format("void a(){\n"
11640 "\t\t// line starts with '\t'\n"
11641 "};",
11642 Tab));
11643
11644 Tab.UseTab = FormatStyle::UT_Always;
11645 EXPECT_EQ("void a(){\n"
11646 "// line starts with '\t'\n"
11647 "};",
11648 format("void a(){\n"
11649 "\t// line starts with '\t'\n"
11650 "};",
11651 Tab));
11652
11653 EXPECT_EQ("void a(){\n"
11654 "// line starts with '\t'\n"
11655 "};",
11656 format("void a(){\n"
11657 "\t\t// line starts with '\t'\n"
11658 "};",
11659 Tab));
11660 }
11661
TEST_F(FormatTest,CalculatesOriginalColumn)11662 TEST_F(FormatTest, CalculatesOriginalColumn) {
11663 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
11664 "q\"; /* some\n"
11665 " comment */",
11666 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
11667 "q\"; /* some\n"
11668 " comment */",
11669 getLLVMStyle()));
11670 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
11671 "/* some\n"
11672 " comment */",
11673 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
11674 " /* some\n"
11675 " comment */",
11676 getLLVMStyle()));
11677 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
11678 "qqq\n"
11679 "/* some\n"
11680 " comment */",
11681 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
11682 "qqq\n"
11683 " /* some\n"
11684 " comment */",
11685 getLLVMStyle()));
11686 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
11687 "wwww; /* some\n"
11688 " comment */",
11689 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
11690 "wwww; /* some\n"
11691 " comment */",
11692 getLLVMStyle()));
11693 }
11694
TEST_F(FormatTest,ConfigurableSpaceBeforeParens)11695 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
11696 FormatStyle NoSpace = getLLVMStyle();
11697 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
11698
11699 verifyFormat("while(true)\n"
11700 " continue;",
11701 NoSpace);
11702 verifyFormat("for(;;)\n"
11703 " continue;",
11704 NoSpace);
11705 verifyFormat("if(true)\n"
11706 " f();\n"
11707 "else if(true)\n"
11708 " f();",
11709 NoSpace);
11710 verifyFormat("do {\n"
11711 " do_something();\n"
11712 "} while(something());",
11713 NoSpace);
11714 verifyFormat("switch(x) {\n"
11715 "default:\n"
11716 " break;\n"
11717 "}",
11718 NoSpace);
11719 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
11720 verifyFormat("size_t x = sizeof(x);", NoSpace);
11721 verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
11722 verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
11723 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
11724 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
11725 verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
11726 verifyFormat("alignas(128) char a[128];", NoSpace);
11727 verifyFormat("size_t x = alignof(MyType);", NoSpace);
11728 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
11729 verifyFormat("int f() throw(Deprecated);", NoSpace);
11730 verifyFormat("typedef void (*cb)(int);", NoSpace);
11731 verifyFormat("T A::operator()();", NoSpace);
11732 verifyFormat("X A::operator++(T);", NoSpace);
11733 verifyFormat("auto lambda = []() { return 0; };", NoSpace);
11734
11735 FormatStyle Space = getLLVMStyle();
11736 Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
11737
11738 verifyFormat("int f ();", Space);
11739 verifyFormat("void f (int a, T b) {\n"
11740 " while (true)\n"
11741 " continue;\n"
11742 "}",
11743 Space);
11744 verifyFormat("if (true)\n"
11745 " f ();\n"
11746 "else if (true)\n"
11747 " f ();",
11748 Space);
11749 verifyFormat("do {\n"
11750 " do_something ();\n"
11751 "} while (something ());",
11752 Space);
11753 verifyFormat("switch (x) {\n"
11754 "default:\n"
11755 " break;\n"
11756 "}",
11757 Space);
11758 verifyFormat("A::A () : a (1) {}", Space);
11759 verifyFormat("void f () __attribute__ ((asdf));", Space);
11760 verifyFormat("*(&a + 1);\n"
11761 "&((&a)[1]);\n"
11762 "a[(b + c) * d];\n"
11763 "(((a + 1) * 2) + 3) * 4;",
11764 Space);
11765 verifyFormat("#define A(x) x", Space);
11766 verifyFormat("#define A (x) x", Space);
11767 verifyFormat("#if defined(x)\n"
11768 "#endif",
11769 Space);
11770 verifyFormat("auto i = std::make_unique<int> (5);", Space);
11771 verifyFormat("size_t x = sizeof (x);", Space);
11772 verifyFormat("auto f (int x) -> decltype (x);", Space);
11773 verifyFormat("auto f (int x) -> typeof (x);", Space);
11774 verifyFormat("auto f (int x) -> _Atomic (x);", Space);
11775 verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
11776 verifyFormat("int f (T x) noexcept (x.create ());", Space);
11777 verifyFormat("alignas (128) char a[128];", Space);
11778 verifyFormat("size_t x = alignof (MyType);", Space);
11779 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
11780 verifyFormat("int f () throw (Deprecated);", Space);
11781 verifyFormat("typedef void (*cb) (int);", Space);
11782 verifyFormat("T A::operator() ();", Space);
11783 verifyFormat("X A::operator++ (T);", Space);
11784 verifyFormat("auto lambda = [] () { return 0; };", Space);
11785 verifyFormat("int x = int (y);", Space);
11786
11787 FormatStyle SomeSpace = getLLVMStyle();
11788 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
11789
11790 verifyFormat("[]() -> float {}", SomeSpace);
11791 verifyFormat("[] (auto foo) {}", SomeSpace);
11792 verifyFormat("[foo]() -> int {}", SomeSpace);
11793 verifyFormat("int f();", SomeSpace);
11794 verifyFormat("void f (int a, T b) {\n"
11795 " while (true)\n"
11796 " continue;\n"
11797 "}",
11798 SomeSpace);
11799 verifyFormat("if (true)\n"
11800 " f();\n"
11801 "else if (true)\n"
11802 " f();",
11803 SomeSpace);
11804 verifyFormat("do {\n"
11805 " do_something();\n"
11806 "} while (something());",
11807 SomeSpace);
11808 verifyFormat("switch (x) {\n"
11809 "default:\n"
11810 " break;\n"
11811 "}",
11812 SomeSpace);
11813 verifyFormat("A::A() : a (1) {}", SomeSpace);
11814 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
11815 verifyFormat("*(&a + 1);\n"
11816 "&((&a)[1]);\n"
11817 "a[(b + c) * d];\n"
11818 "(((a + 1) * 2) + 3) * 4;",
11819 SomeSpace);
11820 verifyFormat("#define A(x) x", SomeSpace);
11821 verifyFormat("#define A (x) x", SomeSpace);
11822 verifyFormat("#if defined(x)\n"
11823 "#endif",
11824 SomeSpace);
11825 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
11826 verifyFormat("size_t x = sizeof (x);", SomeSpace);
11827 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
11828 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
11829 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
11830 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
11831 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
11832 verifyFormat("alignas (128) char a[128];", SomeSpace);
11833 verifyFormat("size_t x = alignof (MyType);", SomeSpace);
11834 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
11835 SomeSpace);
11836 verifyFormat("int f() throw (Deprecated);", SomeSpace);
11837 verifyFormat("typedef void (*cb) (int);", SomeSpace);
11838 verifyFormat("T A::operator()();", SomeSpace);
11839 verifyFormat("X A::operator++ (T);", SomeSpace);
11840 verifyFormat("int x = int (y);", SomeSpace);
11841 verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
11842 }
11843
TEST_F(FormatTest,SpaceAfterLogicalNot)11844 TEST_F(FormatTest, SpaceAfterLogicalNot) {
11845 FormatStyle Spaces = getLLVMStyle();
11846 Spaces.SpaceAfterLogicalNot = true;
11847
11848 verifyFormat("bool x = ! y", Spaces);
11849 verifyFormat("if (! isFailure())", Spaces);
11850 verifyFormat("if (! (a && b))", Spaces);
11851 verifyFormat("\"Error!\"", Spaces);
11852 verifyFormat("! ! x", Spaces);
11853 }
11854
TEST_F(FormatTest,ConfigurableSpacesInParentheses)11855 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
11856 FormatStyle Spaces = getLLVMStyle();
11857
11858 Spaces.SpacesInParentheses = true;
11859 verifyFormat("do_something( ::globalVar );", Spaces);
11860 verifyFormat("call( x, y, z );", Spaces);
11861 verifyFormat("call();", Spaces);
11862 verifyFormat("std::function<void( int, int )> callback;", Spaces);
11863 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
11864 Spaces);
11865 verifyFormat("while ( (bool)1 )\n"
11866 " continue;",
11867 Spaces);
11868 verifyFormat("for ( ;; )\n"
11869 " continue;",
11870 Spaces);
11871 verifyFormat("if ( true )\n"
11872 " f();\n"
11873 "else if ( true )\n"
11874 " f();",
11875 Spaces);
11876 verifyFormat("do {\n"
11877 " do_something( (int)i );\n"
11878 "} while ( something() );",
11879 Spaces);
11880 verifyFormat("switch ( x ) {\n"
11881 "default:\n"
11882 " break;\n"
11883 "}",
11884 Spaces);
11885
11886 Spaces.SpacesInParentheses = false;
11887 Spaces.SpacesInCStyleCastParentheses = true;
11888 verifyFormat("Type *A = ( Type * )P;", Spaces);
11889 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
11890 verifyFormat("x = ( int32 )y;", Spaces);
11891 verifyFormat("int a = ( int )(2.0f);", Spaces);
11892 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
11893 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
11894 verifyFormat("#define x (( int )-1)", Spaces);
11895
11896 // Run the first set of tests again with:
11897 Spaces.SpacesInParentheses = false;
11898 Spaces.SpaceInEmptyParentheses = true;
11899 Spaces.SpacesInCStyleCastParentheses = true;
11900 verifyFormat("call(x, y, z);", Spaces);
11901 verifyFormat("call( );", Spaces);
11902 verifyFormat("std::function<void(int, int)> callback;", Spaces);
11903 verifyFormat("while (( bool )1)\n"
11904 " continue;",
11905 Spaces);
11906 verifyFormat("for (;;)\n"
11907 " continue;",
11908 Spaces);
11909 verifyFormat("if (true)\n"
11910 " f( );\n"
11911 "else if (true)\n"
11912 " f( );",
11913 Spaces);
11914 verifyFormat("do {\n"
11915 " do_something(( int )i);\n"
11916 "} while (something( ));",
11917 Spaces);
11918 verifyFormat("switch (x) {\n"
11919 "default:\n"
11920 " break;\n"
11921 "}",
11922 Spaces);
11923
11924 // Run the first set of tests again with:
11925 Spaces.SpaceAfterCStyleCast = true;
11926 verifyFormat("call(x, y, z);", Spaces);
11927 verifyFormat("call( );", Spaces);
11928 verifyFormat("std::function<void(int, int)> callback;", Spaces);
11929 verifyFormat("while (( bool ) 1)\n"
11930 " continue;",
11931 Spaces);
11932 verifyFormat("for (;;)\n"
11933 " continue;",
11934 Spaces);
11935 verifyFormat("if (true)\n"
11936 " f( );\n"
11937 "else if (true)\n"
11938 " f( );",
11939 Spaces);
11940 verifyFormat("do {\n"
11941 " do_something(( int ) i);\n"
11942 "} while (something( ));",
11943 Spaces);
11944 verifyFormat("switch (x) {\n"
11945 "default:\n"
11946 " break;\n"
11947 "}",
11948 Spaces);
11949
11950 // Run subset of tests again with:
11951 Spaces.SpacesInCStyleCastParentheses = false;
11952 Spaces.SpaceAfterCStyleCast = true;
11953 verifyFormat("while ((bool) 1)\n"
11954 " continue;",
11955 Spaces);
11956 verifyFormat("do {\n"
11957 " do_something((int) i);\n"
11958 "} while (something( ));",
11959 Spaces);
11960 }
11961
TEST_F(FormatTest,ConfigurableSpacesInSquareBrackets)11962 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
11963 verifyFormat("int a[5];");
11964 verifyFormat("a[3] += 42;");
11965
11966 FormatStyle Spaces = getLLVMStyle();
11967 Spaces.SpacesInSquareBrackets = true;
11968 // Not lambdas.
11969 verifyFormat("int a[ 5 ];", Spaces);
11970 verifyFormat("a[ 3 ] += 42;", Spaces);
11971 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
11972 verifyFormat("double &operator[](int i) { return 0; }\n"
11973 "int i;",
11974 Spaces);
11975 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
11976 verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
11977 verifyFormat("int i = (*b)[ a ]->f();", Spaces);
11978 // Lambdas.
11979 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
11980 verifyFormat("return [ i, args... ] {};", Spaces);
11981 verifyFormat("int foo = [ &bar ]() {};", Spaces);
11982 verifyFormat("int foo = [ = ]() {};", Spaces);
11983 verifyFormat("int foo = [ & ]() {};", Spaces);
11984 verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
11985 verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
11986 }
11987
TEST_F(FormatTest,ConfigurableSpaceBeforeBrackets)11988 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
11989 FormatStyle NoSpaceStyle = getLLVMStyle();
11990 verifyFormat("int a[5];", NoSpaceStyle);
11991 verifyFormat("a[3] += 42;", NoSpaceStyle);
11992
11993 verifyFormat("int a[1];", NoSpaceStyle);
11994 verifyFormat("int 1 [a];", NoSpaceStyle);
11995 verifyFormat("int a[1][2];", NoSpaceStyle);
11996 verifyFormat("a[7] = 5;", NoSpaceStyle);
11997 verifyFormat("int a = (f())[23];", NoSpaceStyle);
11998 verifyFormat("f([] {})", NoSpaceStyle);
11999
12000 FormatStyle Space = getLLVMStyle();
12001 Space.SpaceBeforeSquareBrackets = true;
12002 verifyFormat("int c = []() -> int { return 2; }();\n", Space);
12003 verifyFormat("return [i, args...] {};", Space);
12004
12005 verifyFormat("int a [5];", Space);
12006 verifyFormat("a [3] += 42;", Space);
12007 verifyFormat("constexpr char hello []{\"hello\"};", Space);
12008 verifyFormat("double &operator[](int i) { return 0; }\n"
12009 "int i;",
12010 Space);
12011 verifyFormat("std::unique_ptr<int []> foo() {}", Space);
12012 verifyFormat("int i = a [a][a]->f();", Space);
12013 verifyFormat("int i = (*b) [a]->f();", Space);
12014
12015 verifyFormat("int a [1];", Space);
12016 verifyFormat("int 1 [a];", Space);
12017 verifyFormat("int a [1][2];", Space);
12018 verifyFormat("a [7] = 5;", Space);
12019 verifyFormat("int a = (f()) [23];", Space);
12020 verifyFormat("f([] {})", Space);
12021 }
12022
TEST_F(FormatTest,ConfigurableSpaceBeforeAssignmentOperators)12023 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
12024 verifyFormat("int a = 5;");
12025 verifyFormat("a += 42;");
12026 verifyFormat("a or_eq 8;");
12027
12028 FormatStyle Spaces = getLLVMStyle();
12029 Spaces.SpaceBeforeAssignmentOperators = false;
12030 verifyFormat("int a= 5;", Spaces);
12031 verifyFormat("a+= 42;", Spaces);
12032 verifyFormat("a or_eq 8;", Spaces);
12033 }
12034
TEST_F(FormatTest,ConfigurableSpaceBeforeColon)12035 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
12036 verifyFormat("class Foo : public Bar {};");
12037 verifyFormat("Foo::Foo() : foo(1) {}");
12038 verifyFormat("for (auto a : b) {\n}");
12039 verifyFormat("int x = a ? b : c;");
12040 verifyFormat("{\n"
12041 "label0:\n"
12042 " int x = 0;\n"
12043 "}");
12044 verifyFormat("switch (x) {\n"
12045 "case 1:\n"
12046 "default:\n"
12047 "}");
12048
12049 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
12050 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
12051 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
12052 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
12053 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
12054 verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
12055 verifyFormat("{\n"
12056 "label1:\n"
12057 " int x = 0;\n"
12058 "}",
12059 CtorInitializerStyle);
12060 verifyFormat("switch (x) {\n"
12061 "case 1:\n"
12062 "default:\n"
12063 "}",
12064 CtorInitializerStyle);
12065 CtorInitializerStyle.BreakConstructorInitializers =
12066 FormatStyle::BCIS_AfterColon;
12067 verifyFormat("Fooooooooooo::Fooooooooooo():\n"
12068 " aaaaaaaaaaaaaaaa(1),\n"
12069 " bbbbbbbbbbbbbbbb(2) {}",
12070 CtorInitializerStyle);
12071 CtorInitializerStyle.BreakConstructorInitializers =
12072 FormatStyle::BCIS_BeforeComma;
12073 verifyFormat("Fooooooooooo::Fooooooooooo()\n"
12074 " : aaaaaaaaaaaaaaaa(1)\n"
12075 " , bbbbbbbbbbbbbbbb(2) {}",
12076 CtorInitializerStyle);
12077 CtorInitializerStyle.BreakConstructorInitializers =
12078 FormatStyle::BCIS_BeforeColon;
12079 verifyFormat("Fooooooooooo::Fooooooooooo()\n"
12080 " : aaaaaaaaaaaaaaaa(1),\n"
12081 " bbbbbbbbbbbbbbbb(2) {}",
12082 CtorInitializerStyle);
12083 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
12084 verifyFormat("Fooooooooooo::Fooooooooooo()\n"
12085 ": aaaaaaaaaaaaaaaa(1),\n"
12086 " bbbbbbbbbbbbbbbb(2) {}",
12087 CtorInitializerStyle);
12088
12089 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
12090 InheritanceStyle.SpaceBeforeInheritanceColon = false;
12091 verifyFormat("class Foo: public Bar {};", InheritanceStyle);
12092 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
12093 verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
12094 verifyFormat("int x = a ? b : c;", InheritanceStyle);
12095 verifyFormat("{\n"
12096 "label2:\n"
12097 " int x = 0;\n"
12098 "}",
12099 InheritanceStyle);
12100 verifyFormat("switch (x) {\n"
12101 "case 1:\n"
12102 "default:\n"
12103 "}",
12104 InheritanceStyle);
12105 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
12106 verifyFormat("class Foooooooooooooooooooooo:\n"
12107 " public aaaaaaaaaaaaaaaaaa,\n"
12108 " public bbbbbbbbbbbbbbbbbb {\n"
12109 "}",
12110 InheritanceStyle);
12111 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
12112 verifyFormat("class Foooooooooooooooooooooo\n"
12113 " : public aaaaaaaaaaaaaaaaaa\n"
12114 " , public bbbbbbbbbbbbbbbbbb {\n"
12115 "}",
12116 InheritanceStyle);
12117 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
12118 verifyFormat("class Foooooooooooooooooooooo\n"
12119 " : public aaaaaaaaaaaaaaaaaa,\n"
12120 " public bbbbbbbbbbbbbbbbbb {\n"
12121 "}",
12122 InheritanceStyle);
12123 InheritanceStyle.ConstructorInitializerIndentWidth = 0;
12124 verifyFormat("class Foooooooooooooooooooooo\n"
12125 ": public aaaaaaaaaaaaaaaaaa,\n"
12126 " public bbbbbbbbbbbbbbbbbb {}",
12127 InheritanceStyle);
12128
12129 FormatStyle ForLoopStyle = getLLVMStyle();
12130 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
12131 verifyFormat("class Foo : public Bar {};", ForLoopStyle);
12132 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
12133 verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
12134 verifyFormat("int x = a ? b : c;", ForLoopStyle);
12135 verifyFormat("{\n"
12136 "label2:\n"
12137 " int x = 0;\n"
12138 "}",
12139 ForLoopStyle);
12140 verifyFormat("switch (x) {\n"
12141 "case 1:\n"
12142 "default:\n"
12143 "}",
12144 ForLoopStyle);
12145
12146 FormatStyle NoSpaceStyle = getLLVMStyle();
12147 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
12148 NoSpaceStyle.SpaceBeforeInheritanceColon = false;
12149 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
12150 verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
12151 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
12152 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
12153 verifyFormat("int x = a ? b : c;", NoSpaceStyle);
12154 verifyFormat("{\n"
12155 "label3:\n"
12156 " int x = 0;\n"
12157 "}",
12158 NoSpaceStyle);
12159 verifyFormat("switch (x) {\n"
12160 "case 1:\n"
12161 "default:\n"
12162 "}",
12163 NoSpaceStyle);
12164 }
12165
TEST_F(FormatTest,ConfigurableSpaceAroundPointerQualifiers)12166 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
12167 FormatStyle Style = getLLVMStyle();
12168
12169 Style.PointerAlignment = FormatStyle::PAS_Left;
12170 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
12171 verifyFormat("void* const* x = NULL;", Style);
12172
12173 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \
12174 do { \
12175 Style.PointerAlignment = FormatStyle::Pointers; \
12176 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \
12177 verifyFormat(Code, Style); \
12178 } while (false)
12179
12180 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
12181 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
12182 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
12183
12184 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
12185 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
12186 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
12187
12188 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
12189 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
12190 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
12191
12192 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
12193 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
12194 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
12195
12196 #undef verifyQualifierSpaces
12197
12198 FormatStyle Spaces = getLLVMStyle();
12199 Spaces.AttributeMacros.push_back("qualified");
12200 Spaces.PointerAlignment = FormatStyle::PAS_Right;
12201 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
12202 verifyFormat("SomeType *volatile *a = NULL;", Spaces);
12203 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
12204 verifyFormat("std::vector<SomeType *const *> x;", Spaces);
12205 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
12206 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12207 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
12208 verifyFormat("SomeType * volatile *a = NULL;", Spaces);
12209 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
12210 verifyFormat("std::vector<SomeType * const *> x;", Spaces);
12211 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
12212 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12213
12214 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
12215 Spaces.PointerAlignment = FormatStyle::PAS_Left;
12216 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
12217 verifyFormat("SomeType* volatile* a = NULL;", Spaces);
12218 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
12219 verifyFormat("std::vector<SomeType* const*> x;", Spaces);
12220 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
12221 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12222 // However, setting it to SAPQ_After should add spaces after __attribute, etc.
12223 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
12224 verifyFormat("SomeType* volatile * a = NULL;", Spaces);
12225 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
12226 verifyFormat("std::vector<SomeType* const *> x;", Spaces);
12227 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
12228 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12229
12230 // PAS_Middle should not have any noticeable changes even for SAPQ_Both
12231 Spaces.PointerAlignment = FormatStyle::PAS_Middle;
12232 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
12233 verifyFormat("SomeType * volatile * a = NULL;", Spaces);
12234 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
12235 verifyFormat("std::vector<SomeType * const *> x;", Spaces);
12236 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
12237 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12238 }
12239
TEST_F(FormatTest,AlignConsecutiveMacros)12240 TEST_F(FormatTest, AlignConsecutiveMacros) {
12241 FormatStyle Style = getLLVMStyle();
12242 Style.AlignConsecutiveAssignments = true;
12243 Style.AlignConsecutiveDeclarations = true;
12244 Style.AlignConsecutiveMacros = false;
12245
12246 verifyFormat("#define a 3\n"
12247 "#define bbbb 4\n"
12248 "#define ccc (5)",
12249 Style);
12250
12251 verifyFormat("#define f(x) (x * x)\n"
12252 "#define fff(x, y, z) (x * y + z)\n"
12253 "#define ffff(x, y) (x - y)",
12254 Style);
12255
12256 verifyFormat("#define foo(x, y) (x + y)\n"
12257 "#define bar (5, 6)(2 + 2)",
12258 Style);
12259
12260 verifyFormat("#define a 3\n"
12261 "#define bbbb 4\n"
12262 "#define ccc (5)\n"
12263 "#define f(x) (x * x)\n"
12264 "#define fff(x, y, z) (x * y + z)\n"
12265 "#define ffff(x, y) (x - y)",
12266 Style);
12267
12268 Style.AlignConsecutiveMacros = true;
12269 verifyFormat("#define a 3\n"
12270 "#define bbbb 4\n"
12271 "#define ccc (5)",
12272 Style);
12273
12274 verifyFormat("#define f(x) (x * x)\n"
12275 "#define fff(x, y, z) (x * y + z)\n"
12276 "#define ffff(x, y) (x - y)",
12277 Style);
12278
12279 verifyFormat("#define foo(x, y) (x + y)\n"
12280 "#define bar (5, 6)(2 + 2)",
12281 Style);
12282
12283 verifyFormat("#define a 3\n"
12284 "#define bbbb 4\n"
12285 "#define ccc (5)\n"
12286 "#define f(x) (x * x)\n"
12287 "#define fff(x, y, z) (x * y + z)\n"
12288 "#define ffff(x, y) (x - y)",
12289 Style);
12290
12291 verifyFormat("#define a 5\n"
12292 "#define foo(x, y) (x + y)\n"
12293 "#define CCC (6)\n"
12294 "auto lambda = []() {\n"
12295 " auto ii = 0;\n"
12296 " float j = 0;\n"
12297 " return 0;\n"
12298 "};\n"
12299 "int i = 0;\n"
12300 "float i2 = 0;\n"
12301 "auto v = type{\n"
12302 " i = 1, //\n"
12303 " (i = 2), //\n"
12304 " i = 3 //\n"
12305 "};",
12306 Style);
12307
12308 Style.AlignConsecutiveMacros = false;
12309 Style.ColumnLimit = 20;
12310
12311 verifyFormat("#define a \\\n"
12312 " \"aabbbbbbbbbbbb\"\n"
12313 "#define D \\\n"
12314 " \"aabbbbbbbbbbbb\" \\\n"
12315 " \"ccddeeeeeeeee\"\n"
12316 "#define B \\\n"
12317 " \"QQQQQQQQQQQQQ\" \\\n"
12318 " \"FFFFFFFFFFFFF\" \\\n"
12319 " \"LLLLLLLL\"\n",
12320 Style);
12321
12322 Style.AlignConsecutiveMacros = true;
12323 verifyFormat("#define a \\\n"
12324 " \"aabbbbbbbbbbbb\"\n"
12325 "#define D \\\n"
12326 " \"aabbbbbbbbbbbb\" \\\n"
12327 " \"ccddeeeeeeeee\"\n"
12328 "#define B \\\n"
12329 " \"QQQQQQQQQQQQQ\" \\\n"
12330 " \"FFFFFFFFFFFFF\" \\\n"
12331 " \"LLLLLLLL\"\n",
12332 Style);
12333 }
12334
TEST_F(FormatTest,AlignConsecutiveAssignments)12335 TEST_F(FormatTest, AlignConsecutiveAssignments) {
12336 FormatStyle Alignment = getLLVMStyle();
12337 Alignment.AlignConsecutiveMacros = true;
12338 Alignment.AlignConsecutiveAssignments = false;
12339 verifyFormat("int a = 5;\n"
12340 "int oneTwoThree = 123;",
12341 Alignment);
12342 verifyFormat("int a = 5;\n"
12343 "int oneTwoThree = 123;",
12344 Alignment);
12345
12346 Alignment.AlignConsecutiveAssignments = true;
12347 verifyFormat("int a = 5;\n"
12348 "int oneTwoThree = 123;",
12349 Alignment);
12350 verifyFormat("int a = method();\n"
12351 "int oneTwoThree = 133;",
12352 Alignment);
12353 verifyFormat("a &= 5;\n"
12354 "bcd *= 5;\n"
12355 "ghtyf += 5;\n"
12356 "dvfvdb -= 5;\n"
12357 "a /= 5;\n"
12358 "vdsvsv %= 5;\n"
12359 "sfdbddfbdfbb ^= 5;\n"
12360 "dvsdsv |= 5;\n"
12361 "int dsvvdvsdvvv = 123;",
12362 Alignment);
12363 verifyFormat("int i = 1, j = 10;\n"
12364 "something = 2000;",
12365 Alignment);
12366 verifyFormat("something = 2000;\n"
12367 "int i = 1, j = 10;\n",
12368 Alignment);
12369 verifyFormat("something = 2000;\n"
12370 "another = 911;\n"
12371 "int i = 1, j = 10;\n"
12372 "oneMore = 1;\n"
12373 "i = 2;",
12374 Alignment);
12375 verifyFormat("int a = 5;\n"
12376 "int one = 1;\n"
12377 "method();\n"
12378 "int oneTwoThree = 123;\n"
12379 "int oneTwo = 12;",
12380 Alignment);
12381 verifyFormat("int oneTwoThree = 123;\n"
12382 "int oneTwo = 12;\n"
12383 "method();\n",
12384 Alignment);
12385 verifyFormat("int oneTwoThree = 123; // comment\n"
12386 "int oneTwo = 12; // comment",
12387 Alignment);
12388
12389 // Bug 25167
12390 /* Uncomment when fixed
12391 verifyFormat("#if A\n"
12392 "#else\n"
12393 "int aaaaaaaa = 12;\n"
12394 "#endif\n"
12395 "#if B\n"
12396 "#else\n"
12397 "int a = 12;\n"
12398 "#endif\n",
12399 Alignment);
12400 verifyFormat("enum foo {\n"
12401 "#if A\n"
12402 "#else\n"
12403 " aaaaaaaa = 12;\n"
12404 "#endif\n"
12405 "#if B\n"
12406 "#else\n"
12407 " a = 12;\n"
12408 "#endif\n"
12409 "};\n",
12410 Alignment);
12411 */
12412
12413 EXPECT_EQ("int a = 5;\n"
12414 "\n"
12415 "int oneTwoThree = 123;",
12416 format("int a = 5;\n"
12417 "\n"
12418 "int oneTwoThree= 123;",
12419 Alignment));
12420 EXPECT_EQ("int a = 5;\n"
12421 "int one = 1;\n"
12422 "\n"
12423 "int oneTwoThree = 123;",
12424 format("int a = 5;\n"
12425 "int one = 1;\n"
12426 "\n"
12427 "int oneTwoThree = 123;",
12428 Alignment));
12429 EXPECT_EQ("int a = 5;\n"
12430 "int one = 1;\n"
12431 "\n"
12432 "int oneTwoThree = 123;\n"
12433 "int oneTwo = 12;",
12434 format("int a = 5;\n"
12435 "int one = 1;\n"
12436 "\n"
12437 "int oneTwoThree = 123;\n"
12438 "int oneTwo = 12;",
12439 Alignment));
12440 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
12441 verifyFormat("#define A \\\n"
12442 " int aaaa = 12; \\\n"
12443 " int b = 23; \\\n"
12444 " int ccc = 234; \\\n"
12445 " int dddddddddd = 2345;",
12446 Alignment);
12447 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12448 verifyFormat("#define A \\\n"
12449 " int aaaa = 12; \\\n"
12450 " int b = 23; \\\n"
12451 " int ccc = 234; \\\n"
12452 " int dddddddddd = 2345;",
12453 Alignment);
12454 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
12455 verifyFormat("#define A "
12456 " \\\n"
12457 " int aaaa = 12; "
12458 " \\\n"
12459 " int b = 23; "
12460 " \\\n"
12461 " int ccc = 234; "
12462 " \\\n"
12463 " int dddddddddd = 2345;",
12464 Alignment);
12465 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
12466 "k = 4, int l = 5,\n"
12467 " int m = 6) {\n"
12468 " int j = 10;\n"
12469 " otherThing = 1;\n"
12470 "}",
12471 Alignment);
12472 verifyFormat("void SomeFunction(int parameter = 0) {\n"
12473 " int i = 1;\n"
12474 " int j = 2;\n"
12475 " int big = 10000;\n"
12476 "}",
12477 Alignment);
12478 verifyFormat("class C {\n"
12479 "public:\n"
12480 " int i = 1;\n"
12481 " virtual void f() = 0;\n"
12482 "};",
12483 Alignment);
12484 verifyFormat("int i = 1;\n"
12485 "if (SomeType t = getSomething()) {\n"
12486 "}\n"
12487 "int j = 2;\n"
12488 "int big = 10000;",
12489 Alignment);
12490 verifyFormat("int j = 7;\n"
12491 "for (int k = 0; k < N; ++k) {\n"
12492 "}\n"
12493 "int j = 2;\n"
12494 "int big = 10000;\n"
12495 "}",
12496 Alignment);
12497 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
12498 verifyFormat("int i = 1;\n"
12499 "LooooooooooongType loooooooooooooooooooooongVariable\n"
12500 " = someLooooooooooooooooongFunction();\n"
12501 "int j = 2;",
12502 Alignment);
12503 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
12504 verifyFormat("int i = 1;\n"
12505 "LooooooooooongType loooooooooooooooooooooongVariable =\n"
12506 " someLooooooooooooooooongFunction();\n"
12507 "int j = 2;",
12508 Alignment);
12509
12510 verifyFormat("auto lambda = []() {\n"
12511 " auto i = 0;\n"
12512 " return 0;\n"
12513 "};\n"
12514 "int i = 0;\n"
12515 "auto v = type{\n"
12516 " i = 1, //\n"
12517 " (i = 2), //\n"
12518 " i = 3 //\n"
12519 "};",
12520 Alignment);
12521
12522 verifyFormat(
12523 "int i = 1;\n"
12524 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
12525 " loooooooooooooooooooooongParameterB);\n"
12526 "int j = 2;",
12527 Alignment);
12528
12529 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
12530 " typename B = very_long_type_name_1,\n"
12531 " typename T_2 = very_long_type_name_2>\n"
12532 "auto foo() {}\n",
12533 Alignment);
12534 verifyFormat("int a, b = 1;\n"
12535 "int c = 2;\n"
12536 "int dd = 3;\n",
12537 Alignment);
12538 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
12539 "float b[1][] = {{3.f}};\n",
12540 Alignment);
12541 verifyFormat("for (int i = 0; i < 1; i++)\n"
12542 " int x = 1;\n",
12543 Alignment);
12544 verifyFormat("for (i = 0; i < 1; i++)\n"
12545 " x = 1;\n"
12546 "y = 1;\n",
12547 Alignment);
12548
12549 Alignment.ReflowComments = true;
12550 Alignment.ColumnLimit = 50;
12551 EXPECT_EQ("int x = 0;\n"
12552 "int yy = 1; /// specificlennospace\n"
12553 "int zzz = 2;\n",
12554 format("int x = 0;\n"
12555 "int yy = 1; ///specificlennospace\n"
12556 "int zzz = 2;\n",
12557 Alignment));
12558 }
12559
TEST_F(FormatTest,AlignConsecutiveBitFields)12560 TEST_F(FormatTest, AlignConsecutiveBitFields) {
12561 FormatStyle Alignment = getLLVMStyle();
12562 Alignment.AlignConsecutiveBitFields = true;
12563 verifyFormat("int const a : 5;\n"
12564 "int oneTwoThree : 23;",
12565 Alignment);
12566
12567 // Initializers are allowed starting with c++2a
12568 verifyFormat("int const a : 5 = 1;\n"
12569 "int oneTwoThree : 23 = 0;",
12570 Alignment);
12571
12572 Alignment.AlignConsecutiveDeclarations = true;
12573 verifyFormat("int const a : 5;\n"
12574 "int oneTwoThree : 23;",
12575 Alignment);
12576
12577 verifyFormat("int const a : 5; // comment\n"
12578 "int oneTwoThree : 23; // comment",
12579 Alignment);
12580
12581 verifyFormat("int const a : 5 = 1;\n"
12582 "int oneTwoThree : 23 = 0;",
12583 Alignment);
12584
12585 Alignment.AlignConsecutiveAssignments = true;
12586 verifyFormat("int const a : 5 = 1;\n"
12587 "int oneTwoThree : 23 = 0;",
12588 Alignment);
12589 verifyFormat("int const a : 5 = {1};\n"
12590 "int oneTwoThree : 23 = 0;",
12591 Alignment);
12592
12593 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
12594 verifyFormat("int const a :5;\n"
12595 "int oneTwoThree:23;",
12596 Alignment);
12597
12598 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
12599 verifyFormat("int const a :5;\n"
12600 "int oneTwoThree :23;",
12601 Alignment);
12602
12603 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
12604 verifyFormat("int const a : 5;\n"
12605 "int oneTwoThree: 23;",
12606 Alignment);
12607
12608 // Known limitations: ':' is only recognized as a bitfield colon when
12609 // followed by a number.
12610 /*
12611 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
12612 "int a : 5;",
12613 Alignment);
12614 */
12615 }
12616
TEST_F(FormatTest,AlignConsecutiveDeclarations)12617 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
12618 FormatStyle Alignment = getLLVMStyle();
12619 Alignment.AlignConsecutiveMacros = true;
12620 Alignment.AlignConsecutiveDeclarations = false;
12621 verifyFormat("float const a = 5;\n"
12622 "int oneTwoThree = 123;",
12623 Alignment);
12624 verifyFormat("int a = 5;\n"
12625 "float const oneTwoThree = 123;",
12626 Alignment);
12627
12628 Alignment.AlignConsecutiveDeclarations = true;
12629 verifyFormat("float const a = 5;\n"
12630 "int oneTwoThree = 123;",
12631 Alignment);
12632 verifyFormat("int a = method();\n"
12633 "float const oneTwoThree = 133;",
12634 Alignment);
12635 verifyFormat("int i = 1, j = 10;\n"
12636 "something = 2000;",
12637 Alignment);
12638 verifyFormat("something = 2000;\n"
12639 "int i = 1, j = 10;\n",
12640 Alignment);
12641 verifyFormat("float something = 2000;\n"
12642 "double another = 911;\n"
12643 "int i = 1, j = 10;\n"
12644 "const int *oneMore = 1;\n"
12645 "unsigned i = 2;",
12646 Alignment);
12647 verifyFormat("float a = 5;\n"
12648 "int one = 1;\n"
12649 "method();\n"
12650 "const double oneTwoThree = 123;\n"
12651 "const unsigned int oneTwo = 12;",
12652 Alignment);
12653 verifyFormat("int oneTwoThree{0}; // comment\n"
12654 "unsigned oneTwo; // comment",
12655 Alignment);
12656 EXPECT_EQ("float const a = 5;\n"
12657 "\n"
12658 "int oneTwoThree = 123;",
12659 format("float const a = 5;\n"
12660 "\n"
12661 "int oneTwoThree= 123;",
12662 Alignment));
12663 EXPECT_EQ("float a = 5;\n"
12664 "int one = 1;\n"
12665 "\n"
12666 "unsigned oneTwoThree = 123;",
12667 format("float a = 5;\n"
12668 "int one = 1;\n"
12669 "\n"
12670 "unsigned oneTwoThree = 123;",
12671 Alignment));
12672 EXPECT_EQ("float a = 5;\n"
12673 "int one = 1;\n"
12674 "\n"
12675 "unsigned oneTwoThree = 123;\n"
12676 "int oneTwo = 12;",
12677 format("float a = 5;\n"
12678 "int one = 1;\n"
12679 "\n"
12680 "unsigned oneTwoThree = 123;\n"
12681 "int oneTwo = 12;",
12682 Alignment));
12683 // Function prototype alignment
12684 verifyFormat("int a();\n"
12685 "double b();",
12686 Alignment);
12687 verifyFormat("int a(int x);\n"
12688 "double b();",
12689 Alignment);
12690 unsigned OldColumnLimit = Alignment.ColumnLimit;
12691 // We need to set ColumnLimit to zero, in order to stress nested alignments,
12692 // otherwise the function parameters will be re-flowed onto a single line.
12693 Alignment.ColumnLimit = 0;
12694 EXPECT_EQ("int a(int x,\n"
12695 " float y);\n"
12696 "double b(int x,\n"
12697 " double y);",
12698 format("int a(int x,\n"
12699 " float y);\n"
12700 "double b(int x,\n"
12701 " double y);",
12702 Alignment));
12703 // This ensures that function parameters of function declarations are
12704 // correctly indented when their owning functions are indented.
12705 // The failure case here is for 'double y' to not be indented enough.
12706 EXPECT_EQ("double a(int x);\n"
12707 "int b(int y,\n"
12708 " double z);",
12709 format("double a(int x);\n"
12710 "int b(int y,\n"
12711 " double z);",
12712 Alignment));
12713 // Set ColumnLimit low so that we induce wrapping immediately after
12714 // the function name and opening paren.
12715 Alignment.ColumnLimit = 13;
12716 verifyFormat("int function(\n"
12717 " int x,\n"
12718 " bool y);",
12719 Alignment);
12720 Alignment.ColumnLimit = OldColumnLimit;
12721 // Ensure function pointers don't screw up recursive alignment
12722 verifyFormat("int a(int x, void (*fp)(int y));\n"
12723 "double b();",
12724 Alignment);
12725 Alignment.AlignConsecutiveAssignments = true;
12726 // Ensure recursive alignment is broken by function braces, so that the
12727 // "a = 1" does not align with subsequent assignments inside the function
12728 // body.
12729 verifyFormat("int func(int a = 1) {\n"
12730 " int b = 2;\n"
12731 " int cc = 3;\n"
12732 "}",
12733 Alignment);
12734 verifyFormat("float something = 2000;\n"
12735 "double another = 911;\n"
12736 "int i = 1, j = 10;\n"
12737 "const int *oneMore = 1;\n"
12738 "unsigned i = 2;",
12739 Alignment);
12740 verifyFormat("int oneTwoThree = {0}; // comment\n"
12741 "unsigned oneTwo = 0; // comment",
12742 Alignment);
12743 // Make sure that scope is correctly tracked, in the absence of braces
12744 verifyFormat("for (int i = 0; i < n; i++)\n"
12745 " j = i;\n"
12746 "double x = 1;\n",
12747 Alignment);
12748 verifyFormat("if (int i = 0)\n"
12749 " j = i;\n"
12750 "double x = 1;\n",
12751 Alignment);
12752 // Ensure operator[] and operator() are comprehended
12753 verifyFormat("struct test {\n"
12754 " long long int foo();\n"
12755 " int operator[](int a);\n"
12756 " double bar();\n"
12757 "};\n",
12758 Alignment);
12759 verifyFormat("struct test {\n"
12760 " long long int foo();\n"
12761 " int operator()(int a);\n"
12762 " double bar();\n"
12763 "};\n",
12764 Alignment);
12765 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
12766 " int const i = 1;\n"
12767 " int * j = 2;\n"
12768 " int big = 10000;\n"
12769 "\n"
12770 " unsigned oneTwoThree = 123;\n"
12771 " int oneTwo = 12;\n"
12772 " method();\n"
12773 " float k = 2;\n"
12774 " int ll = 10000;\n"
12775 "}",
12776 format("void SomeFunction(int parameter= 0) {\n"
12777 " int const i= 1;\n"
12778 " int *j=2;\n"
12779 " int big = 10000;\n"
12780 "\n"
12781 "unsigned oneTwoThree =123;\n"
12782 "int oneTwo = 12;\n"
12783 " method();\n"
12784 "float k= 2;\n"
12785 "int ll=10000;\n"
12786 "}",
12787 Alignment));
12788 Alignment.AlignConsecutiveAssignments = false;
12789 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
12790 verifyFormat("#define A \\\n"
12791 " int aaaa = 12; \\\n"
12792 " float b = 23; \\\n"
12793 " const int ccc = 234; \\\n"
12794 " unsigned dddddddddd = 2345;",
12795 Alignment);
12796 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12797 verifyFormat("#define A \\\n"
12798 " int aaaa = 12; \\\n"
12799 " float b = 23; \\\n"
12800 " const int ccc = 234; \\\n"
12801 " unsigned dddddddddd = 2345;",
12802 Alignment);
12803 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
12804 Alignment.ColumnLimit = 30;
12805 verifyFormat("#define A \\\n"
12806 " int aaaa = 12; \\\n"
12807 " float b = 23; \\\n"
12808 " const int ccc = 234; \\\n"
12809 " int dddddddddd = 2345;",
12810 Alignment);
12811 Alignment.ColumnLimit = 80;
12812 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
12813 "k = 4, int l = 5,\n"
12814 " int m = 6) {\n"
12815 " const int j = 10;\n"
12816 " otherThing = 1;\n"
12817 "}",
12818 Alignment);
12819 verifyFormat("void SomeFunction(int parameter = 0) {\n"
12820 " int const i = 1;\n"
12821 " int * j = 2;\n"
12822 " int big = 10000;\n"
12823 "}",
12824 Alignment);
12825 verifyFormat("class C {\n"
12826 "public:\n"
12827 " int i = 1;\n"
12828 " virtual void f() = 0;\n"
12829 "};",
12830 Alignment);
12831 verifyFormat("float i = 1;\n"
12832 "if (SomeType t = getSomething()) {\n"
12833 "}\n"
12834 "const unsigned j = 2;\n"
12835 "int big = 10000;",
12836 Alignment);
12837 verifyFormat("float j = 7;\n"
12838 "for (int k = 0; k < N; ++k) {\n"
12839 "}\n"
12840 "unsigned j = 2;\n"
12841 "int big = 10000;\n"
12842 "}",
12843 Alignment);
12844 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
12845 verifyFormat("float i = 1;\n"
12846 "LooooooooooongType loooooooooooooooooooooongVariable\n"
12847 " = someLooooooooooooooooongFunction();\n"
12848 "int j = 2;",
12849 Alignment);
12850 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
12851 verifyFormat("int i = 1;\n"
12852 "LooooooooooongType loooooooooooooooooooooongVariable =\n"
12853 " someLooooooooooooooooongFunction();\n"
12854 "int j = 2;",
12855 Alignment);
12856
12857 Alignment.AlignConsecutiveAssignments = true;
12858 verifyFormat("auto lambda = []() {\n"
12859 " auto ii = 0;\n"
12860 " float j = 0;\n"
12861 " return 0;\n"
12862 "};\n"
12863 "int i = 0;\n"
12864 "float i2 = 0;\n"
12865 "auto v = type{\n"
12866 " i = 1, //\n"
12867 " (i = 2), //\n"
12868 " i = 3 //\n"
12869 "};",
12870 Alignment);
12871 Alignment.AlignConsecutiveAssignments = false;
12872
12873 verifyFormat(
12874 "int i = 1;\n"
12875 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
12876 " loooooooooooooooooooooongParameterB);\n"
12877 "int j = 2;",
12878 Alignment);
12879
12880 // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
12881 // We expect declarations and assignments to align, as long as it doesn't
12882 // exceed the column limit, starting a new alignment sequence whenever it
12883 // happens.
12884 Alignment.AlignConsecutiveAssignments = true;
12885 Alignment.ColumnLimit = 30;
12886 verifyFormat("float ii = 1;\n"
12887 "unsigned j = 2;\n"
12888 "int someVerylongVariable = 1;\n"
12889 "AnotherLongType ll = 123456;\n"
12890 "VeryVeryLongType k = 2;\n"
12891 "int myvar = 1;",
12892 Alignment);
12893 Alignment.ColumnLimit = 80;
12894 Alignment.AlignConsecutiveAssignments = false;
12895
12896 verifyFormat(
12897 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
12898 " typename LongType, typename B>\n"
12899 "auto foo() {}\n",
12900 Alignment);
12901 verifyFormat("float a, b = 1;\n"
12902 "int c = 2;\n"
12903 "int dd = 3;\n",
12904 Alignment);
12905 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
12906 "float b[1][] = {{3.f}};\n",
12907 Alignment);
12908 Alignment.AlignConsecutiveAssignments = true;
12909 verifyFormat("float a, b = 1;\n"
12910 "int c = 2;\n"
12911 "int dd = 3;\n",
12912 Alignment);
12913 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n"
12914 "float b[1][] = {{3.f}};\n",
12915 Alignment);
12916 Alignment.AlignConsecutiveAssignments = false;
12917
12918 Alignment.ColumnLimit = 30;
12919 Alignment.BinPackParameters = false;
12920 verifyFormat("void foo(float a,\n"
12921 " float b,\n"
12922 " int c,\n"
12923 " uint32_t *d) {\n"
12924 " int * e = 0;\n"
12925 " float f = 0;\n"
12926 " double g = 0;\n"
12927 "}\n"
12928 "void bar(ino_t a,\n"
12929 " int b,\n"
12930 " uint32_t *c,\n"
12931 " bool d) {}\n",
12932 Alignment);
12933 Alignment.BinPackParameters = true;
12934 Alignment.ColumnLimit = 80;
12935
12936 // Bug 33507
12937 Alignment.PointerAlignment = FormatStyle::PAS_Middle;
12938 verifyFormat(
12939 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
12940 " static const Version verVs2017;\n"
12941 " return true;\n"
12942 "});\n",
12943 Alignment);
12944 Alignment.PointerAlignment = FormatStyle::PAS_Right;
12945
12946 // See llvm.org/PR35641
12947 Alignment.AlignConsecutiveDeclarations = true;
12948 verifyFormat("int func() { //\n"
12949 " int b;\n"
12950 " unsigned c;\n"
12951 "}",
12952 Alignment);
12953
12954 // See PR37175
12955 FormatStyle Style = getMozillaStyle();
12956 Style.AlignConsecutiveDeclarations = true;
12957 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
12958 "foo(int a);",
12959 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
12960 }
12961
TEST_F(FormatTest,LinuxBraceBreaking)12962 TEST_F(FormatTest, LinuxBraceBreaking) {
12963 FormatStyle LinuxBraceStyle = getLLVMStyle();
12964 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
12965 verifyFormat("namespace a\n"
12966 "{\n"
12967 "class A\n"
12968 "{\n"
12969 " void f()\n"
12970 " {\n"
12971 " if (true) {\n"
12972 " a();\n"
12973 " b();\n"
12974 " } else {\n"
12975 " a();\n"
12976 " }\n"
12977 " }\n"
12978 " void g() { return; }\n"
12979 "};\n"
12980 "struct B {\n"
12981 " int x;\n"
12982 "};\n"
12983 "} // namespace a\n",
12984 LinuxBraceStyle);
12985 verifyFormat("enum X {\n"
12986 " Y = 0,\n"
12987 "}\n",
12988 LinuxBraceStyle);
12989 verifyFormat("struct S {\n"
12990 " int Type;\n"
12991 " union {\n"
12992 " int x;\n"
12993 " double y;\n"
12994 " } Value;\n"
12995 " class C\n"
12996 " {\n"
12997 " MyFavoriteType Value;\n"
12998 " } Class;\n"
12999 "}\n",
13000 LinuxBraceStyle);
13001 }
13002
TEST_F(FormatTest,MozillaBraceBreaking)13003 TEST_F(FormatTest, MozillaBraceBreaking) {
13004 FormatStyle MozillaBraceStyle = getLLVMStyle();
13005 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
13006 MozillaBraceStyle.FixNamespaceComments = false;
13007 verifyFormat("namespace a {\n"
13008 "class A\n"
13009 "{\n"
13010 " void f()\n"
13011 " {\n"
13012 " if (true) {\n"
13013 " a();\n"
13014 " b();\n"
13015 " }\n"
13016 " }\n"
13017 " void g() { return; }\n"
13018 "};\n"
13019 "enum E\n"
13020 "{\n"
13021 " A,\n"
13022 " // foo\n"
13023 " B,\n"
13024 " C\n"
13025 "};\n"
13026 "struct B\n"
13027 "{\n"
13028 " int x;\n"
13029 "};\n"
13030 "}\n",
13031 MozillaBraceStyle);
13032 verifyFormat("struct S\n"
13033 "{\n"
13034 " int Type;\n"
13035 " union\n"
13036 " {\n"
13037 " int x;\n"
13038 " double y;\n"
13039 " } Value;\n"
13040 " class C\n"
13041 " {\n"
13042 " MyFavoriteType Value;\n"
13043 " } Class;\n"
13044 "}\n",
13045 MozillaBraceStyle);
13046 }
13047
TEST_F(FormatTest,StroustrupBraceBreaking)13048 TEST_F(FormatTest, StroustrupBraceBreaking) {
13049 FormatStyle StroustrupBraceStyle = getLLVMStyle();
13050 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
13051 verifyFormat("namespace a {\n"
13052 "class A {\n"
13053 " void f()\n"
13054 " {\n"
13055 " if (true) {\n"
13056 " a();\n"
13057 " b();\n"
13058 " }\n"
13059 " }\n"
13060 " void g() { return; }\n"
13061 "};\n"
13062 "struct B {\n"
13063 " int x;\n"
13064 "};\n"
13065 "} // namespace a\n",
13066 StroustrupBraceStyle);
13067
13068 verifyFormat("void foo()\n"
13069 "{\n"
13070 " if (a) {\n"
13071 " a();\n"
13072 " }\n"
13073 " else {\n"
13074 " b();\n"
13075 " }\n"
13076 "}\n",
13077 StroustrupBraceStyle);
13078
13079 verifyFormat("#ifdef _DEBUG\n"
13080 "int foo(int i = 0)\n"
13081 "#else\n"
13082 "int foo(int i = 5)\n"
13083 "#endif\n"
13084 "{\n"
13085 " return i;\n"
13086 "}",
13087 StroustrupBraceStyle);
13088
13089 verifyFormat("void foo() {}\n"
13090 "void bar()\n"
13091 "#ifdef _DEBUG\n"
13092 "{\n"
13093 " foo();\n"
13094 "}\n"
13095 "#else\n"
13096 "{\n"
13097 "}\n"
13098 "#endif",
13099 StroustrupBraceStyle);
13100
13101 verifyFormat("void foobar() { int i = 5; }\n"
13102 "#ifdef _DEBUG\n"
13103 "void bar() {}\n"
13104 "#else\n"
13105 "void bar() { foobar(); }\n"
13106 "#endif",
13107 StroustrupBraceStyle);
13108 }
13109
TEST_F(FormatTest,AllmanBraceBreaking)13110 TEST_F(FormatTest, AllmanBraceBreaking) {
13111 FormatStyle AllmanBraceStyle = getLLVMStyle();
13112 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
13113
13114 EXPECT_EQ("namespace a\n"
13115 "{\n"
13116 "void f();\n"
13117 "void g();\n"
13118 "} // namespace a\n",
13119 format("namespace a\n"
13120 "{\n"
13121 "void f();\n"
13122 "void g();\n"
13123 "}\n",
13124 AllmanBraceStyle));
13125
13126 verifyFormat("namespace a\n"
13127 "{\n"
13128 "class A\n"
13129 "{\n"
13130 " void f()\n"
13131 " {\n"
13132 " if (true)\n"
13133 " {\n"
13134 " a();\n"
13135 " b();\n"
13136 " }\n"
13137 " }\n"
13138 " void g() { return; }\n"
13139 "};\n"
13140 "struct B\n"
13141 "{\n"
13142 " int x;\n"
13143 "};\n"
13144 "union C\n"
13145 "{\n"
13146 "};\n"
13147 "} // namespace a",
13148 AllmanBraceStyle);
13149
13150 verifyFormat("void f()\n"
13151 "{\n"
13152 " if (true)\n"
13153 " {\n"
13154 " a();\n"
13155 " }\n"
13156 " else if (false)\n"
13157 " {\n"
13158 " b();\n"
13159 " }\n"
13160 " else\n"
13161 " {\n"
13162 " c();\n"
13163 " }\n"
13164 "}\n",
13165 AllmanBraceStyle);
13166
13167 verifyFormat("void f()\n"
13168 "{\n"
13169 " for (int i = 0; i < 10; ++i)\n"
13170 " {\n"
13171 " a();\n"
13172 " }\n"
13173 " while (false)\n"
13174 " {\n"
13175 " b();\n"
13176 " }\n"
13177 " do\n"
13178 " {\n"
13179 " c();\n"
13180 " } while (false)\n"
13181 "}\n",
13182 AllmanBraceStyle);
13183
13184 verifyFormat("void f(int a)\n"
13185 "{\n"
13186 " switch (a)\n"
13187 " {\n"
13188 " case 0:\n"
13189 " break;\n"
13190 " case 1:\n"
13191 " {\n"
13192 " break;\n"
13193 " }\n"
13194 " case 2:\n"
13195 " {\n"
13196 " }\n"
13197 " break;\n"
13198 " default:\n"
13199 " break;\n"
13200 " }\n"
13201 "}\n",
13202 AllmanBraceStyle);
13203
13204 verifyFormat("enum X\n"
13205 "{\n"
13206 " Y = 0,\n"
13207 "}\n",
13208 AllmanBraceStyle);
13209 verifyFormat("enum X\n"
13210 "{\n"
13211 " Y = 0\n"
13212 "}\n",
13213 AllmanBraceStyle);
13214
13215 verifyFormat("@interface BSApplicationController ()\n"
13216 "{\n"
13217 "@private\n"
13218 " id _extraIvar;\n"
13219 "}\n"
13220 "@end\n",
13221 AllmanBraceStyle);
13222
13223 verifyFormat("#ifdef _DEBUG\n"
13224 "int foo(int i = 0)\n"
13225 "#else\n"
13226 "int foo(int i = 5)\n"
13227 "#endif\n"
13228 "{\n"
13229 " return i;\n"
13230 "}",
13231 AllmanBraceStyle);
13232
13233 verifyFormat("void foo() {}\n"
13234 "void bar()\n"
13235 "#ifdef _DEBUG\n"
13236 "{\n"
13237 " foo();\n"
13238 "}\n"
13239 "#else\n"
13240 "{\n"
13241 "}\n"
13242 "#endif",
13243 AllmanBraceStyle);
13244
13245 verifyFormat("void foobar() { int i = 5; }\n"
13246 "#ifdef _DEBUG\n"
13247 "void bar() {}\n"
13248 "#else\n"
13249 "void bar() { foobar(); }\n"
13250 "#endif",
13251 AllmanBraceStyle);
13252
13253 // This shouldn't affect ObjC blocks..
13254 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
13255 " // ...\n"
13256 " int i;\n"
13257 "}];",
13258 AllmanBraceStyle);
13259 verifyFormat("void (^block)(void) = ^{\n"
13260 " // ...\n"
13261 " int i;\n"
13262 "};",
13263 AllmanBraceStyle);
13264 // .. or dict literals.
13265 verifyFormat("void f()\n"
13266 "{\n"
13267 " // ...\n"
13268 " [object someMethod:@{@\"a\" : @\"b\"}];\n"
13269 "}",
13270 AllmanBraceStyle);
13271 verifyFormat("void f()\n"
13272 "{\n"
13273 " // ...\n"
13274 " [object someMethod:@{a : @\"b\"}];\n"
13275 "}",
13276 AllmanBraceStyle);
13277 verifyFormat("int f()\n"
13278 "{ // comment\n"
13279 " return 42;\n"
13280 "}",
13281 AllmanBraceStyle);
13282
13283 AllmanBraceStyle.ColumnLimit = 19;
13284 verifyFormat("void f() { int i; }", AllmanBraceStyle);
13285 AllmanBraceStyle.ColumnLimit = 18;
13286 verifyFormat("void f()\n"
13287 "{\n"
13288 " int i;\n"
13289 "}",
13290 AllmanBraceStyle);
13291 AllmanBraceStyle.ColumnLimit = 80;
13292
13293 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
13294 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
13295 FormatStyle::SIS_WithoutElse;
13296 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
13297 verifyFormat("void f(bool b)\n"
13298 "{\n"
13299 " if (b)\n"
13300 " {\n"
13301 " return;\n"
13302 " }\n"
13303 "}\n",
13304 BreakBeforeBraceShortIfs);
13305 verifyFormat("void f(bool b)\n"
13306 "{\n"
13307 " if constexpr (b)\n"
13308 " {\n"
13309 " return;\n"
13310 " }\n"
13311 "}\n",
13312 BreakBeforeBraceShortIfs);
13313 verifyFormat("void f(bool b)\n"
13314 "{\n"
13315 " if CONSTEXPR (b)\n"
13316 " {\n"
13317 " return;\n"
13318 " }\n"
13319 "}\n",
13320 BreakBeforeBraceShortIfs);
13321 verifyFormat("void f(bool b)\n"
13322 "{\n"
13323 " if (b) return;\n"
13324 "}\n",
13325 BreakBeforeBraceShortIfs);
13326 verifyFormat("void f(bool b)\n"
13327 "{\n"
13328 " if constexpr (b) return;\n"
13329 "}\n",
13330 BreakBeforeBraceShortIfs);
13331 verifyFormat("void f(bool b)\n"
13332 "{\n"
13333 " if CONSTEXPR (b) return;\n"
13334 "}\n",
13335 BreakBeforeBraceShortIfs);
13336 verifyFormat("void f(bool b)\n"
13337 "{\n"
13338 " while (b)\n"
13339 " {\n"
13340 " return;\n"
13341 " }\n"
13342 "}\n",
13343 BreakBeforeBraceShortIfs);
13344 }
13345
TEST_F(FormatTest,WhitesmithsBraceBreaking)13346 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
13347 FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
13348 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
13349
13350 // Make a few changes to the style for testing purposes
13351 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
13352 FormatStyle::SFS_Empty;
13353 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
13354 WhitesmithsBraceStyle.ColumnLimit = 0;
13355
13356 // FIXME: this test case can't decide whether there should be a blank line
13357 // after the ~D() line or not. It adds one if one doesn't exist in the test
13358 // and it removes the line if one exists.
13359 /*
13360 verifyFormat("class A;\n"
13361 "namespace B\n"
13362 " {\n"
13363 "class C;\n"
13364 "// Comment\n"
13365 "class D\n"
13366 " {\n"
13367 "public:\n"
13368 " D();\n"
13369 " ~D() {}\n"
13370 "private:\n"
13371 " enum E\n"
13372 " {\n"
13373 " F\n"
13374 " }\n"
13375 " };\n"
13376 " } // namespace B\n",
13377 WhitesmithsBraceStyle);
13378 */
13379
13380 verifyFormat("namespace a\n"
13381 " {\n"
13382 "class A\n"
13383 " {\n"
13384 " void f()\n"
13385 " {\n"
13386 " if (true)\n"
13387 " {\n"
13388 " a();\n"
13389 " b();\n"
13390 " }\n"
13391 " }\n"
13392 " void g()\n"
13393 " {\n"
13394 " return;\n"
13395 " }\n"
13396 " };\n"
13397 "struct B\n"
13398 " {\n"
13399 " int x;\n"
13400 " };\n"
13401 " } // namespace a",
13402 WhitesmithsBraceStyle);
13403
13404 verifyFormat("void f()\n"
13405 " {\n"
13406 " if (true)\n"
13407 " {\n"
13408 " a();\n"
13409 " }\n"
13410 " else if (false)\n"
13411 " {\n"
13412 " b();\n"
13413 " }\n"
13414 " else\n"
13415 " {\n"
13416 " c();\n"
13417 " }\n"
13418 " }\n",
13419 WhitesmithsBraceStyle);
13420
13421 verifyFormat("void f()\n"
13422 " {\n"
13423 " for (int i = 0; i < 10; ++i)\n"
13424 " {\n"
13425 " a();\n"
13426 " }\n"
13427 " while (false)\n"
13428 " {\n"
13429 " b();\n"
13430 " }\n"
13431 " do\n"
13432 " {\n"
13433 " c();\n"
13434 " } while (false)\n"
13435 " }\n",
13436 WhitesmithsBraceStyle);
13437
13438 WhitesmithsBraceStyle.IndentCaseBlocks = true;
13439 verifyFormat("void switchTest1(int a)\n"
13440 " {\n"
13441 " switch (a)\n"
13442 " {\n"
13443 " case 2:\n"
13444 " {\n"
13445 " }\n"
13446 " break;\n"
13447 " }\n"
13448 " }\n",
13449 WhitesmithsBraceStyle);
13450
13451 verifyFormat("void switchTest2(int a)\n"
13452 " {\n"
13453 " switch (a)\n"
13454 " {\n"
13455 " case 0:\n"
13456 " break;\n"
13457 " case 1:\n"
13458 " {\n"
13459 " break;\n"
13460 " }\n"
13461 " case 2:\n"
13462 " {\n"
13463 " }\n"
13464 " break;\n"
13465 " default:\n"
13466 " break;\n"
13467 " }\n"
13468 " }\n",
13469 WhitesmithsBraceStyle);
13470
13471 verifyFormat("void switchTest3(int a)\n"
13472 " {\n"
13473 " switch (a)\n"
13474 " {\n"
13475 " case 0:\n"
13476 " {\n"
13477 " foo(x);\n"
13478 " }\n"
13479 " break;\n"
13480 " default:\n"
13481 " {\n"
13482 " foo(1);\n"
13483 " }\n"
13484 " break;\n"
13485 " }\n"
13486 " }\n",
13487 WhitesmithsBraceStyle);
13488
13489 WhitesmithsBraceStyle.IndentCaseBlocks = false;
13490
13491 verifyFormat("void switchTest4(int a)\n"
13492 " {\n"
13493 " switch (a)\n"
13494 " {\n"
13495 " case 2:\n"
13496 " {\n"
13497 " }\n"
13498 " break;\n"
13499 " }\n"
13500 " }\n",
13501 WhitesmithsBraceStyle);
13502
13503 verifyFormat("void switchTest5(int a)\n"
13504 " {\n"
13505 " switch (a)\n"
13506 " {\n"
13507 " case 0:\n"
13508 " break;\n"
13509 " case 1:\n"
13510 " {\n"
13511 " foo();\n"
13512 " break;\n"
13513 " }\n"
13514 " case 2:\n"
13515 " {\n"
13516 " }\n"
13517 " break;\n"
13518 " default:\n"
13519 " break;\n"
13520 " }\n"
13521 " }\n",
13522 WhitesmithsBraceStyle);
13523
13524 verifyFormat("void switchTest6(int a)\n"
13525 " {\n"
13526 " switch (a)\n"
13527 " {\n"
13528 " case 0:\n"
13529 " {\n"
13530 " foo(x);\n"
13531 " }\n"
13532 " break;\n"
13533 " default:\n"
13534 " {\n"
13535 " foo(1);\n"
13536 " }\n"
13537 " break;\n"
13538 " }\n"
13539 " }\n",
13540 WhitesmithsBraceStyle);
13541
13542 verifyFormat("enum X\n"
13543 " {\n"
13544 " Y = 0, // testing\n"
13545 " }\n",
13546 WhitesmithsBraceStyle);
13547
13548 verifyFormat("enum X\n"
13549 " {\n"
13550 " Y = 0\n"
13551 " }\n",
13552 WhitesmithsBraceStyle);
13553 verifyFormat("enum X\n"
13554 " {\n"
13555 " Y = 0,\n"
13556 " Z = 1\n"
13557 " };\n",
13558 WhitesmithsBraceStyle);
13559
13560 verifyFormat("@interface BSApplicationController ()\n"
13561 " {\n"
13562 "@private\n"
13563 " id _extraIvar;\n"
13564 " }\n"
13565 "@end\n",
13566 WhitesmithsBraceStyle);
13567
13568 verifyFormat("#ifdef _DEBUG\n"
13569 "int foo(int i = 0)\n"
13570 "#else\n"
13571 "int foo(int i = 5)\n"
13572 "#endif\n"
13573 " {\n"
13574 " return i;\n"
13575 " }",
13576 WhitesmithsBraceStyle);
13577
13578 verifyFormat("void foo() {}\n"
13579 "void bar()\n"
13580 "#ifdef _DEBUG\n"
13581 " {\n"
13582 " foo();\n"
13583 " }\n"
13584 "#else\n"
13585 " {\n"
13586 " }\n"
13587 "#endif",
13588 WhitesmithsBraceStyle);
13589
13590 verifyFormat("void foobar()\n"
13591 " {\n"
13592 " int i = 5;\n"
13593 " }\n"
13594 "#ifdef _DEBUG\n"
13595 "void bar()\n"
13596 " {\n"
13597 " }\n"
13598 "#else\n"
13599 "void bar()\n"
13600 " {\n"
13601 " foobar();\n"
13602 " }\n"
13603 "#endif",
13604 WhitesmithsBraceStyle);
13605
13606 // This shouldn't affect ObjC blocks..
13607 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
13608 " // ...\n"
13609 " int i;\n"
13610 "}];",
13611 WhitesmithsBraceStyle);
13612 verifyFormat("void (^block)(void) = ^{\n"
13613 " // ...\n"
13614 " int i;\n"
13615 "};",
13616 WhitesmithsBraceStyle);
13617 // .. or dict literals.
13618 verifyFormat("void f()\n"
13619 " {\n"
13620 " [object someMethod:@{@\"a\" : @\"b\"}];\n"
13621 " }",
13622 WhitesmithsBraceStyle);
13623
13624 verifyFormat("int f()\n"
13625 " { // comment\n"
13626 " return 42;\n"
13627 " }",
13628 WhitesmithsBraceStyle);
13629
13630 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
13631 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
13632 FormatStyle::SIS_Always;
13633 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
13634 verifyFormat("void f(bool b)\n"
13635 " {\n"
13636 " if (b)\n"
13637 " {\n"
13638 " return;\n"
13639 " }\n"
13640 " }\n",
13641 BreakBeforeBraceShortIfs);
13642 verifyFormat("void f(bool b)\n"
13643 " {\n"
13644 " if (b) return;\n"
13645 " }\n",
13646 BreakBeforeBraceShortIfs);
13647 verifyFormat("void f(bool b)\n"
13648 " {\n"
13649 " while (b)\n"
13650 " {\n"
13651 " return;\n"
13652 " }\n"
13653 " }\n",
13654 BreakBeforeBraceShortIfs);
13655 }
13656
TEST_F(FormatTest,GNUBraceBreaking)13657 TEST_F(FormatTest, GNUBraceBreaking) {
13658 FormatStyle GNUBraceStyle = getLLVMStyle();
13659 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
13660 verifyFormat("namespace a\n"
13661 "{\n"
13662 "class A\n"
13663 "{\n"
13664 " void f()\n"
13665 " {\n"
13666 " int a;\n"
13667 " {\n"
13668 " int b;\n"
13669 " }\n"
13670 " if (true)\n"
13671 " {\n"
13672 " a();\n"
13673 " b();\n"
13674 " }\n"
13675 " }\n"
13676 " void g() { return; }\n"
13677 "}\n"
13678 "} // namespace a",
13679 GNUBraceStyle);
13680
13681 verifyFormat("void f()\n"
13682 "{\n"
13683 " if (true)\n"
13684 " {\n"
13685 " a();\n"
13686 " }\n"
13687 " else if (false)\n"
13688 " {\n"
13689 " b();\n"
13690 " }\n"
13691 " else\n"
13692 " {\n"
13693 " c();\n"
13694 " }\n"
13695 "}\n",
13696 GNUBraceStyle);
13697
13698 verifyFormat("void f()\n"
13699 "{\n"
13700 " for (int i = 0; i < 10; ++i)\n"
13701 " {\n"
13702 " a();\n"
13703 " }\n"
13704 " while (false)\n"
13705 " {\n"
13706 " b();\n"
13707 " }\n"
13708 " do\n"
13709 " {\n"
13710 " c();\n"
13711 " }\n"
13712 " while (false);\n"
13713 "}\n",
13714 GNUBraceStyle);
13715
13716 verifyFormat("void f(int a)\n"
13717 "{\n"
13718 " switch (a)\n"
13719 " {\n"
13720 " case 0:\n"
13721 " break;\n"
13722 " case 1:\n"
13723 " {\n"
13724 " break;\n"
13725 " }\n"
13726 " case 2:\n"
13727 " {\n"
13728 " }\n"
13729 " break;\n"
13730 " default:\n"
13731 " break;\n"
13732 " }\n"
13733 "}\n",
13734 GNUBraceStyle);
13735
13736 verifyFormat("enum X\n"
13737 "{\n"
13738 " Y = 0,\n"
13739 "}\n",
13740 GNUBraceStyle);
13741
13742 verifyFormat("@interface BSApplicationController ()\n"
13743 "{\n"
13744 "@private\n"
13745 " id _extraIvar;\n"
13746 "}\n"
13747 "@end\n",
13748 GNUBraceStyle);
13749
13750 verifyFormat("#ifdef _DEBUG\n"
13751 "int foo(int i = 0)\n"
13752 "#else\n"
13753 "int foo(int i = 5)\n"
13754 "#endif\n"
13755 "{\n"
13756 " return i;\n"
13757 "}",
13758 GNUBraceStyle);
13759
13760 verifyFormat("void foo() {}\n"
13761 "void bar()\n"
13762 "#ifdef _DEBUG\n"
13763 "{\n"
13764 " foo();\n"
13765 "}\n"
13766 "#else\n"
13767 "{\n"
13768 "}\n"
13769 "#endif",
13770 GNUBraceStyle);
13771
13772 verifyFormat("void foobar() { int i = 5; }\n"
13773 "#ifdef _DEBUG\n"
13774 "void bar() {}\n"
13775 "#else\n"
13776 "void bar() { foobar(); }\n"
13777 "#endif",
13778 GNUBraceStyle);
13779 }
13780
TEST_F(FormatTest,WebKitBraceBreaking)13781 TEST_F(FormatTest, WebKitBraceBreaking) {
13782 FormatStyle WebKitBraceStyle = getLLVMStyle();
13783 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
13784 WebKitBraceStyle.FixNamespaceComments = false;
13785 verifyFormat("namespace a {\n"
13786 "class A {\n"
13787 " void f()\n"
13788 " {\n"
13789 " if (true) {\n"
13790 " a();\n"
13791 " b();\n"
13792 " }\n"
13793 " }\n"
13794 " void g() { return; }\n"
13795 "};\n"
13796 "enum E {\n"
13797 " A,\n"
13798 " // foo\n"
13799 " B,\n"
13800 " C\n"
13801 "};\n"
13802 "struct B {\n"
13803 " int x;\n"
13804 "};\n"
13805 "}\n",
13806 WebKitBraceStyle);
13807 verifyFormat("struct S {\n"
13808 " int Type;\n"
13809 " union {\n"
13810 " int x;\n"
13811 " double y;\n"
13812 " } Value;\n"
13813 " class C {\n"
13814 " MyFavoriteType Value;\n"
13815 " } Class;\n"
13816 "};\n",
13817 WebKitBraceStyle);
13818 }
13819
TEST_F(FormatTest,CatchExceptionReferenceBinding)13820 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
13821 verifyFormat("void f() {\n"
13822 " try {\n"
13823 " } catch (const Exception &e) {\n"
13824 " }\n"
13825 "}\n",
13826 getLLVMStyle());
13827 }
13828
TEST_F(FormatTest,UnderstandsPragmas)13829 TEST_F(FormatTest, UnderstandsPragmas) {
13830 verifyFormat("#pragma omp reduction(| : var)");
13831 verifyFormat("#pragma omp reduction(+ : var)");
13832
13833 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
13834 "(including parentheses).",
13835 format("#pragma mark Any non-hyphenated or hyphenated string "
13836 "(including parentheses)."));
13837 }
13838
TEST_F(FormatTest,UnderstandPragmaOption)13839 TEST_F(FormatTest, UnderstandPragmaOption) {
13840 verifyFormat("#pragma option -C -A");
13841
13842 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A"));
13843 }
13844
TEST_F(FormatTest,OptimizeBreakPenaltyVsExcess)13845 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
13846 FormatStyle Style = getLLVMStyle();
13847 Style.ColumnLimit = 20;
13848
13849 // See PR41213
13850 EXPECT_EQ("/*\n"
13851 " *\t9012345\n"
13852 " * /8901\n"
13853 " */",
13854 format("/*\n"
13855 " *\t9012345 /8901\n"
13856 " */",
13857 Style));
13858 EXPECT_EQ("/*\n"
13859 " *345678\n"
13860 " *\t/8901\n"
13861 " */",
13862 format("/*\n"
13863 " *345678\t/8901\n"
13864 " */",
13865 Style));
13866
13867 verifyFormat("int a; // the\n"
13868 " // comment",
13869 Style);
13870 EXPECT_EQ("int a; /* first line\n"
13871 " * second\n"
13872 " * line third\n"
13873 " * line\n"
13874 " */",
13875 format("int a; /* first line\n"
13876 " * second\n"
13877 " * line third\n"
13878 " * line\n"
13879 " */",
13880 Style));
13881 EXPECT_EQ("int a; // first line\n"
13882 " // second\n"
13883 " // line third\n"
13884 " // line",
13885 format("int a; // first line\n"
13886 " // second line\n"
13887 " // third line",
13888 Style));
13889
13890 Style.PenaltyExcessCharacter = 90;
13891 verifyFormat("int a; // the comment", Style);
13892 EXPECT_EQ("int a; // the comment\n"
13893 " // aaa",
13894 format("int a; // the comment aaa", Style));
13895 EXPECT_EQ("int a; /* first line\n"
13896 " * second line\n"
13897 " * third line\n"
13898 " */",
13899 format("int a; /* first line\n"
13900 " * second line\n"
13901 " * third line\n"
13902 " */",
13903 Style));
13904 EXPECT_EQ("int a; // first line\n"
13905 " // second line\n"
13906 " // third line",
13907 format("int a; // first line\n"
13908 " // second line\n"
13909 " // third line",
13910 Style));
13911 // FIXME: Investigate why this is not getting the same layout as the test
13912 // above.
13913 EXPECT_EQ("int a; /* first line\n"
13914 " * second line\n"
13915 " * third line\n"
13916 " */",
13917 format("int a; /* first line second line third line"
13918 "\n*/",
13919 Style));
13920
13921 EXPECT_EQ("// foo bar baz bazfoo\n"
13922 "// foo bar foo bar\n",
13923 format("// foo bar baz bazfoo\n"
13924 "// foo bar foo bar\n",
13925 Style));
13926 EXPECT_EQ("// foo bar baz bazfoo\n"
13927 "// foo bar foo bar\n",
13928 format("// foo bar baz bazfoo\n"
13929 "// foo bar foo bar\n",
13930 Style));
13931
13932 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
13933 // next one.
13934 EXPECT_EQ("// foo bar baz bazfoo\n"
13935 "// bar foo bar\n",
13936 format("// foo bar baz bazfoo bar\n"
13937 "// foo bar\n",
13938 Style));
13939
13940 EXPECT_EQ("// foo bar baz bazfoo\n"
13941 "// foo bar baz bazfoo\n"
13942 "// bar foo bar\n",
13943 format("// foo bar baz bazfoo\n"
13944 "// foo bar baz bazfoo bar\n"
13945 "// foo bar\n",
13946 Style));
13947
13948 EXPECT_EQ("// foo bar baz bazfoo\n"
13949 "// foo bar baz bazfoo\n"
13950 "// bar foo bar\n",
13951 format("// foo bar baz bazfoo\n"
13952 "// foo bar baz bazfoo bar\n"
13953 "// foo bar\n",
13954 Style));
13955
13956 // Make sure we do not keep protruding characters if strict mode reflow is
13957 // cheaper than keeping protruding characters.
13958 Style.ColumnLimit = 21;
13959 EXPECT_EQ(
13960 "// foo foo foo foo\n"
13961 "// foo foo foo foo\n"
13962 "// foo foo foo foo\n",
13963 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
13964
13965 EXPECT_EQ("int a = /* long block\n"
13966 " comment */\n"
13967 " 42;",
13968 format("int a = /* long block comment */ 42;", Style));
13969 }
13970
13971 #define EXPECT_ALL_STYLES_EQUAL(Styles) \
13972 for (size_t i = 1; i < Styles.size(); ++i) \
13973 EXPECT_EQ(Styles[0], Styles[i]) \
13974 << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
13975
TEST_F(FormatTest,GetsPredefinedStyleByName)13976 TEST_F(FormatTest, GetsPredefinedStyleByName) {
13977 SmallVector<FormatStyle, 3> Styles;
13978 Styles.resize(3);
13979
13980 Styles[0] = getLLVMStyle();
13981 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
13982 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
13983 EXPECT_ALL_STYLES_EQUAL(Styles);
13984
13985 Styles[0] = getGoogleStyle();
13986 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
13987 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
13988 EXPECT_ALL_STYLES_EQUAL(Styles);
13989
13990 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
13991 EXPECT_TRUE(
13992 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
13993 EXPECT_TRUE(
13994 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
13995 EXPECT_ALL_STYLES_EQUAL(Styles);
13996
13997 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
13998 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
13999 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
14000 EXPECT_ALL_STYLES_EQUAL(Styles);
14001
14002 Styles[0] = getMozillaStyle();
14003 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
14004 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
14005 EXPECT_ALL_STYLES_EQUAL(Styles);
14006
14007 Styles[0] = getWebKitStyle();
14008 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
14009 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
14010 EXPECT_ALL_STYLES_EQUAL(Styles);
14011
14012 Styles[0] = getGNUStyle();
14013 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
14014 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
14015 EXPECT_ALL_STYLES_EQUAL(Styles);
14016
14017 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
14018 }
14019
TEST_F(FormatTest,GetsCorrectBasedOnStyle)14020 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
14021 SmallVector<FormatStyle, 8> Styles;
14022 Styles.resize(2);
14023
14024 Styles[0] = getGoogleStyle();
14025 Styles[1] = getLLVMStyle();
14026 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
14027 EXPECT_ALL_STYLES_EQUAL(Styles);
14028
14029 Styles.resize(5);
14030 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
14031 Styles[1] = getLLVMStyle();
14032 Styles[1].Language = FormatStyle::LK_JavaScript;
14033 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
14034
14035 Styles[2] = getLLVMStyle();
14036 Styles[2].Language = FormatStyle::LK_JavaScript;
14037 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
14038 "BasedOnStyle: Google",
14039 &Styles[2])
14040 .value());
14041
14042 Styles[3] = getLLVMStyle();
14043 Styles[3].Language = FormatStyle::LK_JavaScript;
14044 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
14045 "Language: JavaScript",
14046 &Styles[3])
14047 .value());
14048
14049 Styles[4] = getLLVMStyle();
14050 Styles[4].Language = FormatStyle::LK_JavaScript;
14051 EXPECT_EQ(0, parseConfiguration("---\n"
14052 "BasedOnStyle: LLVM\n"
14053 "IndentWidth: 123\n"
14054 "---\n"
14055 "BasedOnStyle: Google\n"
14056 "Language: JavaScript",
14057 &Styles[4])
14058 .value());
14059 EXPECT_ALL_STYLES_EQUAL(Styles);
14060 }
14061
14062 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \
14063 Style.FIELD = false; \
14064 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \
14065 EXPECT_TRUE(Style.FIELD); \
14066 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \
14067 EXPECT_FALSE(Style.FIELD);
14068
14069 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
14070
14071 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \
14072 Style.STRUCT.FIELD = false; \
14073 EXPECT_EQ(0, \
14074 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \
14075 .value()); \
14076 EXPECT_TRUE(Style.STRUCT.FIELD); \
14077 EXPECT_EQ(0, \
14078 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \
14079 .value()); \
14080 EXPECT_FALSE(Style.STRUCT.FIELD);
14081
14082 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \
14083 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
14084
14085 #define CHECK_PARSE(TEXT, FIELD, VALUE) \
14086 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \
14087 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \
14088 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
14089
TEST_F(FormatTest,ParsesConfigurationBools)14090 TEST_F(FormatTest, ParsesConfigurationBools) {
14091 FormatStyle Style = {};
14092 Style.Language = FormatStyle::LK_Cpp;
14093 CHECK_PARSE_BOOL(AlignTrailingComments);
14094 CHECK_PARSE_BOOL(AlignConsecutiveAssignments);
14095 CHECK_PARSE_BOOL(AlignConsecutiveBitFields);
14096 CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
14097 CHECK_PARSE_BOOL(AlignConsecutiveMacros);
14098 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
14099 CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
14100 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
14101 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
14102 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
14103 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
14104 CHECK_PARSE_BOOL(BinPackArguments);
14105 CHECK_PARSE_BOOL(BinPackParameters);
14106 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
14107 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
14108 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
14109 CHECK_PARSE_BOOL(BreakStringLiterals);
14110 CHECK_PARSE_BOOL(CompactNamespaces);
14111 CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
14112 CHECK_PARSE_BOOL(DeriveLineEnding);
14113 CHECK_PARSE_BOOL(DerivePointerAlignment);
14114 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
14115 CHECK_PARSE_BOOL(DisableFormat);
14116 CHECK_PARSE_BOOL(IndentCaseLabels);
14117 CHECK_PARSE_BOOL(IndentCaseBlocks);
14118 CHECK_PARSE_BOOL(IndentGotoLabels);
14119 CHECK_PARSE_BOOL(IndentRequires);
14120 CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
14121 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
14122 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
14123 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
14124 CHECK_PARSE_BOOL(Cpp11BracedListStyle);
14125 CHECK_PARSE_BOOL(ReflowComments);
14126 CHECK_PARSE_BOOL(SortIncludes);
14127 CHECK_PARSE_BOOL(SortUsingDeclarations);
14128 CHECK_PARSE_BOOL(SpacesInParentheses);
14129 CHECK_PARSE_BOOL(SpacesInSquareBrackets);
14130 CHECK_PARSE_BOOL(SpacesInAngles);
14131 CHECK_PARSE_BOOL(SpacesInConditionalStatement);
14132 CHECK_PARSE_BOOL(SpaceInEmptyBlock);
14133 CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
14134 CHECK_PARSE_BOOL(SpacesInContainerLiterals);
14135 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
14136 CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
14137 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
14138 CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
14139 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
14140 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
14141 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
14142 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
14143 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
14144 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
14145 CHECK_PARSE_BOOL(UseCRLF);
14146
14147 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
14148 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
14149 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
14150 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
14151 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
14152 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
14153 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
14154 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
14155 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
14156 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
14157 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
14158 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
14159 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
14160 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
14161 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
14162 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
14163 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
14164 }
14165
14166 #undef CHECK_PARSE_BOOL
14167
TEST_F(FormatTest,ParsesConfiguration)14168 TEST_F(FormatTest, ParsesConfiguration) {
14169 FormatStyle Style = {};
14170 Style.Language = FormatStyle::LK_Cpp;
14171 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
14172 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
14173 ConstructorInitializerIndentWidth, 1234u);
14174 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
14175 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
14176 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
14177 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
14178 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
14179 PenaltyBreakBeforeFirstCallParameter, 1234u);
14180 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
14181 PenaltyBreakTemplateDeclaration, 1234u);
14182 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
14183 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
14184 PenaltyReturnTypeOnItsOwnLine, 1234u);
14185 CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
14186 SpacesBeforeTrailingComments, 1234u);
14187 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
14188 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
14189 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
14190
14191 Style.PointerAlignment = FormatStyle::PAS_Middle;
14192 CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
14193 FormatStyle::PAS_Left);
14194 CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
14195 FormatStyle::PAS_Right);
14196 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
14197 FormatStyle::PAS_Middle);
14198 // For backward compatibility:
14199 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
14200 FormatStyle::PAS_Left);
14201 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
14202 FormatStyle::PAS_Right);
14203 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
14204 FormatStyle::PAS_Middle);
14205
14206 Style.Standard = FormatStyle::LS_Auto;
14207 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
14208 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
14209 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
14210 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
14211 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
14212 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
14213 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
14214 // Legacy aliases:
14215 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
14216 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
14217 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
14218 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
14219
14220 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14221 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
14222 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
14223 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
14224 FormatStyle::BOS_None);
14225 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
14226 FormatStyle::BOS_All);
14227 // For backward compatibility:
14228 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
14229 FormatStyle::BOS_None);
14230 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
14231 FormatStyle::BOS_All);
14232
14233 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
14234 CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
14235 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
14236 CHECK_PARSE("BreakConstructorInitializers: AfterColon",
14237 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
14238 CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
14239 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
14240 // For backward compatibility:
14241 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
14242 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
14243
14244 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
14245 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
14246 FormatStyle::BILS_BeforeComma);
14247 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
14248 FormatStyle::BILS_AfterColon);
14249 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
14250 FormatStyle::BILS_BeforeColon);
14251 // For backward compatibility:
14252 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
14253 FormatStyle::BILS_BeforeComma);
14254
14255 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14256 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
14257 FormatStyle::BAS_Align);
14258 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
14259 FormatStyle::BAS_DontAlign);
14260 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
14261 FormatStyle::BAS_AlwaysBreak);
14262 // For backward compatibility:
14263 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
14264 FormatStyle::BAS_DontAlign);
14265 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
14266 FormatStyle::BAS_Align);
14267
14268 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14269 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
14270 FormatStyle::ENAS_DontAlign);
14271 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
14272 FormatStyle::ENAS_Left);
14273 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
14274 FormatStyle::ENAS_Right);
14275 // For backward compatibility:
14276 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
14277 FormatStyle::ENAS_Left);
14278 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
14279 FormatStyle::ENAS_Right);
14280
14281 Style.AlignOperands = FormatStyle::OAS_Align;
14282 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
14283 FormatStyle::OAS_DontAlign);
14284 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
14285 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
14286 FormatStyle::OAS_AlignAfterOperator);
14287 // For backward compatibility:
14288 CHECK_PARSE("AlignOperands: false", AlignOperands,
14289 FormatStyle::OAS_DontAlign);
14290 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
14291
14292 Style.UseTab = FormatStyle::UT_ForIndentation;
14293 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
14294 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
14295 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
14296 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
14297 FormatStyle::UT_ForContinuationAndIndentation);
14298 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
14299 FormatStyle::UT_AlignWithSpaces);
14300 // For backward compatibility:
14301 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
14302 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
14303
14304 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
14305 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
14306 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
14307 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
14308 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
14309 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
14310 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
14311 // For backward compatibility:
14312 CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
14313 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
14314 CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
14315 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
14316
14317 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
14318 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
14319 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
14320 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
14321 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
14322 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
14323 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
14324 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
14325 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
14326 // For backward compatibility:
14327 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
14328 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
14329 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
14330 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
14331
14332 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
14333 CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
14334 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
14335 CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
14336 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
14337 CHECK_PARSE("SpaceAroundPointerQualifiers: After",
14338 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
14339 CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
14340 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
14341
14342 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
14343 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
14344 FormatStyle::SBPO_Never);
14345 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
14346 FormatStyle::SBPO_Always);
14347 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
14348 FormatStyle::SBPO_ControlStatements);
14349 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
14350 FormatStyle::SBPO_NonEmptyParentheses);
14351 // For backward compatibility:
14352 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
14353 FormatStyle::SBPO_Never);
14354 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
14355 FormatStyle::SBPO_ControlStatements);
14356
14357 Style.ColumnLimit = 123;
14358 FormatStyle BaseStyle = getLLVMStyle();
14359 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
14360 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
14361
14362 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
14363 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
14364 FormatStyle::BS_Attach);
14365 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
14366 FormatStyle::BS_Linux);
14367 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
14368 FormatStyle::BS_Mozilla);
14369 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
14370 FormatStyle::BS_Stroustrup);
14371 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
14372 FormatStyle::BS_Allman);
14373 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
14374 FormatStyle::BS_Whitesmiths);
14375 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
14376 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
14377 FormatStyle::BS_WebKit);
14378 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
14379 FormatStyle::BS_Custom);
14380
14381 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
14382 CHECK_PARSE("BraceWrapping:\n"
14383 " AfterControlStatement: MultiLine",
14384 BraceWrapping.AfterControlStatement,
14385 FormatStyle::BWACS_MultiLine);
14386 CHECK_PARSE("BraceWrapping:\n"
14387 " AfterControlStatement: Always",
14388 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
14389 CHECK_PARSE("BraceWrapping:\n"
14390 " AfterControlStatement: Never",
14391 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
14392 // For backward compatibility:
14393 CHECK_PARSE("BraceWrapping:\n"
14394 " AfterControlStatement: true",
14395 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
14396 CHECK_PARSE("BraceWrapping:\n"
14397 " AfterControlStatement: false",
14398 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
14399
14400 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
14401 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
14402 FormatStyle::RTBS_None);
14403 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
14404 FormatStyle::RTBS_All);
14405 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
14406 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
14407 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
14408 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
14409 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
14410 AlwaysBreakAfterReturnType,
14411 FormatStyle::RTBS_TopLevelDefinitions);
14412
14413 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
14414 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
14415 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
14416 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
14417 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
14418 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
14419 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
14420 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
14421 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
14422 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
14423 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
14424
14425 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
14426 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
14427 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
14428 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
14429 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
14430 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
14431 AlwaysBreakAfterDefinitionReturnType,
14432 FormatStyle::DRTBS_TopLevel);
14433
14434 Style.NamespaceIndentation = FormatStyle::NI_All;
14435 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
14436 FormatStyle::NI_None);
14437 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
14438 FormatStyle::NI_Inner);
14439 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
14440 FormatStyle::NI_All);
14441
14442 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
14443 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
14444 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
14445 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
14446 AllowShortIfStatementsOnASingleLine,
14447 FormatStyle::SIS_WithoutElse);
14448 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
14449 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always);
14450 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
14451 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
14452 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
14453 AllowShortIfStatementsOnASingleLine,
14454 FormatStyle::SIS_WithoutElse);
14455
14456 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
14457 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
14458 FormatStyle::IEBS_AfterExternBlock);
14459 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
14460 FormatStyle::IEBS_Indent);
14461 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
14462 FormatStyle::IEBS_NoIndent);
14463 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
14464 FormatStyle::IEBS_Indent);
14465 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
14466 FormatStyle::IEBS_NoIndent);
14467
14468 Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
14469 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
14470 FormatStyle::BFCS_Both);
14471 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
14472 FormatStyle::BFCS_None);
14473 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
14474 FormatStyle::BFCS_Before);
14475 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
14476 FormatStyle::BFCS_After);
14477
14478 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
14479 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
14480 FormatStyle::SJSIO_After);
14481 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
14482 FormatStyle::SJSIO_Before);
14483
14484 // FIXME: This is required because parsing a configuration simply overwrites
14485 // the first N elements of the list instead of resetting it.
14486 Style.ForEachMacros.clear();
14487 std::vector<std::string> BoostForeach;
14488 BoostForeach.push_back("BOOST_FOREACH");
14489 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
14490 std::vector<std::string> BoostAndQForeach;
14491 BoostAndQForeach.push_back("BOOST_FOREACH");
14492 BoostAndQForeach.push_back("Q_FOREACH");
14493 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
14494 BoostAndQForeach);
14495
14496 Style.AttributeMacros.clear();
14497 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
14498 std::vector<std::string>{"__capability"});
14499 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
14500 std::vector<std::string>({"attr1", "attr2"}));
14501
14502 Style.StatementMacros.clear();
14503 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
14504 std::vector<std::string>{"QUNUSED"});
14505 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
14506 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
14507
14508 Style.NamespaceMacros.clear();
14509 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
14510 std::vector<std::string>{"TESTSUITE"});
14511 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
14512 std::vector<std::string>({"TESTSUITE", "SUITE"}));
14513
14514 Style.WhitespaceSensitiveMacros.clear();
14515 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
14516 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
14517 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
14518 WhitespaceSensitiveMacros,
14519 std::vector<std::string>({"STRINGIZE", "ASSERT"}));
14520 Style.WhitespaceSensitiveMacros.clear();
14521 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
14522 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
14523 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
14524 WhitespaceSensitiveMacros,
14525 std::vector<std::string>({"STRINGIZE", "ASSERT"}));
14526
14527 Style.IncludeStyle.IncludeCategories.clear();
14528 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
14529 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
14530 CHECK_PARSE("IncludeCategories:\n"
14531 " - Regex: abc/.*\n"
14532 " Priority: 2\n"
14533 " - Regex: .*\n"
14534 " Priority: 1\n"
14535 " CaseSensitive: true\n",
14536 IncludeStyle.IncludeCategories, ExpectedCategories);
14537 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
14538 "abc$");
14539 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
14540 IncludeStyle.IncludeIsMainSourceRegex, "abc$");
14541
14542 Style.RawStringFormats.clear();
14543 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
14544 {
14545 FormatStyle::LK_TextProto,
14546 {"pb", "proto"},
14547 {"PARSE_TEXT_PROTO"},
14548 /*CanonicalDelimiter=*/"",
14549 "llvm",
14550 },
14551 {
14552 FormatStyle::LK_Cpp,
14553 {"cc", "cpp"},
14554 {"C_CODEBLOCK", "CPPEVAL"},
14555 /*CanonicalDelimiter=*/"cc",
14556 /*BasedOnStyle=*/"",
14557 },
14558 };
14559
14560 CHECK_PARSE("RawStringFormats:\n"
14561 " - Language: TextProto\n"
14562 " Delimiters:\n"
14563 " - 'pb'\n"
14564 " - 'proto'\n"
14565 " EnclosingFunctions:\n"
14566 " - 'PARSE_TEXT_PROTO'\n"
14567 " BasedOnStyle: llvm\n"
14568 " - Language: Cpp\n"
14569 " Delimiters:\n"
14570 " - 'cc'\n"
14571 " - 'cpp'\n"
14572 " EnclosingFunctions:\n"
14573 " - 'C_CODEBLOCK'\n"
14574 " - 'CPPEVAL'\n"
14575 " CanonicalDelimiter: 'cc'",
14576 RawStringFormats, ExpectedRawStringFormats);
14577 }
14578
TEST_F(FormatTest,ParsesConfigurationWithLanguages)14579 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
14580 FormatStyle Style = {};
14581 Style.Language = FormatStyle::LK_Cpp;
14582 CHECK_PARSE("Language: Cpp\n"
14583 "IndentWidth: 12",
14584 IndentWidth, 12u);
14585 EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
14586 "IndentWidth: 34",
14587 &Style),
14588 ParseError::Unsuitable);
14589 FormatStyle BinPackedTCS = {};
14590 BinPackedTCS.Language = FormatStyle::LK_JavaScript;
14591 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
14592 "InsertTrailingCommas: Wrapped",
14593 &BinPackedTCS),
14594 ParseError::BinPackTrailingCommaConflict);
14595 EXPECT_EQ(12u, Style.IndentWidth);
14596 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
14597 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
14598
14599 Style.Language = FormatStyle::LK_JavaScript;
14600 CHECK_PARSE("Language: JavaScript\n"
14601 "IndentWidth: 12",
14602 IndentWidth, 12u);
14603 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
14604 EXPECT_EQ(parseConfiguration("Language: Cpp\n"
14605 "IndentWidth: 34",
14606 &Style),
14607 ParseError::Unsuitable);
14608 EXPECT_EQ(23u, Style.IndentWidth);
14609 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
14610 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
14611
14612 CHECK_PARSE("BasedOnStyle: LLVM\n"
14613 "IndentWidth: 67",
14614 IndentWidth, 67u);
14615
14616 CHECK_PARSE("---\n"
14617 "Language: JavaScript\n"
14618 "IndentWidth: 12\n"
14619 "---\n"
14620 "Language: Cpp\n"
14621 "IndentWidth: 34\n"
14622 "...\n",
14623 IndentWidth, 12u);
14624
14625 Style.Language = FormatStyle::LK_Cpp;
14626 CHECK_PARSE("---\n"
14627 "Language: JavaScript\n"
14628 "IndentWidth: 12\n"
14629 "---\n"
14630 "Language: Cpp\n"
14631 "IndentWidth: 34\n"
14632 "...\n",
14633 IndentWidth, 34u);
14634 CHECK_PARSE("---\n"
14635 "IndentWidth: 78\n"
14636 "---\n"
14637 "Language: JavaScript\n"
14638 "IndentWidth: 56\n"
14639 "...\n",
14640 IndentWidth, 78u);
14641
14642 Style.ColumnLimit = 123;
14643 Style.IndentWidth = 234;
14644 Style.BreakBeforeBraces = FormatStyle::BS_Linux;
14645 Style.TabWidth = 345;
14646 EXPECT_FALSE(parseConfiguration("---\n"
14647 "IndentWidth: 456\n"
14648 "BreakBeforeBraces: Allman\n"
14649 "---\n"
14650 "Language: JavaScript\n"
14651 "IndentWidth: 111\n"
14652 "TabWidth: 111\n"
14653 "---\n"
14654 "Language: Cpp\n"
14655 "BreakBeforeBraces: Stroustrup\n"
14656 "TabWidth: 789\n"
14657 "...\n",
14658 &Style));
14659 EXPECT_EQ(123u, Style.ColumnLimit);
14660 EXPECT_EQ(456u, Style.IndentWidth);
14661 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
14662 EXPECT_EQ(789u, Style.TabWidth);
14663
14664 EXPECT_EQ(parseConfiguration("---\n"
14665 "Language: JavaScript\n"
14666 "IndentWidth: 56\n"
14667 "---\n"
14668 "IndentWidth: 78\n"
14669 "...\n",
14670 &Style),
14671 ParseError::Error);
14672 EXPECT_EQ(parseConfiguration("---\n"
14673 "Language: JavaScript\n"
14674 "IndentWidth: 56\n"
14675 "---\n"
14676 "Language: JavaScript\n"
14677 "IndentWidth: 78\n"
14678 "...\n",
14679 &Style),
14680 ParseError::Error);
14681
14682 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
14683 }
14684
14685 #undef CHECK_PARSE
14686
TEST_F(FormatTest,UsesLanguageForBasedOnStyle)14687 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
14688 FormatStyle Style = {};
14689 Style.Language = FormatStyle::LK_JavaScript;
14690 Style.BreakBeforeTernaryOperators = true;
14691 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
14692 EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
14693
14694 Style.BreakBeforeTernaryOperators = true;
14695 EXPECT_EQ(0, parseConfiguration("---\n"
14696 "BasedOnStyle: Google\n"
14697 "---\n"
14698 "Language: JavaScript\n"
14699 "IndentWidth: 76\n"
14700 "...\n",
14701 &Style)
14702 .value());
14703 EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
14704 EXPECT_EQ(76u, Style.IndentWidth);
14705 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
14706 }
14707
TEST_F(FormatTest,ConfigurationRoundTripTest)14708 TEST_F(FormatTest, ConfigurationRoundTripTest) {
14709 FormatStyle Style = getLLVMStyle();
14710 std::string YAML = configurationAsText(Style);
14711 FormatStyle ParsedStyle = {};
14712 ParsedStyle.Language = FormatStyle::LK_Cpp;
14713 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
14714 EXPECT_EQ(Style, ParsedStyle);
14715 }
14716
TEST_F(FormatTest,WorksFor8bitEncodings)14717 TEST_F(FormatTest, WorksFor8bitEncodings) {
14718 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
14719 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
14720 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
14721 "\"\xef\xee\xf0\xf3...\"",
14722 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
14723 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
14724 "\xef\xee\xf0\xf3...\"",
14725 getLLVMStyleWithColumns(12)));
14726 }
14727
TEST_F(FormatTest,HandlesUTF8BOM)14728 TEST_F(FormatTest, HandlesUTF8BOM) {
14729 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
14730 EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
14731 format("\xef\xbb\xbf#include <iostream>"));
14732 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
14733 format("\xef\xbb\xbf\n#include <iostream>"));
14734 }
14735
14736 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
14737 #if !defined(_MSC_VER)
14738
TEST_F(FormatTest,CountsUTF8CharactersProperly)14739 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
14740 verifyFormat("\"Однажды в студёную зимнюю пору...\"",
14741 getLLVMStyleWithColumns(35));
14742 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
14743 getLLVMStyleWithColumns(31));
14744 verifyFormat("// Однажды в студёную зимнюю пору...",
14745 getLLVMStyleWithColumns(36));
14746 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
14747 verifyFormat("/* Однажды в студёную зимнюю пору... */",
14748 getLLVMStyleWithColumns(39));
14749 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
14750 getLLVMStyleWithColumns(35));
14751 }
14752
TEST_F(FormatTest,SplitsUTF8Strings)14753 TEST_F(FormatTest, SplitsUTF8Strings) {
14754 // Non-printable characters' width is currently considered to be the length in
14755 // bytes in UTF8. The characters can be displayed in very different manner
14756 // (zero-width, single width with a substitution glyph, expanded to their code
14757 // (e.g. "<8d>"), so there's no single correct way to handle them.
14758 EXPECT_EQ("\"aaaaÄ\"\n"
14759 "\"\xc2\x8d\";",
14760 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
14761 EXPECT_EQ("\"aaaaaaaÄ\"\n"
14762 "\"\xc2\x8d\";",
14763 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
14764 EXPECT_EQ("\"Однажды, в \"\n"
14765 "\"студёную \"\n"
14766 "\"зимнюю \"\n"
14767 "\"пору,\"",
14768 format("\"Однажды, в студёную зимнюю пору,\"",
14769 getLLVMStyleWithColumns(13)));
14770 EXPECT_EQ(
14771 "\"一 二 三 \"\n"
14772 "\"四 五六 \"\n"
14773 "\"七 八 九 \"\n"
14774 "\"十\"",
14775 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
14776 EXPECT_EQ("\"一\t\"\n"
14777 "\"二 \t\"\n"
14778 "\"三 四 \"\n"
14779 "\"五\t\"\n"
14780 "\"六 \t\"\n"
14781 "\"七 \"\n"
14782 "\"八九十\tqq\"",
14783 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
14784 getLLVMStyleWithColumns(11)));
14785
14786 // UTF8 character in an escape sequence.
14787 EXPECT_EQ("\"aaaaaa\"\n"
14788 "\"\\\xC2\x8D\"",
14789 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
14790 }
14791
TEST_F(FormatTest,HandlesDoubleWidthCharsInMultiLineStrings)14792 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
14793 EXPECT_EQ("const char *sssss =\n"
14794 " \"一二三四五六七八\\\n"
14795 " 九 十\";",
14796 format("const char *sssss = \"一二三四五六七八\\\n"
14797 " 九 十\";",
14798 getLLVMStyleWithColumns(30)));
14799 }
14800
TEST_F(FormatTest,SplitsUTF8LineComments)14801 TEST_F(FormatTest, SplitsUTF8LineComments) {
14802 EXPECT_EQ("// aaaaÄ\xc2\x8d",
14803 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
14804 EXPECT_EQ("// Я из лесу\n"
14805 "// вышел; был\n"
14806 "// сильный\n"
14807 "// мороз.",
14808 format("// Я из лесу вышел; был сильный мороз.",
14809 getLLVMStyleWithColumns(13)));
14810 EXPECT_EQ("// 一二三\n"
14811 "// 四五六七\n"
14812 "// 八 九\n"
14813 "// 十",
14814 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9)));
14815 }
14816
TEST_F(FormatTest,SplitsUTF8BlockComments)14817 TEST_F(FormatTest, SplitsUTF8BlockComments) {
14818 EXPECT_EQ("/* Гляжу,\n"
14819 " * поднимается\n"
14820 " * медленно в\n"
14821 " * гору\n"
14822 " * Лошадка,\n"
14823 " * везущая\n"
14824 " * хворосту\n"
14825 " * воз. */",
14826 format("/* Гляжу, поднимается медленно в гору\n"
14827 " * Лошадка, везущая хворосту воз. */",
14828 getLLVMStyleWithColumns(13)));
14829 EXPECT_EQ(
14830 "/* 一二三\n"
14831 " * 四五六七\n"
14832 " * 八 九\n"
14833 " * 十 */",
14834 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9)));
14835 EXPECT_EQ("/* \n"
14836 " * \n"
14837 " * - */",
14838 format("/* - */", getLLVMStyleWithColumns(12)));
14839 }
14840
14841 #endif // _MSC_VER
14842
TEST_F(FormatTest,ConstructorInitializerIndentWidth)14843 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
14844 FormatStyle Style = getLLVMStyle();
14845
14846 Style.ConstructorInitializerIndentWidth = 4;
14847 verifyFormat(
14848 "SomeClass::Constructor()\n"
14849 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
14850 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
14851 Style);
14852
14853 Style.ConstructorInitializerIndentWidth = 2;
14854 verifyFormat(
14855 "SomeClass::Constructor()\n"
14856 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
14857 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
14858 Style);
14859
14860 Style.ConstructorInitializerIndentWidth = 0;
14861 verifyFormat(
14862 "SomeClass::Constructor()\n"
14863 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
14864 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
14865 Style);
14866 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14867 verifyFormat(
14868 "SomeLongTemplateVariableName<\n"
14869 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
14870 Style);
14871 verifyFormat("bool smaller = 1 < "
14872 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
14873 " "
14874 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
14875 Style);
14876
14877 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
14878 verifyFormat("SomeClass::Constructor() :\n"
14879 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
14880 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
14881 Style);
14882 }
14883
TEST_F(FormatTest,BreakConstructorInitializersBeforeComma)14884 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
14885 FormatStyle Style = getLLVMStyle();
14886 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
14887 Style.ConstructorInitializerIndentWidth = 4;
14888 verifyFormat("SomeClass::Constructor()\n"
14889 " : a(a)\n"
14890 " , b(b)\n"
14891 " , c(c) {}",
14892 Style);
14893 verifyFormat("SomeClass::Constructor()\n"
14894 " : a(a) {}",
14895 Style);
14896
14897 Style.ColumnLimit = 0;
14898 verifyFormat("SomeClass::Constructor()\n"
14899 " : a(a) {}",
14900 Style);
14901 verifyFormat("SomeClass::Constructor() noexcept\n"
14902 " : a(a) {}",
14903 Style);
14904 verifyFormat("SomeClass::Constructor()\n"
14905 " : a(a)\n"
14906 " , b(b)\n"
14907 " , c(c) {}",
14908 Style);
14909 verifyFormat("SomeClass::Constructor()\n"
14910 " : a(a) {\n"
14911 " foo();\n"
14912 " bar();\n"
14913 "}",
14914 Style);
14915
14916 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
14917 verifyFormat("SomeClass::Constructor()\n"
14918 " : a(a)\n"
14919 " , b(b)\n"
14920 " , c(c) {\n}",
14921 Style);
14922 verifyFormat("SomeClass::Constructor()\n"
14923 " : a(a) {\n}",
14924 Style);
14925
14926 Style.ColumnLimit = 80;
14927 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
14928 Style.ConstructorInitializerIndentWidth = 2;
14929 verifyFormat("SomeClass::Constructor()\n"
14930 " : a(a)\n"
14931 " , b(b)\n"
14932 " , c(c) {}",
14933 Style);
14934
14935 Style.ConstructorInitializerIndentWidth = 0;
14936 verifyFormat("SomeClass::Constructor()\n"
14937 ": a(a)\n"
14938 ", b(b)\n"
14939 ", c(c) {}",
14940 Style);
14941
14942 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
14943 Style.ConstructorInitializerIndentWidth = 4;
14944 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
14945 verifyFormat(
14946 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
14947 Style);
14948 verifyFormat(
14949 "SomeClass::Constructor()\n"
14950 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
14951 Style);
14952 Style.ConstructorInitializerIndentWidth = 4;
14953 Style.ColumnLimit = 60;
14954 verifyFormat("SomeClass::Constructor()\n"
14955 " : aaaaaaaa(aaaaaaaa)\n"
14956 " , aaaaaaaa(aaaaaaaa)\n"
14957 " , aaaaaaaa(aaaaaaaa) {}",
14958 Style);
14959 }
14960
TEST_F(FormatTest,Destructors)14961 TEST_F(FormatTest, Destructors) {
14962 verifyFormat("void F(int &i) { i.~int(); }");
14963 verifyFormat("void F(int &i) { i->~int(); }");
14964 }
14965
TEST_F(FormatTest,FormatsWithWebKitStyle)14966 TEST_F(FormatTest, FormatsWithWebKitStyle) {
14967 FormatStyle Style = getWebKitStyle();
14968
14969 // Don't indent in outer namespaces.
14970 verifyFormat("namespace outer {\n"
14971 "int i;\n"
14972 "namespace inner {\n"
14973 " int i;\n"
14974 "} // namespace inner\n"
14975 "} // namespace outer\n"
14976 "namespace other_outer {\n"
14977 "int i;\n"
14978 "}",
14979 Style);
14980
14981 // Don't indent case labels.
14982 verifyFormat("switch (variable) {\n"
14983 "case 1:\n"
14984 "case 2:\n"
14985 " doSomething();\n"
14986 " break;\n"
14987 "default:\n"
14988 " ++variable;\n"
14989 "}",
14990 Style);
14991
14992 // Wrap before binary operators.
14993 EXPECT_EQ("void f()\n"
14994 "{\n"
14995 " if (aaaaaaaaaaaaaaaa\n"
14996 " && bbbbbbbbbbbbbbbbbbbbbbbb\n"
14997 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
14998 " return;\n"
14999 "}",
15000 format("void f() {\n"
15001 "if (aaaaaaaaaaaaaaaa\n"
15002 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
15003 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
15004 "return;\n"
15005 "}",
15006 Style));
15007
15008 // Allow functions on a single line.
15009 verifyFormat("void f() { return; }", Style);
15010
15011 // Allow empty blocks on a single line and insert a space in empty blocks.
15012 EXPECT_EQ("void f() { }", format("void f() {}", Style));
15013 EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
15014 // However, don't merge non-empty short loops.
15015 EXPECT_EQ("while (true) {\n"
15016 " continue;\n"
15017 "}",
15018 format("while (true) { continue; }", Style));
15019
15020 // Constructor initializers are formatted one per line with the "," on the
15021 // new line.
15022 verifyFormat("Constructor()\n"
15023 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
15024 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
15025 " aaaaaaaaaaaaaa)\n"
15026 " , aaaaaaaaaaaaaaaaaaaaaaa()\n"
15027 "{\n"
15028 "}",
15029 Style);
15030 verifyFormat("SomeClass::Constructor()\n"
15031 " : a(a)\n"
15032 "{\n"
15033 "}",
15034 Style);
15035 EXPECT_EQ("SomeClass::Constructor()\n"
15036 " : a(a)\n"
15037 "{\n"
15038 "}",
15039 format("SomeClass::Constructor():a(a){}", Style));
15040 verifyFormat("SomeClass::Constructor()\n"
15041 " : a(a)\n"
15042 " , b(b)\n"
15043 " , c(c)\n"
15044 "{\n"
15045 "}",
15046 Style);
15047 verifyFormat("SomeClass::Constructor()\n"
15048 " : a(a)\n"
15049 "{\n"
15050 " foo();\n"
15051 " bar();\n"
15052 "}",
15053 Style);
15054
15055 // Access specifiers should be aligned left.
15056 verifyFormat("class C {\n"
15057 "public:\n"
15058 " int i;\n"
15059 "};",
15060 Style);
15061
15062 // Do not align comments.
15063 verifyFormat("int a; // Do not\n"
15064 "double b; // align comments.",
15065 Style);
15066
15067 // Do not align operands.
15068 EXPECT_EQ("ASSERT(aaaa\n"
15069 " || bbbb);",
15070 format("ASSERT ( aaaa\n||bbbb);", Style));
15071
15072 // Accept input's line breaks.
15073 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
15074 " || bbbbbbbbbbbbbbb) {\n"
15075 " i++;\n"
15076 "}",
15077 format("if (aaaaaaaaaaaaaaa\n"
15078 "|| bbbbbbbbbbbbbbb) { i++; }",
15079 Style));
15080 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
15081 " i++;\n"
15082 "}",
15083 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
15084
15085 // Don't automatically break all macro definitions (llvm.org/PR17842).
15086 verifyFormat("#define aNumber 10", Style);
15087 // However, generally keep the line breaks that the user authored.
15088 EXPECT_EQ("#define aNumber \\\n"
15089 " 10",
15090 format("#define aNumber \\\n"
15091 " 10",
15092 Style));
15093
15094 // Keep empty and one-element array literals on a single line.
15095 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
15096 " copyItems:YES];",
15097 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
15098 "copyItems:YES];",
15099 Style));
15100 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
15101 " copyItems:YES];",
15102 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
15103 " copyItems:YES];",
15104 Style));
15105 // FIXME: This does not seem right, there should be more indentation before
15106 // the array literal's entries. Nested blocks have the same problem.
15107 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
15108 " @\"a\",\n"
15109 " @\"a\"\n"
15110 "]\n"
15111 " copyItems:YES];",
15112 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
15113 " @\"a\",\n"
15114 " @\"a\"\n"
15115 " ]\n"
15116 " copyItems:YES];",
15117 Style));
15118 EXPECT_EQ(
15119 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
15120 " copyItems:YES];",
15121 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
15122 " copyItems:YES];",
15123 Style));
15124
15125 verifyFormat("[self.a b:c c:d];", Style);
15126 EXPECT_EQ("[self.a b:c\n"
15127 " c:d];",
15128 format("[self.a b:c\n"
15129 "c:d];",
15130 Style));
15131 }
15132
TEST_F(FormatTest,FormatsLambdas)15133 TEST_F(FormatTest, FormatsLambdas) {
15134 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
15135 verifyFormat(
15136 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
15137 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
15138 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
15139 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
15140 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
15141 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
15142 verifyFormat("auto c = [a = [b = 42] {}] {};\n");
15143 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
15144 verifyFormat("int x = f(*+[] {});");
15145 verifyFormat("void f() {\n"
15146 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
15147 "}\n");
15148 verifyFormat("void f() {\n"
15149 " other(x.begin(), //\n"
15150 " x.end(), //\n"
15151 " [&](int, int) { return 1; });\n"
15152 "}\n");
15153 verifyFormat("void f() {\n"
15154 " other.other.other.other.other(\n"
15155 " x.begin(), x.end(),\n"
15156 " [something, rather](int, int, int, int, int, int, int) { "
15157 "return 1; });\n"
15158 "}\n");
15159 verifyFormat(
15160 "void f() {\n"
15161 " other.other.other.other.other(\n"
15162 " x.begin(), x.end(),\n"
15163 " [something, rather](int, int, int, int, int, int, int) {\n"
15164 " //\n"
15165 " });\n"
15166 "}\n");
15167 verifyFormat("SomeFunction([]() { // A cool function...\n"
15168 " return 43;\n"
15169 "});");
15170 EXPECT_EQ("SomeFunction([]() {\n"
15171 "#define A a\n"
15172 " return 43;\n"
15173 "});",
15174 format("SomeFunction([](){\n"
15175 "#define A a\n"
15176 "return 43;\n"
15177 "});"));
15178 verifyFormat("void f() {\n"
15179 " SomeFunction([](decltype(x), A *a) {});\n"
15180 " SomeFunction([](typeof(x), A *a) {});\n"
15181 " SomeFunction([](_Atomic(x), A *a) {});\n"
15182 " SomeFunction([](__underlying_type(x), A *a) {});\n"
15183 "}");
15184 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
15185 " [](const aaaaaaaaaa &a) { return a; });");
15186 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
15187 " SomeOtherFunctioooooooooooooooooooooooooon();\n"
15188 "});");
15189 verifyFormat("Constructor()\n"
15190 " : Field([] { // comment\n"
15191 " int i;\n"
15192 " }) {}");
15193 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
15194 " return some_parameter.size();\n"
15195 "};");
15196 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
15197 " [](const string &s) { return s; };");
15198 verifyFormat("int i = aaaaaa ? 1 //\n"
15199 " : [] {\n"
15200 " return 2; //\n"
15201 " }();");
15202 verifyFormat("llvm::errs() << \"number of twos is \"\n"
15203 " << std::count_if(v.begin(), v.end(), [](int x) {\n"
15204 " return x == 2; // force break\n"
15205 " });");
15206 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
15207 " [=](int iiiiiiiiiiii) {\n"
15208 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
15209 " aaaaaaaaaaaaaaaaaaaaaaa;\n"
15210 " });",
15211 getLLVMStyleWithColumns(60));
15212 verifyFormat("SomeFunction({[&] {\n"
15213 " // comment\n"
15214 " },\n"
15215 " [&] {\n"
15216 " // comment\n"
15217 " }});");
15218 verifyFormat("SomeFunction({[&] {\n"
15219 " // comment\n"
15220 "}});");
15221 verifyFormat(
15222 "virtual aaaaaaaaaaaaaaaa(\n"
15223 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
15224 " aaaaa aaaaaaaaa);");
15225
15226 // Lambdas with return types.
15227 verifyFormat("int c = []() -> int { return 2; }();\n");
15228 verifyFormat("int c = []() -> int * { return 2; }();\n");
15229 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
15230 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
15231 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
15232 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
15233 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
15234 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
15235 verifyFormat("[a, a]() -> a<1> {};");
15236 verifyFormat("[]() -> foo<5 + 2> { return {}; };");
15237 verifyFormat("[]() -> foo<5 - 2> { return {}; };");
15238 verifyFormat("[]() -> foo<5 / 2> { return {}; };");
15239 verifyFormat("[]() -> foo<5 * 2> { return {}; };");
15240 verifyFormat("[]() -> foo<5 % 2> { return {}; };");
15241 verifyFormat("[]() -> foo<5 << 2> { return {}; };");
15242 verifyFormat("[]() -> foo<!5> { return {}; };");
15243 verifyFormat("[]() -> foo<~5> { return {}; };");
15244 verifyFormat("[]() -> foo<5 | 2> { return {}; };");
15245 verifyFormat("[]() -> foo<5 || 2> { return {}; };");
15246 verifyFormat("[]() -> foo<5 & 2> { return {}; };");
15247 verifyFormat("[]() -> foo<5 && 2> { return {}; };");
15248 verifyFormat("[]() -> foo<5 == 2> { return {}; };");
15249 verifyFormat("[]() -> foo<5 != 2> { return {}; };");
15250 verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
15251 verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
15252 verifyFormat("[]() -> foo<5 < 2> { return {}; };");
15253 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
15254 verifyFormat("namespace bar {\n"
15255 "// broken:\n"
15256 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
15257 "} // namespace bar");
15258 verifyFormat("namespace bar {\n"
15259 "// broken:\n"
15260 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
15261 "} // namespace bar");
15262 verifyFormat("namespace bar {\n"
15263 "// broken:\n"
15264 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
15265 "} // namespace bar");
15266 verifyFormat("namespace bar {\n"
15267 "// broken:\n"
15268 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
15269 "} // namespace bar");
15270 verifyFormat("namespace bar {\n"
15271 "// broken:\n"
15272 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
15273 "} // namespace bar");
15274 verifyFormat("namespace bar {\n"
15275 "// broken:\n"
15276 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
15277 "} // namespace bar");
15278 verifyFormat("namespace bar {\n"
15279 "// broken:\n"
15280 "auto foo{[]() -> foo<!5> { return {}; }};\n"
15281 "} // namespace bar");
15282 verifyFormat("namespace bar {\n"
15283 "// broken:\n"
15284 "auto foo{[]() -> foo<~5> { return {}; }};\n"
15285 "} // namespace bar");
15286 verifyFormat("namespace bar {\n"
15287 "// broken:\n"
15288 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
15289 "} // namespace bar");
15290 verifyFormat("namespace bar {\n"
15291 "// broken:\n"
15292 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
15293 "} // namespace bar");
15294 verifyFormat("namespace bar {\n"
15295 "// broken:\n"
15296 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
15297 "} // namespace bar");
15298 verifyFormat("namespace bar {\n"
15299 "// broken:\n"
15300 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
15301 "} // namespace bar");
15302 verifyFormat("namespace bar {\n"
15303 "// broken:\n"
15304 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
15305 "} // namespace bar");
15306 verifyFormat("namespace bar {\n"
15307 "// broken:\n"
15308 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
15309 "} // namespace bar");
15310 verifyFormat("namespace bar {\n"
15311 "// broken:\n"
15312 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
15313 "} // namespace bar");
15314 verifyFormat("namespace bar {\n"
15315 "// broken:\n"
15316 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
15317 "} // namespace bar");
15318 verifyFormat("namespace bar {\n"
15319 "// broken:\n"
15320 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
15321 "} // namespace bar");
15322 verifyFormat("namespace bar {\n"
15323 "// broken:\n"
15324 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
15325 "} // namespace bar");
15326 verifyFormat("[]() -> a<1> {};");
15327 verifyFormat("[]() -> a<1> { ; };");
15328 verifyFormat("[]() -> a<1> { ; }();");
15329 verifyFormat("[a, a]() -> a<true> {};");
15330 verifyFormat("[]() -> a<true> {};");
15331 verifyFormat("[]() -> a<true> { ; };");
15332 verifyFormat("[]() -> a<true> { ; }();");
15333 verifyFormat("[a, a]() -> a<false> {};");
15334 verifyFormat("[]() -> a<false> {};");
15335 verifyFormat("[]() -> a<false> { ; };");
15336 verifyFormat("[]() -> a<false> { ; }();");
15337 verifyFormat("auto foo{[]() -> foo<false> { ; }};");
15338 verifyFormat("namespace bar {\n"
15339 "auto foo{[]() -> foo<false> { ; }};\n"
15340 "} // namespace bar");
15341 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
15342 " int j) -> int {\n"
15343 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
15344 "};");
15345 verifyFormat(
15346 "aaaaaaaaaaaaaaaaaaaaaa(\n"
15347 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
15348 " return aaaaaaaaaaaaaaaaa;\n"
15349 " });",
15350 getLLVMStyleWithColumns(70));
15351 verifyFormat("[]() //\n"
15352 " -> int {\n"
15353 " return 1; //\n"
15354 "};");
15355 verifyFormat("[]() -> Void<T...> {};");
15356 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
15357
15358 // Lambdas with explicit template argument lists.
15359 verifyFormat(
15360 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
15361
15362 // Multiple lambdas in the same parentheses change indentation rules. These
15363 // lambdas are forced to start on new lines.
15364 verifyFormat("SomeFunction(\n"
15365 " []() {\n"
15366 " //\n"
15367 " },\n"
15368 " []() {\n"
15369 " //\n"
15370 " });");
15371
15372 // A lambda passed as arg0 is always pushed to the next line.
15373 verifyFormat("SomeFunction(\n"
15374 " [this] {\n"
15375 " //\n"
15376 " },\n"
15377 " 1);\n");
15378
15379 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
15380 // the arg0 case above.
15381 auto Style = getGoogleStyle();
15382 Style.BinPackArguments = false;
15383 verifyFormat("SomeFunction(\n"
15384 " a,\n"
15385 " [this] {\n"
15386 " //\n"
15387 " },\n"
15388 " b);\n",
15389 Style);
15390 verifyFormat("SomeFunction(\n"
15391 " a,\n"
15392 " [this] {\n"
15393 " //\n"
15394 " },\n"
15395 " b);\n");
15396
15397 // A lambda with a very long line forces arg0 to be pushed out irrespective of
15398 // the BinPackArguments value (as long as the code is wide enough).
15399 verifyFormat(
15400 "something->SomeFunction(\n"
15401 " a,\n"
15402 " [this] {\n"
15403 " "
15404 "D0000000000000000000000000000000000000000000000000000000000001();\n"
15405 " },\n"
15406 " b);\n");
15407
15408 // A multi-line lambda is pulled up as long as the introducer fits on the
15409 // previous line and there are no further args.
15410 verifyFormat("function(1, [this, that] {\n"
15411 " //\n"
15412 "});\n");
15413 verifyFormat("function([this, that] {\n"
15414 " //\n"
15415 "});\n");
15416 // FIXME: this format is not ideal and we should consider forcing the first
15417 // arg onto its own line.
15418 verifyFormat("function(a, b, c, //\n"
15419 " d, [this, that] {\n"
15420 " //\n"
15421 " });\n");
15422
15423 // Multiple lambdas are treated correctly even when there is a short arg0.
15424 verifyFormat("SomeFunction(\n"
15425 " 1,\n"
15426 " [this] {\n"
15427 " //\n"
15428 " },\n"
15429 " [this] {\n"
15430 " //\n"
15431 " },\n"
15432 " 1);\n");
15433
15434 // More complex introducers.
15435 verifyFormat("return [i, args...] {};");
15436
15437 // Not lambdas.
15438 verifyFormat("constexpr char hello[]{\"hello\"};");
15439 verifyFormat("double &operator[](int i) { return 0; }\n"
15440 "int i;");
15441 verifyFormat("std::unique_ptr<int[]> foo() {}");
15442 verifyFormat("int i = a[a][a]->f();");
15443 verifyFormat("int i = (*b)[a]->f();");
15444
15445 // Other corner cases.
15446 verifyFormat("void f() {\n"
15447 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
15448 " );\n"
15449 "}");
15450
15451 // Lambdas created through weird macros.
15452 verifyFormat("void f() {\n"
15453 " MACRO((const AA &a) { return 1; });\n"
15454 " MACRO((AA &a) { return 1; });\n"
15455 "}");
15456
15457 verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
15458 " doo_dah();\n"
15459 " doo_dah();\n"
15460 " })) {\n"
15461 "}");
15462 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
15463 " doo_dah();\n"
15464 " doo_dah();\n"
15465 " })) {\n"
15466 "}");
15467 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
15468 " doo_dah();\n"
15469 " doo_dah();\n"
15470 " })) {\n"
15471 "}");
15472 verifyFormat("auto lambda = []() {\n"
15473 " int a = 2\n"
15474 "#if A\n"
15475 " + 2\n"
15476 "#endif\n"
15477 " ;\n"
15478 "};");
15479
15480 // Lambdas with complex multiline introducers.
15481 verifyFormat(
15482 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
15483 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
15484 " -> ::std::unordered_set<\n"
15485 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
15486 " //\n"
15487 " });");
15488
15489 FormatStyle DoNotMerge = getLLVMStyle();
15490 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15491 verifyFormat("auto c = []() {\n"
15492 " return b;\n"
15493 "};",
15494 "auto c = []() { return b; };", DoNotMerge);
15495 verifyFormat("auto c = []() {\n"
15496 "};",
15497 " auto c = []() {};", DoNotMerge);
15498
15499 FormatStyle MergeEmptyOnly = getLLVMStyle();
15500 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
15501 verifyFormat("auto c = []() {\n"
15502 " return b;\n"
15503 "};",
15504 "auto c = []() {\n"
15505 " return b;\n"
15506 " };",
15507 MergeEmptyOnly);
15508 verifyFormat("auto c = []() {};",
15509 "auto c = []() {\n"
15510 "};",
15511 MergeEmptyOnly);
15512
15513 FormatStyle MergeInline = getLLVMStyle();
15514 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
15515 verifyFormat("auto c = []() {\n"
15516 " return b;\n"
15517 "};",
15518 "auto c = []() { return b; };", MergeInline);
15519 verifyFormat("function([]() { return b; })", "function([]() { return b; })",
15520 MergeInline);
15521 verifyFormat("function([]() { return b; }, a)",
15522 "function([]() { return b; }, a)", MergeInline);
15523 verifyFormat("function(a, []() { return b; })",
15524 "function(a, []() { return b; })", MergeInline);
15525
15526 // Check option "BraceWrapping.BeforeLambdaBody" and different state of
15527 // AllowShortLambdasOnASingleLine
15528 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
15529 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
15530 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
15531 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
15532 FormatStyle::ShortLambdaStyle::SLS_None;
15533 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
15534 " []()\n"
15535 " {\n"
15536 " return 17;\n"
15537 " });",
15538 LLVMWithBeforeLambdaBody);
15539 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
15540 " []()\n"
15541 " {\n"
15542 " });",
15543 LLVMWithBeforeLambdaBody);
15544 verifyFormat("auto fct_SLS_None = []()\n"
15545 "{\n"
15546 " return 17;\n"
15547 "};",
15548 LLVMWithBeforeLambdaBody);
15549 verifyFormat("TwoNestedLambdas_SLS_None(\n"
15550 " []()\n"
15551 " {\n"
15552 " return Call(\n"
15553 " []()\n"
15554 " {\n"
15555 " return 17;\n"
15556 " });\n"
15557 " });",
15558 LLVMWithBeforeLambdaBody);
15559 verifyFormat("void Fct()\n"
15560 "{\n"
15561 " return {[]()\n"
15562 " {\n"
15563 " return 17;\n"
15564 " }};\n"
15565 "}",
15566 LLVMWithBeforeLambdaBody);
15567
15568 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
15569 FormatStyle::ShortLambdaStyle::SLS_Empty;
15570 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
15571 " []()\n"
15572 " {\n"
15573 " return 17;\n"
15574 " });",
15575 LLVMWithBeforeLambdaBody);
15576 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
15577 LLVMWithBeforeLambdaBody);
15578 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
15579 "ongFunctionName_SLS_Empty(\n"
15580 " []() {});",
15581 LLVMWithBeforeLambdaBody);
15582 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
15583 " []()\n"
15584 " {\n"
15585 " return 17;\n"
15586 " });",
15587 LLVMWithBeforeLambdaBody);
15588 verifyFormat("auto fct_SLS_Empty = []()\n"
15589 "{\n"
15590 " return 17;\n"
15591 "};",
15592 LLVMWithBeforeLambdaBody);
15593 verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
15594 " []()\n"
15595 " {\n"
15596 " return Call([]() {});\n"
15597 " });",
15598 LLVMWithBeforeLambdaBody);
15599 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
15600 " []()\n"
15601 " {\n"
15602 " return Call([]() {});\n"
15603 " });",
15604 LLVMWithBeforeLambdaBody);
15605 verifyFormat(
15606 "FctWithLongLineInLambda_SLS_Empty(\n"
15607 " []()\n"
15608 " {\n"
15609 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
15610 " AndShouldNotBeConsiderAsInline,\n"
15611 " LambdaBodyMustBeBreak);\n"
15612 " });",
15613 LLVMWithBeforeLambdaBody);
15614
15615 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
15616 FormatStyle::ShortLambdaStyle::SLS_Inline;
15617 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
15618 LLVMWithBeforeLambdaBody);
15619 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
15620 LLVMWithBeforeLambdaBody);
15621 verifyFormat("auto fct_SLS_Inline = []()\n"
15622 "{\n"
15623 " return 17;\n"
15624 "};",
15625 LLVMWithBeforeLambdaBody);
15626 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
15627 "17; }); });",
15628 LLVMWithBeforeLambdaBody);
15629 verifyFormat(
15630 "FctWithLongLineInLambda_SLS_Inline(\n"
15631 " []()\n"
15632 " {\n"
15633 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
15634 " AndShouldNotBeConsiderAsInline,\n"
15635 " LambdaBodyMustBeBreak);\n"
15636 " });",
15637 LLVMWithBeforeLambdaBody);
15638 verifyFormat("FctWithMultipleParams_SLS_Inline("
15639 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
15640 " []() { return 17; });",
15641 LLVMWithBeforeLambdaBody);
15642 verifyFormat(
15643 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
15644 LLVMWithBeforeLambdaBody);
15645
15646 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
15647 FormatStyle::ShortLambdaStyle::SLS_All;
15648 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
15649 LLVMWithBeforeLambdaBody);
15650 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
15651 LLVMWithBeforeLambdaBody);
15652 verifyFormat("auto fct_SLS_All = []() { return 17; };",
15653 LLVMWithBeforeLambdaBody);
15654 verifyFormat("FctWithOneParam_SLS_All(\n"
15655 " []()\n"
15656 " {\n"
15657 " // A cool function...\n"
15658 " return 43;\n"
15659 " });",
15660 LLVMWithBeforeLambdaBody);
15661 verifyFormat("FctWithMultipleParams_SLS_All("
15662 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
15663 " []() { return 17; });",
15664 LLVMWithBeforeLambdaBody);
15665 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
15666 LLVMWithBeforeLambdaBody);
15667 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
15668 LLVMWithBeforeLambdaBody);
15669 verifyFormat(
15670 "FctWithLongLineInLambda_SLS_All(\n"
15671 " []()\n"
15672 " {\n"
15673 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
15674 " AndShouldNotBeConsiderAsInline,\n"
15675 " LambdaBodyMustBeBreak);\n"
15676 " });",
15677 LLVMWithBeforeLambdaBody);
15678 verifyFormat(
15679 "auto fct_SLS_All = []()\n"
15680 "{\n"
15681 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
15682 " AndShouldNotBeConsiderAsInline,\n"
15683 " LambdaBodyMustBeBreak);\n"
15684 "};",
15685 LLVMWithBeforeLambdaBody);
15686 LLVMWithBeforeLambdaBody.BinPackParameters = false;
15687 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
15688 LLVMWithBeforeLambdaBody);
15689 verifyFormat(
15690 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
15691 " FirstParam,\n"
15692 " SecondParam,\n"
15693 " ThirdParam,\n"
15694 " FourthParam);",
15695 LLVMWithBeforeLambdaBody);
15696 verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
15697 " []() { return "
15698 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
15699 " FirstParam,\n"
15700 " SecondParam,\n"
15701 " ThirdParam,\n"
15702 " FourthParam);",
15703 LLVMWithBeforeLambdaBody);
15704 verifyFormat(
15705 "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
15706 " SecondParam,\n"
15707 " ThirdParam,\n"
15708 " FourthParam,\n"
15709 " []() { return SomeValueNotSoLong; });",
15710 LLVMWithBeforeLambdaBody);
15711 verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
15712 " []()\n"
15713 " {\n"
15714 " return "
15715 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
15716 "eConsiderAsInline;\n"
15717 " });",
15718 LLVMWithBeforeLambdaBody);
15719 verifyFormat(
15720 "FctWithLongLineInLambda_SLS_All(\n"
15721 " []()\n"
15722 " {\n"
15723 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
15724 " AndShouldNotBeConsiderAsInline,\n"
15725 " LambdaBodyMustBeBreak);\n"
15726 " });",
15727 LLVMWithBeforeLambdaBody);
15728 verifyFormat("FctWithTwoParams_SLS_All(\n"
15729 " []()\n"
15730 " {\n"
15731 " // A cool function...\n"
15732 " return 43;\n"
15733 " },\n"
15734 " 87);",
15735 LLVMWithBeforeLambdaBody);
15736 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
15737 LLVMWithBeforeLambdaBody);
15738 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
15739 LLVMWithBeforeLambdaBody);
15740 verifyFormat(
15741 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
15742 LLVMWithBeforeLambdaBody);
15743 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
15744 "}); }, x);",
15745 LLVMWithBeforeLambdaBody);
15746 verifyFormat("TwoNestedLambdas_SLS_All(\n"
15747 " []()\n"
15748 " {\n"
15749 " // A cool function...\n"
15750 " return Call([]() { return 17; });\n"
15751 " });",
15752 LLVMWithBeforeLambdaBody);
15753 verifyFormat("TwoNestedLambdas_SLS_All(\n"
15754 " []()\n"
15755 " {\n"
15756 " return Call(\n"
15757 " []()\n"
15758 " {\n"
15759 " // A cool function...\n"
15760 " return 17;\n"
15761 " });\n"
15762 " });",
15763 LLVMWithBeforeLambdaBody);
15764 }
15765
TEST_F(FormatTest,LambdaWithLineComments)15766 TEST_F(FormatTest, LambdaWithLineComments) {
15767 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
15768 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
15769 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
15770 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
15771 FormatStyle::ShortLambdaStyle::SLS_All;
15772
15773 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
15774 verifyFormat("auto k = []() // comment\n"
15775 "{ return; }",
15776 LLVMWithBeforeLambdaBody);
15777 verifyFormat("auto k = []() /* comment */ { return; }",
15778 LLVMWithBeforeLambdaBody);
15779 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
15780 LLVMWithBeforeLambdaBody);
15781 verifyFormat("auto k = []() // X\n"
15782 "{ return; }",
15783 LLVMWithBeforeLambdaBody);
15784 verifyFormat(
15785 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
15786 "{ return; }",
15787 LLVMWithBeforeLambdaBody);
15788 }
15789
TEST_F(FormatTest,EmptyLinesInLambdas)15790 TEST_F(FormatTest, EmptyLinesInLambdas) {
15791 verifyFormat("auto lambda = []() {\n"
15792 " x(); //\n"
15793 "};",
15794 "auto lambda = []() {\n"
15795 "\n"
15796 " x(); //\n"
15797 "\n"
15798 "};");
15799 }
15800
TEST_F(FormatTest,FormatsBlocks)15801 TEST_F(FormatTest, FormatsBlocks) {
15802 FormatStyle ShortBlocks = getLLVMStyle();
15803 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
15804 verifyFormat("int (^Block)(int, int);", ShortBlocks);
15805 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
15806 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
15807 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
15808 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
15809 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
15810
15811 verifyFormat("foo(^{ bar(); });", ShortBlocks);
15812 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
15813 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
15814
15815 verifyFormat("[operation setCompletionBlock:^{\n"
15816 " [self onOperationDone];\n"
15817 "}];");
15818 verifyFormat("int i = {[operation setCompletionBlock:^{\n"
15819 " [self onOperationDone];\n"
15820 "}]};");
15821 verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
15822 " f();\n"
15823 "}];");
15824 verifyFormat("int a = [operation block:^int(int *i) {\n"
15825 " return 1;\n"
15826 "}];");
15827 verifyFormat("[myObject doSomethingWith:arg1\n"
15828 " aaa:^int(int *a) {\n"
15829 " return 1;\n"
15830 " }\n"
15831 " bbb:f(a * bbbbbbbb)];");
15832
15833 verifyFormat("[operation setCompletionBlock:^{\n"
15834 " [self.delegate newDataAvailable];\n"
15835 "}];",
15836 getLLVMStyleWithColumns(60));
15837 verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
15838 " NSString *path = [self sessionFilePath];\n"
15839 " if (path) {\n"
15840 " // ...\n"
15841 " }\n"
15842 "});");
15843 verifyFormat("[[SessionService sharedService]\n"
15844 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
15845 " if (window) {\n"
15846 " [self windowDidLoad:window];\n"
15847 " } else {\n"
15848 " [self errorLoadingWindow];\n"
15849 " }\n"
15850 " }];");
15851 verifyFormat("void (^largeBlock)(void) = ^{\n"
15852 " // ...\n"
15853 "};\n",
15854 getLLVMStyleWithColumns(40));
15855 verifyFormat("[[SessionService sharedService]\n"
15856 " loadWindowWithCompletionBlock: //\n"
15857 " ^(SessionWindow *window) {\n"
15858 " if (window) {\n"
15859 " [self windowDidLoad:window];\n"
15860 " } else {\n"
15861 " [self errorLoadingWindow];\n"
15862 " }\n"
15863 " }];",
15864 getLLVMStyleWithColumns(60));
15865 verifyFormat("[myObject doSomethingWith:arg1\n"
15866 " firstBlock:^(Foo *a) {\n"
15867 " // ...\n"
15868 " int i;\n"
15869 " }\n"
15870 " secondBlock:^(Bar *b) {\n"
15871 " // ...\n"
15872 " int i;\n"
15873 " }\n"
15874 " thirdBlock:^Foo(Bar *b) {\n"
15875 " // ...\n"
15876 " int i;\n"
15877 " }];");
15878 verifyFormat("[myObject doSomethingWith:arg1\n"
15879 " firstBlock:-1\n"
15880 " secondBlock:^(Bar *b) {\n"
15881 " // ...\n"
15882 " int i;\n"
15883 " }];");
15884
15885 verifyFormat("f(^{\n"
15886 " @autoreleasepool {\n"
15887 " if (a) {\n"
15888 " g();\n"
15889 " }\n"
15890 " }\n"
15891 "});");
15892 verifyFormat("Block b = ^int *(A *a, B *b) {}");
15893 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
15894 "};");
15895
15896 FormatStyle FourIndent = getLLVMStyle();
15897 FourIndent.ObjCBlockIndentWidth = 4;
15898 verifyFormat("[operation setCompletionBlock:^{\n"
15899 " [self onOperationDone];\n"
15900 "}];",
15901 FourIndent);
15902 }
15903
TEST_F(FormatTest,FormatsBlocksWithZeroColumnWidth)15904 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
15905 FormatStyle ZeroColumn = getLLVMStyle();
15906 ZeroColumn.ColumnLimit = 0;
15907
15908 verifyFormat("[[SessionService sharedService] "
15909 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
15910 " if (window) {\n"
15911 " [self windowDidLoad:window];\n"
15912 " } else {\n"
15913 " [self errorLoadingWindow];\n"
15914 " }\n"
15915 "}];",
15916 ZeroColumn);
15917 EXPECT_EQ("[[SessionService sharedService]\n"
15918 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
15919 " if (window) {\n"
15920 " [self windowDidLoad:window];\n"
15921 " } else {\n"
15922 " [self errorLoadingWindow];\n"
15923 " }\n"
15924 " }];",
15925 format("[[SessionService sharedService]\n"
15926 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
15927 " if (window) {\n"
15928 " [self windowDidLoad:window];\n"
15929 " } else {\n"
15930 " [self errorLoadingWindow];\n"
15931 " }\n"
15932 "}];",
15933 ZeroColumn));
15934 verifyFormat("[myObject doSomethingWith:arg1\n"
15935 " firstBlock:^(Foo *a) {\n"
15936 " // ...\n"
15937 " int i;\n"
15938 " }\n"
15939 " secondBlock:^(Bar *b) {\n"
15940 " // ...\n"
15941 " int i;\n"
15942 " }\n"
15943 " thirdBlock:^Foo(Bar *b) {\n"
15944 " // ...\n"
15945 " int i;\n"
15946 " }];",
15947 ZeroColumn);
15948 verifyFormat("f(^{\n"
15949 " @autoreleasepool {\n"
15950 " if (a) {\n"
15951 " g();\n"
15952 " }\n"
15953 " }\n"
15954 "});",
15955 ZeroColumn);
15956 verifyFormat("void (^largeBlock)(void) = ^{\n"
15957 " // ...\n"
15958 "};",
15959 ZeroColumn);
15960
15961 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
15962 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
15963 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn));
15964 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
15965 EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
15966 " int i;\n"
15967 "};",
15968 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn));
15969 }
15970
TEST_F(FormatTest,SupportsCRLF)15971 TEST_F(FormatTest, SupportsCRLF) {
15972 EXPECT_EQ("int a;\r\n"
15973 "int b;\r\n"
15974 "int c;\r\n",
15975 format("int a;\r\n"
15976 " int b;\r\n"
15977 " int c;\r\n",
15978 getLLVMStyle()));
15979 EXPECT_EQ("int a;\r\n"
15980 "int b;\r\n"
15981 "int c;\r\n",
15982 format("int a;\r\n"
15983 " int b;\n"
15984 " int c;\r\n",
15985 getLLVMStyle()));
15986 EXPECT_EQ("int a;\n"
15987 "int b;\n"
15988 "int c;\n",
15989 format("int a;\r\n"
15990 " int b;\n"
15991 " int c;\n",
15992 getLLVMStyle()));
15993 EXPECT_EQ("\"aaaaaaa \"\r\n"
15994 "\"bbbbbbb\";\r\n",
15995 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
15996 EXPECT_EQ("#define A \\\r\n"
15997 " b; \\\r\n"
15998 " c; \\\r\n"
15999 " d;\r\n",
16000 format("#define A \\\r\n"
16001 " b; \\\r\n"
16002 " c; d; \r\n",
16003 getGoogleStyle()));
16004
16005 EXPECT_EQ("/*\r\n"
16006 "multi line block comments\r\n"
16007 "should not introduce\r\n"
16008 "an extra carriage return\r\n"
16009 "*/\r\n",
16010 format("/*\r\n"
16011 "multi line block comments\r\n"
16012 "should not introduce\r\n"
16013 "an extra carriage return\r\n"
16014 "*/\r\n"));
16015 EXPECT_EQ("/*\r\n"
16016 "\r\n"
16017 "*/",
16018 format("/*\r\n"
16019 " \r\r\r\n"
16020 "*/"));
16021
16022 FormatStyle style = getLLVMStyle();
16023
16024 style.DeriveLineEnding = true;
16025 style.UseCRLF = false;
16026 EXPECT_EQ("union FooBarBazQux {\n"
16027 " int foo;\n"
16028 " int bar;\n"
16029 " int baz;\n"
16030 "};",
16031 format("union FooBarBazQux {\r\n"
16032 " int foo;\n"
16033 " int bar;\r\n"
16034 " int baz;\n"
16035 "};",
16036 style));
16037 style.UseCRLF = true;
16038 EXPECT_EQ("union FooBarBazQux {\r\n"
16039 " int foo;\r\n"
16040 " int bar;\r\n"
16041 " int baz;\r\n"
16042 "};",
16043 format("union FooBarBazQux {\r\n"
16044 " int foo;\n"
16045 " int bar;\r\n"
16046 " int baz;\n"
16047 "};",
16048 style));
16049
16050 style.DeriveLineEnding = false;
16051 style.UseCRLF = false;
16052 EXPECT_EQ("union FooBarBazQux {\n"
16053 " int foo;\n"
16054 " int bar;\n"
16055 " int baz;\n"
16056 " int qux;\n"
16057 "};",
16058 format("union FooBarBazQux {\r\n"
16059 " int foo;\n"
16060 " int bar;\r\n"
16061 " int baz;\n"
16062 " int qux;\r\n"
16063 "};",
16064 style));
16065 style.UseCRLF = true;
16066 EXPECT_EQ("union FooBarBazQux {\r\n"
16067 " int foo;\r\n"
16068 " int bar;\r\n"
16069 " int baz;\r\n"
16070 " int qux;\r\n"
16071 "};",
16072 format("union FooBarBazQux {\r\n"
16073 " int foo;\n"
16074 " int bar;\r\n"
16075 " int baz;\n"
16076 " int qux;\n"
16077 "};",
16078 style));
16079
16080 style.DeriveLineEnding = true;
16081 style.UseCRLF = false;
16082 EXPECT_EQ("union FooBarBazQux {\r\n"
16083 " int foo;\r\n"
16084 " int bar;\r\n"
16085 " int baz;\r\n"
16086 " int qux;\r\n"
16087 "};",
16088 format("union FooBarBazQux {\r\n"
16089 " int foo;\n"
16090 " int bar;\r\n"
16091 " int baz;\n"
16092 " int qux;\r\n"
16093 "};",
16094 style));
16095 style.UseCRLF = true;
16096 EXPECT_EQ("union FooBarBazQux {\n"
16097 " int foo;\n"
16098 " int bar;\n"
16099 " int baz;\n"
16100 " int qux;\n"
16101 "};",
16102 format("union FooBarBazQux {\r\n"
16103 " int foo;\n"
16104 " int bar;\r\n"
16105 " int baz;\n"
16106 " int qux;\n"
16107 "};",
16108 style));
16109 }
16110
TEST_F(FormatTest,MunchSemicolonAfterBlocks)16111 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
16112 verifyFormat("MY_CLASS(C) {\n"
16113 " int i;\n"
16114 " int j;\n"
16115 "};");
16116 }
16117
TEST_F(FormatTest,ConfigurableContinuationIndentWidth)16118 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
16119 FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
16120 TwoIndent.ContinuationIndentWidth = 2;
16121
16122 EXPECT_EQ("int i =\n"
16123 " longFunction(\n"
16124 " arg);",
16125 format("int i = longFunction(arg);", TwoIndent));
16126
16127 FormatStyle SixIndent = getLLVMStyleWithColumns(20);
16128 SixIndent.ContinuationIndentWidth = 6;
16129
16130 EXPECT_EQ("int i =\n"
16131 " longFunction(\n"
16132 " arg);",
16133 format("int i = longFunction(arg);", SixIndent));
16134 }
16135
TEST_F(FormatTest,WrappedClosingParenthesisIndent)16136 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
16137 FormatStyle Style = getLLVMStyle();
16138 verifyFormat("int Foo::getter(\n"
16139 " //\n"
16140 ") const {\n"
16141 " return foo;\n"
16142 "}",
16143 Style);
16144 verifyFormat("void Foo::setter(\n"
16145 " //\n"
16146 ") {\n"
16147 " foo = 1;\n"
16148 "}",
16149 Style);
16150 }
16151
TEST_F(FormatTest,SpacesInAngles)16152 TEST_F(FormatTest, SpacesInAngles) {
16153 FormatStyle Spaces = getLLVMStyle();
16154 Spaces.SpacesInAngles = true;
16155
16156 verifyFormat("static_cast< int >(arg);", Spaces);
16157 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
16158 verifyFormat("f< int, float >();", Spaces);
16159 verifyFormat("template <> g() {}", Spaces);
16160 verifyFormat("template < std::vector< int > > f() {}", Spaces);
16161 verifyFormat("std::function< void(int, int) > fct;", Spaces);
16162 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
16163 Spaces);
16164
16165 Spaces.Standard = FormatStyle::LS_Cpp03;
16166 Spaces.SpacesInAngles = true;
16167 verifyFormat("A< A< int > >();", Spaces);
16168
16169 Spaces.SpacesInAngles = false;
16170 verifyFormat("A<A<int> >();", Spaces);
16171
16172 Spaces.Standard = FormatStyle::LS_Cpp11;
16173 Spaces.SpacesInAngles = true;
16174 verifyFormat("A< A< int > >();", Spaces);
16175
16176 Spaces.SpacesInAngles = false;
16177 verifyFormat("A<A<int>>();", Spaces);
16178 }
16179
TEST_F(FormatTest,SpaceAfterTemplateKeyword)16180 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
16181 FormatStyle Style = getLLVMStyle();
16182 Style.SpaceAfterTemplateKeyword = false;
16183 verifyFormat("template<int> void foo();", Style);
16184 }
16185
TEST_F(FormatTest,TripleAngleBrackets)16186 TEST_F(FormatTest, TripleAngleBrackets) {
16187 verifyFormat("f<<<1, 1>>>();");
16188 verifyFormat("f<<<1, 1, 1, s>>>();");
16189 verifyFormat("f<<<a, b, c, d>>>();");
16190 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
16191 verifyFormat("f<param><<<1, 1>>>();");
16192 verifyFormat("f<1><<<1, 1>>>();");
16193 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
16194 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
16195 "aaaaaaaaaaa<<<\n 1, 1>>>();");
16196 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
16197 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
16198 }
16199
TEST_F(FormatTest,MergeLessLessAtEnd)16200 TEST_F(FormatTest, MergeLessLessAtEnd) {
16201 verifyFormat("<<");
16202 EXPECT_EQ("< < <", format("\\\n<<<"));
16203 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
16204 "aaallvm::outs() <<");
16205 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
16206 "aaaallvm::outs()\n <<");
16207 }
16208
TEST_F(FormatTest,HandleUnbalancedImplicitBracesAcrossPPBranches)16209 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
16210 std::string code = "#if A\n"
16211 "#if B\n"
16212 "a.\n"
16213 "#endif\n"
16214 " a = 1;\n"
16215 "#else\n"
16216 "#endif\n"
16217 "#if C\n"
16218 "#else\n"
16219 "#endif\n";
16220 EXPECT_EQ(code, format(code));
16221 }
16222
TEST_F(FormatTest,HandleConflictMarkers)16223 TEST_F(FormatTest, HandleConflictMarkers) {
16224 // Git/SVN conflict markers.
16225 EXPECT_EQ("int a;\n"
16226 "void f() {\n"
16227 " callme(some(parameter1,\n"
16228 "<<<<<<< text by the vcs\n"
16229 " parameter2),\n"
16230 "||||||| text by the vcs\n"
16231 " parameter2),\n"
16232 " parameter3,\n"
16233 "======= text by the vcs\n"
16234 " parameter2, parameter3),\n"
16235 ">>>>>>> text by the vcs\n"
16236 " otherparameter);\n",
16237 format("int a;\n"
16238 "void f() {\n"
16239 " callme(some(parameter1,\n"
16240 "<<<<<<< text by the vcs\n"
16241 " parameter2),\n"
16242 "||||||| text by the vcs\n"
16243 " parameter2),\n"
16244 " parameter3,\n"
16245 "======= text by the vcs\n"
16246 " parameter2,\n"
16247 " parameter3),\n"
16248 ">>>>>>> text by the vcs\n"
16249 " otherparameter);\n"));
16250
16251 // Perforce markers.
16252 EXPECT_EQ("void f() {\n"
16253 " function(\n"
16254 ">>>> text by the vcs\n"
16255 " parameter,\n"
16256 "==== text by the vcs\n"
16257 " parameter,\n"
16258 "==== text by the vcs\n"
16259 " parameter,\n"
16260 "<<<< text by the vcs\n"
16261 " parameter);\n",
16262 format("void f() {\n"
16263 " function(\n"
16264 ">>>> text by the vcs\n"
16265 " parameter,\n"
16266 "==== text by the vcs\n"
16267 " parameter,\n"
16268 "==== text by the vcs\n"
16269 " parameter,\n"
16270 "<<<< text by the vcs\n"
16271 " parameter);\n"));
16272
16273 EXPECT_EQ("<<<<<<<\n"
16274 "|||||||\n"
16275 "=======\n"
16276 ">>>>>>>",
16277 format("<<<<<<<\n"
16278 "|||||||\n"
16279 "=======\n"
16280 ">>>>>>>"));
16281
16282 EXPECT_EQ("<<<<<<<\n"
16283 "|||||||\n"
16284 "int i;\n"
16285 "=======\n"
16286 ">>>>>>>",
16287 format("<<<<<<<\n"
16288 "|||||||\n"
16289 "int i;\n"
16290 "=======\n"
16291 ">>>>>>>"));
16292
16293 // FIXME: Handle parsing of macros around conflict markers correctly:
16294 EXPECT_EQ("#define Macro \\\n"
16295 "<<<<<<<\n"
16296 "Something \\\n"
16297 "|||||||\n"
16298 "Else \\\n"
16299 "=======\n"
16300 "Other \\\n"
16301 ">>>>>>>\n"
16302 " End int i;\n",
16303 format("#define Macro \\\n"
16304 "<<<<<<<\n"
16305 " Something \\\n"
16306 "|||||||\n"
16307 " Else \\\n"
16308 "=======\n"
16309 " Other \\\n"
16310 ">>>>>>>\n"
16311 " End\n"
16312 "int i;\n"));
16313 }
16314
TEST_F(FormatTest,DisableRegions)16315 TEST_F(FormatTest, DisableRegions) {
16316 EXPECT_EQ("int i;\n"
16317 "// clang-format off\n"
16318 " int j;\n"
16319 "// clang-format on\n"
16320 "int k;",
16321 format(" int i;\n"
16322 " // clang-format off\n"
16323 " int j;\n"
16324 " // clang-format on\n"
16325 " int k;"));
16326 EXPECT_EQ("int i;\n"
16327 "/* clang-format off */\n"
16328 " int j;\n"
16329 "/* clang-format on */\n"
16330 "int k;",
16331 format(" int i;\n"
16332 " /* clang-format off */\n"
16333 " int j;\n"
16334 " /* clang-format on */\n"
16335 " int k;"));
16336
16337 // Don't reflow comments within disabled regions.
16338 EXPECT_EQ("// clang-format off\n"
16339 "// long long long long long long line\n"
16340 "/* clang-format on */\n"
16341 "/* long long long\n"
16342 " * long long long\n"
16343 " * line */\n"
16344 "int i;\n"
16345 "/* clang-format off */\n"
16346 "/* long long long long long long line */\n",
16347 format("// clang-format off\n"
16348 "// long long long long long long line\n"
16349 "/* clang-format on */\n"
16350 "/* long long long long long long line */\n"
16351 "int i;\n"
16352 "/* clang-format off */\n"
16353 "/* long long long long long long line */\n",
16354 getLLVMStyleWithColumns(20)));
16355 }
16356
TEST_F(FormatTest,DoNotCrashOnInvalidInput)16357 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
16358 format("? ) =");
16359 verifyNoCrash("#define a\\\n /**/}");
16360 }
16361
TEST_F(FormatTest,FormatsTableGenCode)16362 TEST_F(FormatTest, FormatsTableGenCode) {
16363 FormatStyle Style = getLLVMStyle();
16364 Style.Language = FormatStyle::LK_TableGen;
16365 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
16366 }
16367
TEST_F(FormatTest,ArrayOfTemplates)16368 TEST_F(FormatTest, ArrayOfTemplates) {
16369 EXPECT_EQ("auto a = new unique_ptr<int>[10];",
16370 format("auto a = new unique_ptr<int > [ 10];"));
16371
16372 FormatStyle Spaces = getLLVMStyle();
16373 Spaces.SpacesInSquareBrackets = true;
16374 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
16375 format("auto a = new unique_ptr<int > [10];", Spaces));
16376 }
16377
TEST_F(FormatTest,ArrayAsTemplateType)16378 TEST_F(FormatTest, ArrayAsTemplateType) {
16379 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
16380 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
16381
16382 FormatStyle Spaces = getLLVMStyle();
16383 Spaces.SpacesInSquareBrackets = true;
16384 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
16385 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
16386 }
16387
TEST_F(FormatTest,NoSpaceAfterSuper)16388 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
16389
TEST(FormatStyle,GetStyleWithEmptyFileName)16390 TEST(FormatStyle, GetStyleWithEmptyFileName) {
16391 llvm::vfs::InMemoryFileSystem FS;
16392 auto Style1 = getStyle("file", "", "Google", "", &FS);
16393 ASSERT_TRUE((bool)Style1);
16394 ASSERT_EQ(*Style1, getGoogleStyle());
16395 }
16396
TEST(FormatStyle,GetStyleOfFile)16397 TEST(FormatStyle, GetStyleOfFile) {
16398 llvm::vfs::InMemoryFileSystem FS;
16399 // Test 1: format file in the same directory.
16400 ASSERT_TRUE(
16401 FS.addFile("/a/.clang-format", 0,
16402 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
16403 ASSERT_TRUE(
16404 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
16405 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
16406 ASSERT_TRUE((bool)Style1);
16407 ASSERT_EQ(*Style1, getLLVMStyle());
16408
16409 // Test 2.1: fallback to default.
16410 ASSERT_TRUE(
16411 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
16412 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
16413 ASSERT_TRUE((bool)Style2);
16414 ASSERT_EQ(*Style2, getMozillaStyle());
16415
16416 // Test 2.2: no format on 'none' fallback style.
16417 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
16418 ASSERT_TRUE((bool)Style2);
16419 ASSERT_EQ(*Style2, getNoStyle());
16420
16421 // Test 2.3: format if config is found with no based style while fallback is
16422 // 'none'.
16423 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
16424 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
16425 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
16426 ASSERT_TRUE((bool)Style2);
16427 ASSERT_EQ(*Style2, getLLVMStyle());
16428
16429 // Test 2.4: format if yaml with no based style, while fallback is 'none'.
16430 Style2 = getStyle("{}", "a.h", "none", "", &FS);
16431 ASSERT_TRUE((bool)Style2);
16432 ASSERT_EQ(*Style2, getLLVMStyle());
16433
16434 // Test 3: format file in parent directory.
16435 ASSERT_TRUE(
16436 FS.addFile("/c/.clang-format", 0,
16437 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
16438 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
16439 llvm::MemoryBuffer::getMemBuffer("int i;")));
16440 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
16441 ASSERT_TRUE((bool)Style3);
16442 ASSERT_EQ(*Style3, getGoogleStyle());
16443
16444 // Test 4: error on invalid fallback style
16445 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
16446 ASSERT_FALSE((bool)Style4);
16447 llvm::consumeError(Style4.takeError());
16448
16449 // Test 5: error on invalid yaml on command line
16450 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
16451 ASSERT_FALSE((bool)Style5);
16452 llvm::consumeError(Style5.takeError());
16453
16454 // Test 6: error on invalid style
16455 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
16456 ASSERT_FALSE((bool)Style6);
16457 llvm::consumeError(Style6.takeError());
16458
16459 // Test 7: found config file, error on parsing it
16460 ASSERT_TRUE(
16461 FS.addFile("/d/.clang-format", 0,
16462 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
16463 "InvalidKey: InvalidValue")));
16464 ASSERT_TRUE(
16465 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
16466 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
16467 ASSERT_FALSE((bool)Style7a);
16468 llvm::consumeError(Style7a.takeError());
16469
16470 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
16471 ASSERT_TRUE((bool)Style7b);
16472
16473 // Test 8: inferred per-language defaults apply.
16474 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
16475 ASSERT_TRUE((bool)StyleTd);
16476 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
16477 }
16478
TEST_F(ReplacementTest,FormatCodeAfterReplacements)16479 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
16480 // Column limit is 20.
16481 std::string Code = "Type *a =\n"
16482 " new Type();\n"
16483 "g(iiiii, 0, jjjjj,\n"
16484 " 0, kkkkk, 0, mm);\n"
16485 "int bad = format ;";
16486 std::string Expected = "auto a = new Type();\n"
16487 "g(iiiii, nullptr,\n"
16488 " jjjjj, nullptr,\n"
16489 " kkkkk, nullptr,\n"
16490 " mm);\n"
16491 "int bad = format ;";
16492 FileID ID = Context.createInMemoryFile("format.cpp", Code);
16493 tooling::Replacements Replaces = toReplacements(
16494 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
16495 "auto "),
16496 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
16497 "nullptr"),
16498 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
16499 "nullptr"),
16500 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
16501 "nullptr")});
16502
16503 format::FormatStyle Style = format::getLLVMStyle();
16504 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
16505 auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
16506 EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
16507 << llvm::toString(FormattedReplaces.takeError()) << "\n";
16508 auto Result = applyAllReplacements(Code, *FormattedReplaces);
16509 EXPECT_TRUE(static_cast<bool>(Result));
16510 EXPECT_EQ(Expected, *Result);
16511 }
16512
TEST_F(ReplacementTest,SortIncludesAfterReplacement)16513 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
16514 std::string Code = "#include \"a.h\"\n"
16515 "#include \"c.h\"\n"
16516 "\n"
16517 "int main() {\n"
16518 " return 0;\n"
16519 "}";
16520 std::string Expected = "#include \"a.h\"\n"
16521 "#include \"b.h\"\n"
16522 "#include \"c.h\"\n"
16523 "\n"
16524 "int main() {\n"
16525 " return 0;\n"
16526 "}";
16527 FileID ID = Context.createInMemoryFile("fix.cpp", Code);
16528 tooling::Replacements Replaces = toReplacements(
16529 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
16530 "#include \"b.h\"\n")});
16531
16532 format::FormatStyle Style = format::getLLVMStyle();
16533 Style.SortIncludes = true;
16534 auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
16535 EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
16536 << llvm::toString(FormattedReplaces.takeError()) << "\n";
16537 auto Result = applyAllReplacements(Code, *FormattedReplaces);
16538 EXPECT_TRUE(static_cast<bool>(Result));
16539 EXPECT_EQ(Expected, *Result);
16540 }
16541
TEST_F(FormatTest,FormatSortsUsingDeclarations)16542 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
16543 EXPECT_EQ("using std::cin;\n"
16544 "using std::cout;",
16545 format("using std::cout;\n"
16546 "using std::cin;",
16547 getGoogleStyle()));
16548 }
16549
TEST_F(FormatTest,UTF8CharacterLiteralCpp03)16550 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
16551 format::FormatStyle Style = format::getLLVMStyle();
16552 Style.Standard = FormatStyle::LS_Cpp03;
16553 // cpp03 recognize this string as identifier u8 and literal character 'a'
16554 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
16555 }
16556
TEST_F(FormatTest,UTF8CharacterLiteralCpp11)16557 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
16558 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
16559 // all modes, including C++11, C++14 and C++17
16560 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
16561 }
16562
TEST_F(FormatTest,DoNotFormatLikelyXml)16563 TEST_F(FormatTest, DoNotFormatLikelyXml) {
16564 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
16565 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
16566 }
16567
TEST_F(FormatTest,StructuredBindings)16568 TEST_F(FormatTest, StructuredBindings) {
16569 // Structured bindings is a C++17 feature.
16570 // all modes, including C++11, C++14 and C++17
16571 verifyFormat("auto [a, b] = f();");
16572 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
16573 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();"));
16574 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();"));
16575 EXPECT_EQ("auto const volatile [a, b] = f();",
16576 format("auto const volatile[a, b] = f();"));
16577 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();"));
16578 EXPECT_EQ("auto &[a, b, c] = f();",
16579 format("auto &[ a , b,c ] = f();"));
16580 EXPECT_EQ("auto &&[a, b, c] = f();",
16581 format("auto &&[ a , b,c ] = f();"));
16582 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();"));
16583 EXPECT_EQ("auto const volatile &&[a, b] = f();",
16584 format("auto const volatile &&[a, b] = f();"));
16585 EXPECT_EQ("auto const &&[a, b] = f();",
16586 format("auto const && [a, b] = f();"));
16587 EXPECT_EQ("const auto &[a, b] = f();",
16588 format("const auto & [a, b] = f();"));
16589 EXPECT_EQ("const auto volatile &&[a, b] = f();",
16590 format("const auto volatile &&[a, b] = f();"));
16591 EXPECT_EQ("volatile const auto &&[a, b] = f();",
16592 format("volatile const auto &&[a, b] = f();"));
16593 EXPECT_EQ("const auto &&[a, b] = f();",
16594 format("const auto && [a, b] = f();"));
16595
16596 // Make sure we don't mistake structured bindings for lambdas.
16597 FormatStyle PointerMiddle = getLLVMStyle();
16598 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16599 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
16600 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
16601 verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
16602 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
16603 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
16604 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
16605 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
16606 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
16607 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
16608 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
16609 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
16610 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
16611
16612 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
16613 format("for (const auto && [a, b] : some_range) {\n}"));
16614 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
16615 format("for (const auto & [a, b] : some_range) {\n}"));
16616 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
16617 format("for (const auto[a, b] : some_range) {\n}"));
16618 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);"));
16619 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);"));
16620 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);"));
16621 EXPECT_EQ("auto const &[x, y](expr);",
16622 format("auto const & [x,y] (expr);"));
16623 EXPECT_EQ("auto const &&[x, y](expr);",
16624 format("auto const && [x,y] (expr);"));
16625 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};"));
16626 EXPECT_EQ("auto const &[x, y]{expr};",
16627 format("auto const & [x,y] {expr};"));
16628 EXPECT_EQ("auto const &&[x, y]{expr};",
16629 format("auto const && [x,y] {expr};"));
16630
16631 format::FormatStyle Spaces = format::getLLVMStyle();
16632 Spaces.SpacesInSquareBrackets = true;
16633 verifyFormat("auto [ a, b ] = f();", Spaces);
16634 verifyFormat("auto &&[ a, b ] = f();", Spaces);
16635 verifyFormat("auto &[ a, b ] = f();", Spaces);
16636 verifyFormat("auto const &&[ a, b ] = f();", Spaces);
16637 verifyFormat("auto const &[ a, b ] = f();", Spaces);
16638 }
16639
TEST_F(FormatTest,FileAndCode)16640 TEST_F(FormatTest, FileAndCode) {
16641 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
16642 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
16643 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
16644 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
16645 EXPECT_EQ(FormatStyle::LK_ObjC,
16646 guessLanguage("foo.h", "@interface Foo\n@end\n"));
16647 EXPECT_EQ(
16648 FormatStyle::LK_ObjC,
16649 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
16650 EXPECT_EQ(FormatStyle::LK_ObjC,
16651 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
16652 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
16653 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
16654 EXPECT_EQ(FormatStyle::LK_ObjC,
16655 guessLanguage("foo", "@interface Foo\n@end\n"));
16656 EXPECT_EQ(FormatStyle::LK_ObjC,
16657 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
16658 EXPECT_EQ(
16659 FormatStyle::LK_ObjC,
16660 guessLanguage("foo.h",
16661 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
16662 EXPECT_EQ(
16663 FormatStyle::LK_Cpp,
16664 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
16665 }
16666
TEST_F(FormatTest,GuessLanguageWithCpp11AttributeSpecifiers)16667 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
16668 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
16669 EXPECT_EQ(FormatStyle::LK_ObjC,
16670 guessLanguage("foo.h", "array[[calculator getIndex]];"));
16671 EXPECT_EQ(FormatStyle::LK_Cpp,
16672 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
16673 EXPECT_EQ(
16674 FormatStyle::LK_Cpp,
16675 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
16676 EXPECT_EQ(FormatStyle::LK_ObjC,
16677 guessLanguage("foo.h", "[[noreturn foo] bar];"));
16678 EXPECT_EQ(FormatStyle::LK_Cpp,
16679 guessLanguage("foo.h", "[[clang::fallthrough]];"));
16680 EXPECT_EQ(FormatStyle::LK_ObjC,
16681 guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
16682 EXPECT_EQ(FormatStyle::LK_Cpp,
16683 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
16684 EXPECT_EQ(FormatStyle::LK_Cpp,
16685 guessLanguage("foo.h", "[[using clang: fallthrough]];"));
16686 EXPECT_EQ(FormatStyle::LK_ObjC,
16687 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
16688 EXPECT_EQ(FormatStyle::LK_Cpp,
16689 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
16690 EXPECT_EQ(
16691 FormatStyle::LK_Cpp,
16692 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
16693 EXPECT_EQ(
16694 FormatStyle::LK_Cpp,
16695 guessLanguage("foo.h",
16696 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
16697 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
16698 }
16699
TEST_F(FormatTest,GuessLanguageWithCaret)16700 TEST_F(FormatTest, GuessLanguageWithCaret) {
16701 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
16702 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
16703 EXPECT_EQ(FormatStyle::LK_ObjC,
16704 guessLanguage("foo.h", "int(^)(char, float);"));
16705 EXPECT_EQ(FormatStyle::LK_ObjC,
16706 guessLanguage("foo.h", "int(^foo)(char, float);"));
16707 EXPECT_EQ(FormatStyle::LK_ObjC,
16708 guessLanguage("foo.h", "int(^foo[10])(char, float);"));
16709 EXPECT_EQ(FormatStyle::LK_ObjC,
16710 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
16711 EXPECT_EQ(
16712 FormatStyle::LK_ObjC,
16713 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
16714 }
16715
TEST_F(FormatTest,FormatsInlineAsmSymbolicNames)16716 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
16717 // ASM symbolic names are identifiers that must be surrounded by [] without
16718 // space in between:
16719 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
16720
16721 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
16722 verifyFormat(R"(//
16723 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
16724 )");
16725
16726 // A list of several ASM symbolic names.
16727 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
16728
16729 // ASM symbolic names in inline ASM with inputs and outputs.
16730 verifyFormat(R"(//
16731 asm("cmoveq %1, %2, %[result]"
16732 : [result] "=r"(result)
16733 : "r"(test), "r"(new), "[result]"(old));
16734 )");
16735
16736 // ASM symbolic names in inline ASM with no outputs.
16737 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
16738 }
16739
TEST_F(FormatTest,GuessedLanguageWithInlineAsmClobbers)16740 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
16741 EXPECT_EQ(FormatStyle::LK_Cpp,
16742 guessLanguage("foo.h", "void f() {\n"
16743 " asm (\"mov %[e], %[d]\"\n"
16744 " : [d] \"=rm\" (d)\n"
16745 " [e] \"rm\" (*e));\n"
16746 "}"));
16747 EXPECT_EQ(FormatStyle::LK_Cpp,
16748 guessLanguage("foo.h", "void f() {\n"
16749 " _asm (\"mov %[e], %[d]\"\n"
16750 " : [d] \"=rm\" (d)\n"
16751 " [e] \"rm\" (*e));\n"
16752 "}"));
16753 EXPECT_EQ(FormatStyle::LK_Cpp,
16754 guessLanguage("foo.h", "void f() {\n"
16755 " __asm (\"mov %[e], %[d]\"\n"
16756 " : [d] \"=rm\" (d)\n"
16757 " [e] \"rm\" (*e));\n"
16758 "}"));
16759 EXPECT_EQ(FormatStyle::LK_Cpp,
16760 guessLanguage("foo.h", "void f() {\n"
16761 " __asm__ (\"mov %[e], %[d]\"\n"
16762 " : [d] \"=rm\" (d)\n"
16763 " [e] \"rm\" (*e));\n"
16764 "}"));
16765 EXPECT_EQ(FormatStyle::LK_Cpp,
16766 guessLanguage("foo.h", "void f() {\n"
16767 " asm (\"mov %[e], %[d]\"\n"
16768 " : [d] \"=rm\" (d),\n"
16769 " [e] \"rm\" (*e));\n"
16770 "}"));
16771 EXPECT_EQ(FormatStyle::LK_Cpp,
16772 guessLanguage("foo.h", "void f() {\n"
16773 " asm volatile (\"mov %[e], %[d]\"\n"
16774 " : [d] \"=rm\" (d)\n"
16775 " [e] \"rm\" (*e));\n"
16776 "}"));
16777 }
16778
TEST_F(FormatTest,GuessLanguageWithChildLines)16779 TEST_F(FormatTest, GuessLanguageWithChildLines) {
16780 EXPECT_EQ(FormatStyle::LK_Cpp,
16781 guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
16782 EXPECT_EQ(FormatStyle::LK_ObjC,
16783 guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
16784 EXPECT_EQ(
16785 FormatStyle::LK_Cpp,
16786 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
16787 EXPECT_EQ(
16788 FormatStyle::LK_ObjC,
16789 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
16790 }
16791
TEST_F(FormatTest,TypenameMacros)16792 TEST_F(FormatTest, TypenameMacros) {
16793 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
16794
16795 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
16796 FormatStyle Google = getGoogleStyleWithColumns(0);
16797 Google.TypenameMacros = TypenameMacros;
16798 verifyFormat("struct foo {\n"
16799 " int bar;\n"
16800 " TAILQ_ENTRY(a) bleh;\n"
16801 "};",
16802 Google);
16803
16804 FormatStyle Macros = getLLVMStyle();
16805 Macros.TypenameMacros = TypenameMacros;
16806
16807 verifyFormat("STACK_OF(int) a;", Macros);
16808 verifyFormat("STACK_OF(int) *a;", Macros);
16809 verifyFormat("STACK_OF(int const *) *a;", Macros);
16810 verifyFormat("STACK_OF(int *const) *a;", Macros);
16811 verifyFormat("STACK_OF(int, string) a;", Macros);
16812 verifyFormat("STACK_OF(LIST(int)) a;", Macros);
16813 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
16814 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
16815 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
16816 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
16817 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
16818
16819 Macros.PointerAlignment = FormatStyle::PAS_Left;
16820 verifyFormat("STACK_OF(int)* a;", Macros);
16821 verifyFormat("STACK_OF(int*)* a;", Macros);
16822 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
16823 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
16824 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
16825 }
16826
TEST_F(FormatTest,AtomicQualifier)16827 TEST_F(FormatTest, AtomicQualifier) {
16828 // Check that we treate _Atomic as a type and not a function call
16829 FormatStyle Google = getGoogleStyleWithColumns(0);
16830 verifyFormat("struct foo {\n"
16831 " int a1;\n"
16832 " _Atomic(a) a2;\n"
16833 " _Atomic(_Atomic(int) *const) a3;\n"
16834 "};",
16835 Google);
16836 verifyFormat("_Atomic(uint64_t) a;");
16837 verifyFormat("_Atomic(uint64_t) *a;");
16838 verifyFormat("_Atomic(uint64_t const *) *a;");
16839 verifyFormat("_Atomic(uint64_t *const) *a;");
16840 verifyFormat("_Atomic(const uint64_t *) *a;");
16841 verifyFormat("_Atomic(uint64_t) a;");
16842 verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
16843 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
16844 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
16845 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
16846
16847 verifyFormat("_Atomic(uint64_t) *s(InitValue);");
16848 verifyFormat("_Atomic(uint64_t) *s{InitValue};");
16849 FormatStyle Style = getLLVMStyle();
16850 Style.PointerAlignment = FormatStyle::PAS_Left;
16851 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
16852 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
16853 verifyFormat("_Atomic(int)* a;", Style);
16854 verifyFormat("_Atomic(int*)* a;", Style);
16855 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
16856
16857 Style.SpacesInCStyleCastParentheses = true;
16858 Style.SpacesInParentheses = false;
16859 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
16860 Style.SpacesInCStyleCastParentheses = false;
16861 Style.SpacesInParentheses = true;
16862 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
16863 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
16864 }
16865
TEST_F(FormatTest,AmbersandInLamda)16866 TEST_F(FormatTest, AmbersandInLamda) {
16867 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
16868 FormatStyle AlignStyle = getLLVMStyle();
16869 AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
16870 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
16871 AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
16872 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
16873 }
16874
TEST_F(FormatTest,SpacesInConditionalStatement)16875 TEST_F(FormatTest, SpacesInConditionalStatement) {
16876 FormatStyle Spaces = getLLVMStyle();
16877 Spaces.SpacesInConditionalStatement = true;
16878 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces);
16879 verifyFormat("if ( !a )\n return;", Spaces);
16880 verifyFormat("if ( a )\n return;", Spaces);
16881 verifyFormat("if constexpr ( a )\n return;", Spaces);
16882 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces);
16883 verifyFormat("while ( a )\n return;", Spaces);
16884 verifyFormat("while ( (a && b) )\n return;", Spaces);
16885 verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
16886 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
16887 // Check that space on the left of "::" is inserted as expected at beginning
16888 // of condition.
16889 verifyFormat("while ( ::func() )\n return;", Spaces);
16890 }
16891
TEST_F(FormatTest,AlternativeOperators)16892 TEST_F(FormatTest, AlternativeOperators) {
16893 // Test case for ensuring alternate operators are not
16894 // combined with their right most neighbour.
16895 verifyFormat("int a and b;");
16896 verifyFormat("int a and_eq b;");
16897 verifyFormat("int a bitand b;");
16898 verifyFormat("int a bitor b;");
16899 verifyFormat("int a compl b;");
16900 verifyFormat("int a not b;");
16901 verifyFormat("int a not_eq b;");
16902 verifyFormat("int a or b;");
16903 verifyFormat("int a xor b;");
16904 verifyFormat("int a xor_eq b;");
16905 verifyFormat("return this not_eq bitand other;");
16906 verifyFormat("bool operator not_eq(const X bitand other)");
16907
16908 verifyFormat("int a and 5;");
16909 verifyFormat("int a and_eq 5;");
16910 verifyFormat("int a bitand 5;");
16911 verifyFormat("int a bitor 5;");
16912 verifyFormat("int a compl 5;");
16913 verifyFormat("int a not 5;");
16914 verifyFormat("int a not_eq 5;");
16915 verifyFormat("int a or 5;");
16916 verifyFormat("int a xor 5;");
16917 verifyFormat("int a xor_eq 5;");
16918
16919 verifyFormat("int a compl(5);");
16920 verifyFormat("int a not(5);");
16921
16922 /* FIXME handle alternate tokens
16923 * https://en.cppreference.com/w/cpp/language/operator_alternative
16924 // alternative tokens
16925 verifyFormat("compl foo();"); // ~foo();
16926 verifyFormat("foo() <%%>;"); // foo();
16927 verifyFormat("void foo() <%%>;"); // void foo(){}
16928 verifyFormat("int a <:1:>;"); // int a[1];[
16929 verifyFormat("%:define ABC abc"); // #define ABC abc
16930 verifyFormat("%:%:"); // ##
16931 */
16932 }
16933
TEST_F(FormatTest,STLWhileNotDefineChed)16934 TEST_F(FormatTest, STLWhileNotDefineChed) {
16935 verifyFormat("#if defined(while)\n"
16936 "#define while EMIT WARNING C4005\n"
16937 "#endif // while");
16938 }
16939
TEST_F(FormatTest,OperatorSpacing)16940 TEST_F(FormatTest, OperatorSpacing) {
16941 FormatStyle Style = getLLVMStyle();
16942 Style.PointerAlignment = FormatStyle::PAS_Right;
16943 verifyFormat("Foo::operator*();", Style);
16944 verifyFormat("Foo::operator void *();", Style);
16945 verifyFormat("Foo::operator void **();", Style);
16946 verifyFormat("Foo::operator void *&();", Style);
16947 verifyFormat("Foo::operator void *&&();", Style);
16948 verifyFormat("Foo::operator()(void *);", Style);
16949 verifyFormat("Foo::operator*(void *);", Style);
16950 verifyFormat("Foo::operator*();", Style);
16951 verifyFormat("Foo::operator**();", Style);
16952 verifyFormat("Foo::operator&();", Style);
16953 verifyFormat("Foo::operator<int> *();", Style);
16954 verifyFormat("Foo::operator<Foo> *();", Style);
16955 verifyFormat("Foo::operator<int> **();", Style);
16956 verifyFormat("Foo::operator<Foo> **();", Style);
16957 verifyFormat("Foo::operator<int> &();", Style);
16958 verifyFormat("Foo::operator<Foo> &();", Style);
16959 verifyFormat("Foo::operator<int> &&();", Style);
16960 verifyFormat("Foo::operator<Foo> &&();", Style);
16961 verifyFormat("Foo::operator<int> *&();", Style);
16962 verifyFormat("Foo::operator<Foo> *&();", Style);
16963 verifyFormat("Foo::operator<int> *&&();", Style);
16964 verifyFormat("Foo::operator<Foo> *&&();", Style);
16965 verifyFormat("operator*(int (*)(), class Foo);", Style);
16966
16967 verifyFormat("Foo::operator&();", Style);
16968 verifyFormat("Foo::operator void &();", Style);
16969 verifyFormat("Foo::operator()(void &);", Style);
16970 verifyFormat("Foo::operator&(void &);", Style);
16971 verifyFormat("Foo::operator&();", Style);
16972 verifyFormat("operator&(int (&)(), class Foo);", Style);
16973
16974 verifyFormat("Foo::operator&&();", Style);
16975 verifyFormat("Foo::operator**();", Style);
16976 verifyFormat("Foo::operator void &&();", Style);
16977 verifyFormat("Foo::operator()(void &&);", Style);
16978 verifyFormat("Foo::operator&&(void &&);", Style);
16979 verifyFormat("Foo::operator&&();", Style);
16980 verifyFormat("operator&&(int(&&)(), class Foo);", Style);
16981 verifyFormat("operator const nsTArrayRight<E> &()", Style);
16982 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
16983 Style);
16984 verifyFormat("operator void **()", Style);
16985 verifyFormat("operator const FooRight<Object> &()", Style);
16986 verifyFormat("operator const FooRight<Object> *()", Style);
16987 verifyFormat("operator const FooRight<Object> **()", Style);
16988 verifyFormat("operator const FooRight<Object> *&()", Style);
16989 verifyFormat("operator const FooRight<Object> *&&()", Style);
16990
16991 Style.PointerAlignment = FormatStyle::PAS_Left;
16992 verifyFormat("Foo::operator*();", Style);
16993 verifyFormat("Foo::operator**();", Style);
16994 verifyFormat("Foo::operator void*();", Style);
16995 verifyFormat("Foo::operator void**();", Style);
16996 verifyFormat("Foo::operator void*&();", Style);
16997 verifyFormat("Foo::operator/*comment*/ void*();", Style);
16998 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
16999 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
17000 verifyFormat("Foo::operator()(void*);", Style);
17001 verifyFormat("Foo::operator*(void*);", Style);
17002 verifyFormat("Foo::operator*();", Style);
17003 verifyFormat("Foo::operator<int>*();", Style);
17004 verifyFormat("Foo::operator<Foo>*();", Style);
17005 verifyFormat("Foo::operator<int>**();", Style);
17006 verifyFormat("Foo::operator<Foo>**();", Style);
17007 verifyFormat("Foo::operator<Foo>*&();", Style);
17008 verifyFormat("Foo::operator<int>&();", Style);
17009 verifyFormat("Foo::operator<Foo>&();", Style);
17010 verifyFormat("Foo::operator<int>&&();", Style);
17011 verifyFormat("Foo::operator<Foo>&&();", Style);
17012 verifyFormat("Foo::operator<int>*&();", Style);
17013 verifyFormat("Foo::operator<Foo>*&();", Style);
17014 verifyFormat("operator*(int (*)(), class Foo);", Style);
17015
17016 verifyFormat("Foo::operator&();", Style);
17017 verifyFormat("Foo::operator void&();", Style);
17018 verifyFormat("Foo::operator/*comment*/ void&();", Style);
17019 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
17020 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
17021 verifyFormat("Foo::operator()(void&);", Style);
17022 verifyFormat("Foo::operator&(void&);", Style);
17023 verifyFormat("Foo::operator&();", Style);
17024 verifyFormat("operator&(int (&)(), class Foo);", Style);
17025
17026 verifyFormat("Foo::operator&&();", Style);
17027 verifyFormat("Foo::operator void&&();", Style);
17028 verifyFormat("Foo::operator/*comment*/ void&&();", Style);
17029 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
17030 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
17031 verifyFormat("Foo::operator()(void&&);", Style);
17032 verifyFormat("Foo::operator&&(void&&);", Style);
17033 verifyFormat("Foo::operator&&();", Style);
17034 verifyFormat("operator&&(int(&&)(), class Foo);", Style);
17035 verifyFormat("operator const nsTArrayLeft<E>&()", Style);
17036 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
17037 Style);
17038 verifyFormat("operator void**()", Style);
17039 verifyFormat("operator const FooLeft<Object>&()", Style);
17040 verifyFormat("operator const FooLeft<Object>*()", Style);
17041 verifyFormat("operator const FooLeft<Object>**()", Style);
17042 verifyFormat("operator const FooLeft<Object>*&()", Style);
17043 verifyFormat("operator const FooLeft<Object>*&&()", Style);
17044
17045 // PR45107
17046 verifyFormat("operator Vector<String>&();", Style);
17047 verifyFormat("operator const Vector<String>&();", Style);
17048 verifyFormat("operator foo::Bar*();", Style);
17049 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
17050 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
17051 Style);
17052
17053 Style.PointerAlignment = FormatStyle::PAS_Middle;
17054 verifyFormat("Foo::operator*();", Style);
17055 verifyFormat("Foo::operator void *();", Style);
17056 verifyFormat("Foo::operator()(void *);", Style);
17057 verifyFormat("Foo::operator*(void *);", Style);
17058 verifyFormat("Foo::operator*();", Style);
17059 verifyFormat("operator*(int (*)(), class Foo);", Style);
17060
17061 verifyFormat("Foo::operator&();", Style);
17062 verifyFormat("Foo::operator void &();", Style);
17063 verifyFormat("Foo::operator()(void &);", Style);
17064 verifyFormat("Foo::operator&(void &);", Style);
17065 verifyFormat("Foo::operator&();", Style);
17066 verifyFormat("operator&(int (&)(), class Foo);", Style);
17067
17068 verifyFormat("Foo::operator&&();", Style);
17069 verifyFormat("Foo::operator void &&();", Style);
17070 verifyFormat("Foo::operator()(void &&);", Style);
17071 verifyFormat("Foo::operator&&(void &&);", Style);
17072 verifyFormat("Foo::operator&&();", Style);
17073 verifyFormat("operator&&(int(&&)(), class Foo);", Style);
17074 }
17075
TEST_F(FormatTest,OperatorPassedAsAFunctionPtr)17076 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
17077 FormatStyle Style = getLLVMStyle();
17078 // PR46157
17079 verifyFormat("foo(operator+, -42);", Style);
17080 verifyFormat("foo(operator++, -42);", Style);
17081 verifyFormat("foo(operator--, -42);", Style);
17082 verifyFormat("foo(-42, operator--);", Style);
17083 verifyFormat("foo(-42, operator, );", Style);
17084 verifyFormat("foo(operator, , -42);", Style);
17085 }
17086
TEST_F(FormatTest,WhitespaceSensitiveMacros)17087 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
17088 FormatStyle Style = getLLVMStyle();
17089 Style.WhitespaceSensitiveMacros.push_back("FOO");
17090
17091 // Don't use the helpers here, since 'mess up' will change the whitespace
17092 // and these are all whitespace sensitive by definition
17093 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
17094 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
17095 EXPECT_EQ(
17096 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
17097 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
17098 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
17099 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
17100 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
17101 " Still=Intentional);",
17102 format("FOO(String-ized&Messy+But,: :\n"
17103 " Still=Intentional);",
17104 Style));
17105 Style.AlignConsecutiveAssignments = true;
17106 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
17107 " Still=Intentional);",
17108 format("FOO(String-ized=&Messy+But,: :\n"
17109 " Still=Intentional);",
17110 Style));
17111
17112 Style.ColumnLimit = 21;
17113 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
17114 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
17115 }
17116
TEST_F(FormatTest,VeryLongNamespaceCommentSplit)17117 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
17118 // These tests are not in NamespaceFixer because that doesn't
17119 // test its interaction with line wrapping
17120 FormatStyle Style = getLLVMStyle();
17121 Style.ColumnLimit = 80;
17122 verifyFormat("namespace {\n"
17123 "int i;\n"
17124 "int j;\n"
17125 "} // namespace",
17126 Style);
17127
17128 verifyFormat("namespace AAA {\n"
17129 "int i;\n"
17130 "int j;\n"
17131 "} // namespace AAA",
17132 Style);
17133
17134 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
17135 "int i;\n"
17136 "int j;\n"
17137 "} // namespace Averyveryveryverylongnamespace",
17138 format("namespace Averyveryveryverylongnamespace {\n"
17139 "int i;\n"
17140 "int j;\n"
17141 "}",
17142 Style));
17143
17144 EXPECT_EQ(
17145 "namespace "
17146 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
17147 " went::mad::now {\n"
17148 "int i;\n"
17149 "int j;\n"
17150 "} // namespace\n"
17151 " // "
17152 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
17153 "went::mad::now",
17154 format("namespace "
17155 "would::it::save::you::a::lot::of::time::if_::i::"
17156 "just::gave::up::and_::went::mad::now {\n"
17157 "int i;\n"
17158 "int j;\n"
17159 "}",
17160 Style));
17161
17162 // This used to duplicate the comment again and again on subsequent runs
17163 EXPECT_EQ(
17164 "namespace "
17165 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
17166 " went::mad::now {\n"
17167 "int i;\n"
17168 "int j;\n"
17169 "} // namespace\n"
17170 " // "
17171 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
17172 "went::mad::now",
17173 format("namespace "
17174 "would::it::save::you::a::lot::of::time::if_::i::"
17175 "just::gave::up::and_::went::mad::now {\n"
17176 "int i;\n"
17177 "int j;\n"
17178 "} // namespace\n"
17179 " // "
17180 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
17181 "and_::went::mad::now",
17182 Style));
17183 }
17184
TEST_F(FormatTest,LikelyUnlikely)17185 TEST_F(FormatTest, LikelyUnlikely) {
17186 FormatStyle Style = getLLVMStyle();
17187
17188 verifyFormat("if (argc > 5) [[unlikely]] {\n"
17189 " return 29;\n"
17190 "}",
17191 Style);
17192
17193 verifyFormat("if (argc > 5) [[likely]] {\n"
17194 " return 29;\n"
17195 "}",
17196 Style);
17197
17198 verifyFormat("if (argc > 5) [[unlikely]] {\n"
17199 " return 29;\n"
17200 "} else [[likely]] {\n"
17201 " return 42;\n"
17202 "}\n",
17203 Style);
17204
17205 verifyFormat("if (argc > 5) [[unlikely]] {\n"
17206 " return 29;\n"
17207 "} else if (argc > 10) [[likely]] {\n"
17208 " return 99;\n"
17209 "} else {\n"
17210 " return 42;\n"
17211 "}\n",
17212 Style);
17213
17214 verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
17215 " return 29;\n"
17216 "}",
17217 Style);
17218 }
17219
TEST_F(FormatTest,PenaltyIndentedWhitespace)17220 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
17221 verifyFormat("Constructor()\n"
17222 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17223 " aaaa(aaaaaaaaaaaaaaaaaa, "
17224 "aaaaaaaaaaaaaaaaaat))");
17225 verifyFormat("Constructor()\n"
17226 " : aaaaaaaaaaaaa(aaaaaa), "
17227 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
17228
17229 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
17230 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
17231 verifyFormat("Constructor()\n"
17232 " : aaaaaa(aaaaaa),\n"
17233 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17234 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
17235 StyleWithWhitespacePenalty);
17236 verifyFormat("Constructor()\n"
17237 " : aaaaaaaaaaaaa(aaaaaa), "
17238 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
17239 StyleWithWhitespacePenalty);
17240 }
17241
TEST_F(FormatTest,LLVMDefaultStyle)17242 TEST_F(FormatTest, LLVMDefaultStyle) {
17243 FormatStyle Style = getLLVMStyle();
17244 verifyFormat("extern \"C\" {\n"
17245 "int foo();\n"
17246 "}",
17247 Style);
17248 }
TEST_F(FormatTest,GNUDefaultStyle)17249 TEST_F(FormatTest, GNUDefaultStyle) {
17250 FormatStyle Style = getGNUStyle();
17251 verifyFormat("extern \"C\"\n"
17252 "{\n"
17253 " int foo ();\n"
17254 "}",
17255 Style);
17256 }
TEST_F(FormatTest,MozillaDefaultStyle)17257 TEST_F(FormatTest, MozillaDefaultStyle) {
17258 FormatStyle Style = getMozillaStyle();
17259 verifyFormat("extern \"C\"\n"
17260 "{\n"
17261 " int foo();\n"
17262 "}",
17263 Style);
17264 }
TEST_F(FormatTest,GoogleDefaultStyle)17265 TEST_F(FormatTest, GoogleDefaultStyle) {
17266 FormatStyle Style = getGoogleStyle();
17267 verifyFormat("extern \"C\" {\n"
17268 "int foo();\n"
17269 "}",
17270 Style);
17271 }
TEST_F(FormatTest,ChromiumDefaultStyle)17272 TEST_F(FormatTest, ChromiumDefaultStyle) {
17273 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
17274 verifyFormat("extern \"C\" {\n"
17275 "int foo();\n"
17276 "}",
17277 Style);
17278 }
TEST_F(FormatTest,MicrosoftDefaultStyle)17279 TEST_F(FormatTest, MicrosoftDefaultStyle) {
17280 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
17281 verifyFormat("extern \"C\"\n"
17282 "{\n"
17283 " int foo();\n"
17284 "}",
17285 Style);
17286 }
TEST_F(FormatTest,WebKitDefaultStyle)17287 TEST_F(FormatTest, WebKitDefaultStyle) {
17288 FormatStyle Style = getWebKitStyle();
17289 verifyFormat("extern \"C\" {\n"
17290 "int foo();\n"
17291 "}",
17292 Style);
17293 }
17294
TEST_F(FormatTest,ConceptsAndRequires)17295 TEST_F(FormatTest, ConceptsAndRequires) {
17296 FormatStyle Style = getLLVMStyle();
17297 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
17298
17299 verifyFormat("template <typename T>\n"
17300 "concept Hashable = requires(T a) {\n"
17301 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
17302 "};",
17303 Style);
17304 verifyFormat("template <typename T>\n"
17305 "concept EqualityComparable = requires(T a, T b) {\n"
17306 " { a == b } -> bool;\n"
17307 "};",
17308 Style);
17309 verifyFormat("template <typename T>\n"
17310 "concept EqualityComparable = requires(T a, T b) {\n"
17311 " { a == b } -> bool;\n"
17312 " { a != b } -> bool;\n"
17313 "};",
17314 Style);
17315 verifyFormat("template <typename T>\n"
17316 "concept EqualityComparable = requires(T a, T b) {\n"
17317 " { a == b } -> bool;\n"
17318 " { a != b } -> bool;\n"
17319 "};",
17320 Style);
17321
17322 verifyFormat("template <typename It>\n"
17323 "requires Iterator<It>\n"
17324 "void sort(It begin, It end) {\n"
17325 " //....\n"
17326 "}",
17327 Style);
17328
17329 verifyFormat("template <typename T>\n"
17330 "concept Large = sizeof(T) > 10;",
17331 Style);
17332
17333 verifyFormat("template <typename T, typename U>\n"
17334 "concept FooableWith = requires(T t, U u) {\n"
17335 " typename T::foo_type;\n"
17336 " { t.foo(u) } -> typename T::foo_type;\n"
17337 " t++;\n"
17338 "};\n"
17339 "void doFoo(FooableWith<int> auto t) {\n"
17340 " t.foo(3);\n"
17341 "}",
17342 Style);
17343 verifyFormat("template <typename T>\n"
17344 "concept Context = sizeof(T) == 1;",
17345 Style);
17346 verifyFormat("template <typename T>\n"
17347 "concept Context = is_specialization_of_v<context, T>;",
17348 Style);
17349 verifyFormat("template <typename T>\n"
17350 "concept Node = std::is_object_v<T>;",
17351 Style);
17352 verifyFormat("template <typename T>\n"
17353 "concept Tree = true;",
17354 Style);
17355
17356 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
17357 " //...\n"
17358 "}",
17359 Style);
17360
17361 verifyFormat(
17362 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
17363 " //...\n"
17364 "}",
17365 Style);
17366
17367 verifyFormat(
17368 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
17369 " //...\n"
17370 "}",
17371 Style);
17372
17373 verifyFormat("template <typename T>\n"
17374 "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
17375 "Concept2<I> {\n"
17376 " //...\n"
17377 "}",
17378 Style);
17379
17380 verifyFormat("template <typename T>\n"
17381 "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
17382 "Concept2<I> {\n"
17383 " //...\n"
17384 "}",
17385 Style);
17386
17387 verifyFormat(
17388 "template <typename T>\n"
17389 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
17390 " //...\n"
17391 "}",
17392 Style);
17393
17394 verifyFormat(
17395 "template <typename T>\n"
17396 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
17397 " //...\n"
17398 "}",
17399 Style);
17400
17401 verifyFormat("template <typename It>\n"
17402 "requires Foo<It>() && Bar<It> {\n"
17403 " //....\n"
17404 "}",
17405 Style);
17406
17407 verifyFormat("template <typename It>\n"
17408 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
17409 " //....\n"
17410 "}",
17411 Style);
17412
17413 verifyFormat("template <typename It>\n"
17414 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
17415 " //....\n"
17416 "}",
17417 Style);
17418
17419 verifyFormat(
17420 "template <typename It>\n"
17421 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
17422 " //....\n"
17423 "}",
17424 Style);
17425
17426 Style.IndentRequires = true;
17427 verifyFormat("template <typename It>\n"
17428 " requires Iterator<It>\n"
17429 "void sort(It begin, It end) {\n"
17430 " //....\n"
17431 "}",
17432 Style);
17433 verifyFormat("template <std::size index_>\n"
17434 " requires(index_ < sizeof...(Children_))\n"
17435 "Tree auto &child() {\n"
17436 " // ...\n"
17437 "}",
17438 Style);
17439
17440 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
17441 verifyFormat("template <typename T>\n"
17442 "concept Hashable = requires (T a) {\n"
17443 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
17444 "};",
17445 Style);
17446
17447 verifyFormat("template <class T = void>\n"
17448 " requires EqualityComparable<T> || Same<T, void>\n"
17449 "struct equal_to;",
17450 Style);
17451
17452 verifyFormat("template <class T>\n"
17453 " requires requires {\n"
17454 " T{};\n"
17455 " T (int);\n"
17456 " }\n",
17457 Style);
17458
17459 Style.ColumnLimit = 78;
17460 verifyFormat("template <typename T>\n"
17461 "concept Context = Traits<typename T::traits_type> and\n"
17462 " Interface<typename T::interface_type> and\n"
17463 " Request<typename T::request_type> and\n"
17464 " Response<typename T::response_type> and\n"
17465 " ContextExtension<typename T::extension_type> and\n"
17466 " ::std::is_copy_constructable<T> and "
17467 "::std::is_move_constructable<T> and\n"
17468 " requires (T c) {\n"
17469 " { c.response; } -> Response;\n"
17470 "} and requires (T c) {\n"
17471 " { c.request; } -> Request;\n"
17472 "}\n",
17473 Style);
17474
17475 verifyFormat("template <typename T>\n"
17476 "concept Context = Traits<typename T::traits_type> or\n"
17477 " Interface<typename T::interface_type> or\n"
17478 " Request<typename T::request_type> or\n"
17479 " Response<typename T::response_type> or\n"
17480 " ContextExtension<typename T::extension_type> or\n"
17481 " ::std::is_copy_constructable<T> or "
17482 "::std::is_move_constructable<T> or\n"
17483 " requires (T c) {\n"
17484 " { c.response; } -> Response;\n"
17485 "} or requires (T c) {\n"
17486 " { c.request; } -> Request;\n"
17487 "}\n",
17488 Style);
17489
17490 verifyFormat("template <typename T>\n"
17491 "concept Context = Traits<typename T::traits_type> &&\n"
17492 " Interface<typename T::interface_type> &&\n"
17493 " Request<typename T::request_type> &&\n"
17494 " Response<typename T::response_type> &&\n"
17495 " ContextExtension<typename T::extension_type> &&\n"
17496 " ::std::is_copy_constructable<T> && "
17497 "::std::is_move_constructable<T> &&\n"
17498 " requires (T c) {\n"
17499 " { c.response; } -> Response;\n"
17500 "} && requires (T c) {\n"
17501 " { c.request; } -> Request;\n"
17502 "}\n",
17503 Style);
17504
17505 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
17506 "Constraint2<T>;");
17507
17508 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
17509 Style.BraceWrapping.AfterFunction = true;
17510 Style.BraceWrapping.AfterClass = true;
17511 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
17512 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
17513 verifyFormat("void Foo () requires (std::copyable<T>)\n"
17514 "{\n"
17515 " return\n"
17516 "}\n",
17517 Style);
17518
17519 verifyFormat("void Foo () requires std::copyable<T>\n"
17520 "{\n"
17521 " return\n"
17522 "}\n",
17523 Style);
17524
17525 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
17526 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
17527 "struct constant;",
17528 Style);
17529
17530 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
17531 " requires std::invocable<F, std::invoke_result_t<Args>...>\n"
17532 "struct constant;",
17533 Style);
17534
17535 verifyFormat("template <class T>\n"
17536 "class plane_with_very_very_very_long_name\n"
17537 "{\n"
17538 " constexpr plane_with_very_very_very_long_name () requires "
17539 "std::copyable<T>\n"
17540 " : plane_with_very_very_very_long_name (1)\n"
17541 " {\n"
17542 " }\n"
17543 "}\n",
17544 Style);
17545
17546 verifyFormat("template <class T>\n"
17547 "class plane_with_long_name\n"
17548 "{\n"
17549 " constexpr plane_with_long_name () requires std::copyable<T>\n"
17550 " : plane_with_long_name (1)\n"
17551 " {\n"
17552 " }\n"
17553 "}\n",
17554 Style);
17555
17556 Style.BreakBeforeConceptDeclarations = false;
17557 verifyFormat("template <typename T> concept Tree = true;", Style);
17558
17559 Style.IndentRequires = false;
17560 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
17561 "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
17562 "struct constant;",
17563 Style);
17564 }
17565 } // namespace
17566 } // namespace format
17567 } // namespace clang
17568