xref: /llvm-project/clang/unittests/Format/ConfigParseTest.cpp (revision 88934a82dced0116227e4ad9af8896d8fa0943b8)
1 //===- unittest/Format/ConfigParseTest.cpp - Config parsing 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 "llvm/Support/VirtualFileSystem.h"
12 #include "gtest/gtest.h"
13 
14 namespace clang {
15 namespace format {
16 namespace {
17 
18 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
19 
20 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
21   for (size_t i = 1; i < Styles.size(); ++i)                                   \
22   EXPECT_EQ(Styles[0], Styles[i])                                              \
23       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
24 
25 TEST(ConfigParseTest, GetsPredefinedStyleByName) {
26   SmallVector<FormatStyle, 3> Styles;
27   Styles.resize(3);
28 
29   Styles[0] = getLLVMStyle();
30   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
31   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
32   EXPECT_ALL_STYLES_EQUAL(Styles);
33 
34   Styles[0] = getGoogleStyle();
35   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
36   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
37   EXPECT_ALL_STYLES_EQUAL(Styles);
38 
39   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
40   EXPECT_TRUE(
41       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
42   EXPECT_TRUE(
43       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
44   EXPECT_ALL_STYLES_EQUAL(Styles);
45 
46   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
47   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
48   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
49   EXPECT_ALL_STYLES_EQUAL(Styles);
50 
51   Styles[0] = getMozillaStyle();
52   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
53   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
54   EXPECT_ALL_STYLES_EQUAL(Styles);
55 
56   Styles[0] = getWebKitStyle();
57   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
58   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
59   EXPECT_ALL_STYLES_EQUAL(Styles);
60 
61   Styles[0] = getGNUStyle();
62   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
63   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
64   EXPECT_ALL_STYLES_EQUAL(Styles);
65 
66   Styles[0] = getClangFormatStyle();
67   EXPECT_TRUE(
68       getPredefinedStyle("clang-format", FormatStyle::LK_Cpp, &Styles[1]));
69   EXPECT_TRUE(
70       getPredefinedStyle("Clang-format", FormatStyle::LK_Cpp, &Styles[2]));
71   EXPECT_ALL_STYLES_EQUAL(Styles);
72 
73   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
74 }
75 
76 TEST(ConfigParseTest, GetsCorrectBasedOnStyle) {
77   SmallVector<FormatStyle, 8> Styles;
78   Styles.resize(2);
79 
80   Styles[0] = getGoogleStyle();
81   Styles[1] = getLLVMStyle();
82   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
83   EXPECT_ALL_STYLES_EQUAL(Styles);
84 
85   Styles.resize(5);
86   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
87   Styles[1] = getLLVMStyle();
88   Styles[1].Language = FormatStyle::LK_JavaScript;
89   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
90 
91   Styles[2] = getLLVMStyle();
92   Styles[2].Language = FormatStyle::LK_JavaScript;
93   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
94                                   "BasedOnStyle: Google",
95                                   &Styles[2])
96                    .value());
97 
98   Styles[3] = getLLVMStyle();
99   Styles[3].Language = FormatStyle::LK_JavaScript;
100   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
101                                   "Language: JavaScript",
102                                   &Styles[3])
103                    .value());
104 
105   Styles[4] = getLLVMStyle();
106   Styles[4].Language = FormatStyle::LK_JavaScript;
107   EXPECT_EQ(0, parseConfiguration("---\n"
108                                   "BasedOnStyle: LLVM\n"
109                                   "IndentWidth: 123\n"
110                                   "---\n"
111                                   "BasedOnStyle: Google\n"
112                                   "Language: JavaScript",
113                                   &Styles[4])
114                    .value());
115   EXPECT_ALL_STYLES_EQUAL(Styles);
116 }
117 
118 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
119   Style.FIELD = false;                                                         \
120   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
121   EXPECT_TRUE(Style.FIELD);                                                    \
122   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
123   EXPECT_FALSE(Style.FIELD)
124 
125 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
126 
127 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
128   Style.STRUCT.FIELD = false;                                                  \
129   EXPECT_EQ(0,                                                                 \
130             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
131                 .value());                                                     \
132   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
133   EXPECT_EQ(0,                                                                 \
134             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
135                 .value());                                                     \
136   EXPECT_FALSE(Style.STRUCT.FIELD)
137 
138 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
139   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
140 
141 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
142   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
143   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
144   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
145 
146 #define CHECK_PARSE_NESTED_VALUE(TEXT, STRUCT, FIELD, VALUE)                   \
147   EXPECT_NE(VALUE, Style.STRUCT.FIELD) << "Initial value already the same!";   \
148   EXPECT_EQ(0, parseConfiguration(#STRUCT ":\n  " TEXT, &Style).value());      \
149   EXPECT_EQ(VALUE, Style.STRUCT.FIELD) << "Unexpected value after parsing!"
150 
151 TEST(ConfigParseTest, ParsesConfigurationBools) {
152   FormatStyle Style = {};
153   Style.Language = FormatStyle::LK_Cpp;
154   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
155   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
156   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
157   CHECK_PARSE_BOOL(AllowShortCompoundRequirementOnASingleLine);
158   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
159   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
160   CHECK_PARSE_BOOL(BinPackArguments);
161   CHECK_PARSE_BOOL(BinPackParameters);
162   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
163   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
164   CHECK_PARSE_BOOL(BreakStringLiterals);
165   CHECK_PARSE_BOOL(CompactNamespaces);
166   CHECK_PARSE_BOOL(DerivePointerAlignment);
167   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
168   CHECK_PARSE_BOOL(DisableFormat);
169   CHECK_PARSE_BOOL(IndentAccessModifiers);
170   CHECK_PARSE_BOOL(IndentCaseLabels);
171   CHECK_PARSE_BOOL(IndentCaseBlocks);
172   CHECK_PARSE_BOOL(IndentGotoLabels);
173   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
174   CHECK_PARSE_BOOL(IndentRequiresClause);
175   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
176   CHECK_PARSE_BOOL(InsertBraces);
177   CHECK_PARSE_BOOL(InsertNewlineAtEOF);
178   CHECK_PARSE_BOOL(KeepEmptyLinesAtEOF);
179   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
180   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
181   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
182   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
183   CHECK_PARSE_BOOL(ReflowComments);
184   CHECK_PARSE_BOOL(RemoveBracesLLVM);
185   CHECK_PARSE_BOOL(RemoveSemicolon);
186   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
187   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
188   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
189   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
190   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
191   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
192   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
193   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
194   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
195   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
196   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
197   CHECK_PARSE_BOOL(SpaceBeforeJsonColon);
198   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
199   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
200   CHECK_PARSE_BOOL(VerilogBreakBetweenInstancePorts);
201 
202   CHECK_PARSE_NESTED_BOOL(AlignConsecutiveShortCaseStatements, Enabled);
203   CHECK_PARSE_NESTED_BOOL(AlignConsecutiveShortCaseStatements,
204                           AcrossEmptyLines);
205   CHECK_PARSE_NESTED_BOOL(AlignConsecutiveShortCaseStatements, AcrossComments);
206   CHECK_PARSE_NESTED_BOOL(AlignConsecutiveShortCaseStatements, AlignCaseColons);
207   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
208   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
209   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
210   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
211   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
212   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
213   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
214   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
215   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
216   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
217   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
218   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
219   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
220   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
221   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
222   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
223   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
224   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
225   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
226   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
227                           AfterFunctionDeclarationName);
228   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
229                           AfterFunctionDefinitionName);
230   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
231   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
232   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
233   CHECK_PARSE_NESTED_BOOL(SpacesInParensOptions, InCStyleCasts);
234   CHECK_PARSE_NESTED_BOOL(SpacesInParensOptions, InConditionalStatements);
235   CHECK_PARSE_NESTED_BOOL(SpacesInParensOptions, InEmptyParentheses);
236   CHECK_PARSE_NESTED_BOOL(SpacesInParensOptions, Other);
237 }
238 
239 #undef CHECK_PARSE_BOOL
240 
241 TEST(ConfigParseTest, ParsesConfiguration) {
242   FormatStyle Style = {};
243   Style.Language = FormatStyle::LK_Cpp;
244   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
245   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
246               ConstructorInitializerIndentWidth, 1234u);
247   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
248   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
249   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
250   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
251   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
252               PenaltyBreakBeforeFirstCallParameter, 1234u);
253   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
254               PenaltyBreakTemplateDeclaration, 1234u);
255   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
256               1234u);
257   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
258   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
259               PenaltyReturnTypeOnItsOwnLine, 1234u);
260   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
261               SpacesBeforeTrailingComments, 1234u);
262   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
263   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
264   CHECK_PARSE("BracedInitializerIndentWidth: 34", BracedInitializerIndentWidth,
265               34);
266   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
267 
268   Style.QualifierAlignment = FormatStyle::QAS_Right;
269   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
270               FormatStyle::QAS_Leave);
271   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
272               FormatStyle::QAS_Right);
273   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
274               FormatStyle::QAS_Left);
275   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
276               FormatStyle::QAS_Custom);
277 
278   Style.QualifierOrder.clear();
279   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
280               std::vector<std::string>({"const", "volatile", "type"}));
281   Style.QualifierOrder.clear();
282   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
283               std::vector<std::string>({"const", "type"}));
284   Style.QualifierOrder.clear();
285   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
286               std::vector<std::string>({"volatile", "type"}));
287 
288 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
289   do {                                                                         \
290     Style.FIELD.Enabled = true;                                                \
291     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
292                 FormatStyle::AlignConsecutiveStyle(                            \
293                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
294                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
295                      /*PadOperators=*/true}));                                 \
296     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
297                 FormatStyle::AlignConsecutiveStyle(                            \
298                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
299                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
300                      /*PadOperators=*/true}));                                 \
301     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
302                 FormatStyle::AlignConsecutiveStyle(                            \
303                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
304                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
305                      /*PadOperators=*/true}));                                 \
306     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
307                 FormatStyle::AlignConsecutiveStyle(                            \
308                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
309                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
310                      /*PadOperators=*/true}));                                 \
311     /* For backwards compability, false / true should still parse */           \
312     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
313                 FormatStyle::AlignConsecutiveStyle(                            \
314                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
315                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
316                      /*PadOperators=*/true}));                                 \
317     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
318                 FormatStyle::AlignConsecutiveStyle(                            \
319                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
320                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
321                      /*PadOperators=*/true}));                                 \
322                                                                                \
323     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
324     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
325     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
326     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
327     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
328   } while (false)
329 
330   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
331   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
332   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
333   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
334 
335 #undef CHECK_ALIGN_CONSECUTIVE
336 
337   Style.PointerAlignment = FormatStyle::PAS_Middle;
338   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
339               FormatStyle::PAS_Left);
340   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
341               FormatStyle::PAS_Right);
342   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
343               FormatStyle::PAS_Middle);
344   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
345   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
346               FormatStyle::RAS_Pointer);
347   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
348               FormatStyle::RAS_Left);
349   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
350               FormatStyle::RAS_Right);
351   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
352               FormatStyle::RAS_Middle);
353   // For backward compatibility:
354   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
355               FormatStyle::PAS_Left);
356   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
357               FormatStyle::PAS_Right);
358   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
359               FormatStyle::PAS_Middle);
360 
361   Style.Standard = FormatStyle::LS_Auto;
362   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
363   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
364   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
365   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
366   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
367   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
368   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
369   // Legacy aliases:
370   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
371   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
372   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
373   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
374 
375   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
376   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
377               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
378   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
379               FormatStyle::BOS_None);
380   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
381               FormatStyle::BOS_All);
382   // For backward compatibility:
383   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
384               FormatStyle::BOS_None);
385   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
386               FormatStyle::BOS_All);
387 
388   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
389   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
390               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
391   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
392               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
393   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
394               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
395   // For backward compatibility:
396   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
397               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
398 
399   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
400   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
401               FormatStyle::BILS_AfterComma);
402   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
403               FormatStyle::BILS_BeforeComma);
404   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
405               FormatStyle::BILS_AfterColon);
406   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
407               FormatStyle::BILS_BeforeColon);
408   // For backward compatibility:
409   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
410               FormatStyle::BILS_BeforeComma);
411 
412   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
413   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
414               FormatStyle::PCIS_Never);
415   CHECK_PARSE("PackConstructorInitializers: BinPack",
416               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
417   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
418               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
419   CHECK_PARSE("PackConstructorInitializers: NextLine",
420               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
421   CHECK_PARSE("PackConstructorInitializers: NextLineOnly",
422               PackConstructorInitializers, FormatStyle::PCIS_NextLineOnly);
423   // For backward compatibility:
424   CHECK_PARSE("BasedOnStyle: Google\n"
425               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
426               "AllowAllConstructorInitializersOnNextLine: false",
427               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
428   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
429   CHECK_PARSE("BasedOnStyle: Google\n"
430               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
431               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
432   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
433               "AllowAllConstructorInitializersOnNextLine: true",
434               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
435   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
436   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
437               "AllowAllConstructorInitializersOnNextLine: false",
438               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
439 
440   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
441   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
442               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
443   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
444               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
445   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
446               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
447   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
448               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
449 
450   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
451   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
452               FormatStyle::BAS_Align);
453   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
454               FormatStyle::BAS_DontAlign);
455   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
456               FormatStyle::BAS_AlwaysBreak);
457   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
458               FormatStyle::BAS_BlockIndent);
459   // For backward compatibility:
460   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
461               FormatStyle::BAS_DontAlign);
462   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
463               FormatStyle::BAS_Align);
464 
465   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
466   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
467               FormatStyle::ENAS_DontAlign);
468   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
469               FormatStyle::ENAS_Left);
470   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
471               FormatStyle::ENAS_Right);
472   // For backward compatibility:
473   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
474               FormatStyle::ENAS_Left);
475   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
476               FormatStyle::ENAS_Right);
477 
478   Style.AlignOperands = FormatStyle::OAS_Align;
479   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
480               FormatStyle::OAS_DontAlign);
481   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
482   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
483               FormatStyle::OAS_AlignAfterOperator);
484   // For backward compatibility:
485   CHECK_PARSE("AlignOperands: false", AlignOperands,
486               FormatStyle::OAS_DontAlign);
487   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
488 
489   CHECK_PARSE("AlignTrailingComments: Leave", AlignTrailingComments,
490               FormatStyle::TrailingCommentsAlignmentStyle(
491                   {FormatStyle::TCAS_Leave, 0}));
492   CHECK_PARSE("AlignTrailingComments: Always", AlignTrailingComments,
493               FormatStyle::TrailingCommentsAlignmentStyle(
494                   {FormatStyle::TCAS_Always, 0}));
495   CHECK_PARSE("AlignTrailingComments: Never", AlignTrailingComments,
496               FormatStyle::TrailingCommentsAlignmentStyle(
497                   {FormatStyle::TCAS_Never, 0}));
498   // For backwards compatibility
499   CHECK_PARSE("AlignTrailingComments: true", AlignTrailingComments,
500               FormatStyle::TrailingCommentsAlignmentStyle(
501                   {FormatStyle::TCAS_Always, 0}));
502   CHECK_PARSE("AlignTrailingComments: false", AlignTrailingComments,
503               FormatStyle::TrailingCommentsAlignmentStyle(
504                   {FormatStyle::TCAS_Never, 0}));
505   CHECK_PARSE_NESTED_VALUE("Kind: Always", AlignTrailingComments, Kind,
506                            FormatStyle::TCAS_Always);
507   CHECK_PARSE_NESTED_VALUE("Kind: Never", AlignTrailingComments, Kind,
508                            FormatStyle::TCAS_Never);
509   CHECK_PARSE_NESTED_VALUE("Kind: Leave", AlignTrailingComments, Kind,
510                            FormatStyle::TCAS_Leave);
511   CHECK_PARSE_NESTED_VALUE("OverEmptyLines: 1234", AlignTrailingComments,
512                            OverEmptyLines, 1234u);
513 
514   Style.UseTab = FormatStyle::UT_ForIndentation;
515   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
516   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
517   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
518   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
519               FormatStyle::UT_ForContinuationAndIndentation);
520   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
521               FormatStyle::UT_AlignWithSpaces);
522   // For backward compatibility:
523   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
524   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
525 
526   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
527   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
528               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
529   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
530               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
531   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
532               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
533   // For backward compatibility:
534   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
535               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
536   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
537               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
538 
539   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
540   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
541               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
542   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
543               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
544   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
545               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
546   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
547               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
548   // For backward compatibility:
549   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
550               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
551   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
552               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
553 
554   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
555   CHECK_PARSE("AllowShortLambdasOnASingleLine: None",
556               AllowShortLambdasOnASingleLine, FormatStyle::SLS_None);
557   CHECK_PARSE("AllowShortLambdasOnASingleLine: Empty",
558               AllowShortLambdasOnASingleLine, FormatStyle::SLS_Empty);
559   CHECK_PARSE("AllowShortLambdasOnASingleLine: Inline",
560               AllowShortLambdasOnASingleLine, FormatStyle::SLS_Inline);
561   CHECK_PARSE("AllowShortLambdasOnASingleLine: All",
562               AllowShortLambdasOnASingleLine, FormatStyle::SLS_All);
563   // For backward compatibility:
564   CHECK_PARSE("AllowShortLambdasOnASingleLine: false",
565               AllowShortLambdasOnASingleLine, FormatStyle::SLS_None);
566   CHECK_PARSE("AllowShortLambdasOnASingleLine: true",
567               AllowShortLambdasOnASingleLine, FormatStyle::SLS_All);
568 
569   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
570   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
571               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
572   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
573               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
574   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
575               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
576   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
577               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
578 
579   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
580   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
581               FormatStyle::SBPO_Never);
582   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
583               FormatStyle::SBPO_Always);
584   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
585               FormatStyle::SBPO_ControlStatements);
586   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
587               SpaceBeforeParens,
588               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
589   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
590               FormatStyle::SBPO_NonEmptyParentheses);
591   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
592               FormatStyle::SBPO_Custom);
593   // For backward compatibility:
594   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
595               FormatStyle::SBPO_Never);
596   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
597               FormatStyle::SBPO_ControlStatements);
598   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
599               SpaceBeforeParens,
600               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
601 
602   Style.SpaceBeforeParens = FormatStyle::SBPO_Custom;
603   Style.SpaceBeforeParensOptions.AfterPlacementOperator =
604       FormatStyle::SpaceBeforeParensCustom::APO_Always;
605   CHECK_PARSE("SpaceBeforeParensOptions:\n"
606               "  AfterPlacementOperator: Never",
607               SpaceBeforeParensOptions.AfterPlacementOperator,
608               FormatStyle::SpaceBeforeParensCustom::APO_Never);
609 
610   CHECK_PARSE("SpaceBeforeParensOptions:\n"
611               "  AfterPlacementOperator: Always",
612               SpaceBeforeParensOptions.AfterPlacementOperator,
613               FormatStyle::SpaceBeforeParensCustom::APO_Always);
614 
615   CHECK_PARSE("SpaceBeforeParensOptions:\n"
616               "  AfterPlacementOperator: Leave",
617               SpaceBeforeParensOptions.AfterPlacementOperator,
618               FormatStyle::SpaceBeforeParensCustom::APO_Leave);
619 
620   // For backward compatibility:
621   Style.SpacesInParens = FormatStyle::SIPO_Never;
622   Style.SpacesInParensOptions = {};
623   CHECK_PARSE("SpacesInParentheses: true", SpacesInParens,
624               FormatStyle::SIPO_Custom);
625   Style.SpacesInParens = FormatStyle::SIPO_Never;
626   Style.SpacesInParensOptions = {};
627   CHECK_PARSE("SpacesInParentheses: true", SpacesInParensOptions,
628               FormatStyle::SpacesInParensCustom(true, false, false, true));
629   Style.SpacesInParens = FormatStyle::SIPO_Never;
630   Style.SpacesInParensOptions = {};
631   CHECK_PARSE("SpacesInConditionalStatement: true", SpacesInParensOptions,
632               FormatStyle::SpacesInParensCustom(true, false, false, false));
633   Style.SpacesInParens = FormatStyle::SIPO_Never;
634   Style.SpacesInParensOptions = {};
635   CHECK_PARSE("SpacesInCStyleCastParentheses: true", SpacesInParensOptions,
636               FormatStyle::SpacesInParensCustom(false, true, false, false));
637   Style.SpacesInParens = FormatStyle::SIPO_Never;
638   Style.SpacesInParensOptions = {};
639   CHECK_PARSE("SpaceInEmptyParentheses: true", SpacesInParensOptions,
640               FormatStyle::SpacesInParensCustom(false, false, true, false));
641   Style.SpacesInParens = FormatStyle::SIPO_Never;
642   Style.SpacesInParensOptions = {};
643 
644   Style.ColumnLimit = 123;
645   FormatStyle BaseStyle = getLLVMStyle();
646   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
647   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
648 
649   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
650   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
651               FormatStyle::BS_Attach);
652   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
653               FormatStyle::BS_Linux);
654   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
655               FormatStyle::BS_Mozilla);
656   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
657               FormatStyle::BS_Stroustrup);
658   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
659               FormatStyle::BS_Allman);
660   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
661               FormatStyle::BS_Whitesmiths);
662   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
663   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
664               FormatStyle::BS_WebKit);
665   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
666               FormatStyle::BS_Custom);
667 
668   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
669   CHECK_PARSE("BraceWrapping:\n"
670               "  AfterControlStatement: MultiLine",
671               BraceWrapping.AfterControlStatement,
672               FormatStyle::BWACS_MultiLine);
673   CHECK_PARSE("BraceWrapping:\n"
674               "  AfterControlStatement: Always",
675               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
676   CHECK_PARSE("BraceWrapping:\n"
677               "  AfterControlStatement: Never",
678               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
679   // For backward compatibility:
680   CHECK_PARSE("BraceWrapping:\n"
681               "  AfterControlStatement: true",
682               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
683   CHECK_PARSE("BraceWrapping:\n"
684               "  AfterControlStatement: false",
685               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
686 
687   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
688   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
689               FormatStyle::RTBS_None);
690   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
691               FormatStyle::RTBS_All);
692   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
693               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
694   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
695               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
696   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
697               AlwaysBreakAfterReturnType,
698               FormatStyle::RTBS_TopLevelDefinitions);
699 
700   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
701   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
702               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
703   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
704               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
705   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
706               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
707   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
708               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
709   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
710               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
711 
712   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
713   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
714               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
715   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
716               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
717   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
718               AlwaysBreakAfterDefinitionReturnType,
719               FormatStyle::DRTBS_TopLevel);
720 
721   Style.NamespaceIndentation = FormatStyle::NI_All;
722   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
723               FormatStyle::NI_None);
724   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
725               FormatStyle::NI_Inner);
726   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
727               FormatStyle::NI_All);
728 
729   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
730   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
731               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
732   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
733               AllowShortIfStatementsOnASingleLine,
734               FormatStyle::SIS_WithoutElse);
735   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
736               AllowShortIfStatementsOnASingleLine,
737               FormatStyle::SIS_OnlyFirstIf);
738   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
739               AllowShortIfStatementsOnASingleLine,
740               FormatStyle::SIS_AllIfsAndElse);
741   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
742               AllowShortIfStatementsOnASingleLine,
743               FormatStyle::SIS_OnlyFirstIf);
744   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
745               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
746   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
747               AllowShortIfStatementsOnASingleLine,
748               FormatStyle::SIS_WithoutElse);
749 
750   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
751   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
752               FormatStyle::IEBS_AfterExternBlock);
753   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
754               FormatStyle::IEBS_Indent);
755   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
756               FormatStyle::IEBS_NoIndent);
757   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
758               FormatStyle::IEBS_Indent);
759   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
760               FormatStyle::IEBS_NoIndent);
761 
762   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
763   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
764               FormatStyle::BFCS_Both);
765   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
766               FormatStyle::BFCS_None);
767   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
768               FormatStyle::BFCS_Before);
769   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
770               FormatStyle::BFCS_After);
771 
772   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
773   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
774               FormatStyle::SJSIO_After);
775   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
776               FormatStyle::SJSIO_Before);
777 
778   Style.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
779   CHECK_PARSE("SortUsingDeclarations: Never", SortUsingDeclarations,
780               FormatStyle::SUD_Never);
781   CHECK_PARSE("SortUsingDeclarations: Lexicographic", SortUsingDeclarations,
782               FormatStyle::SUD_Lexicographic);
783   CHECK_PARSE("SortUsingDeclarations: LexicographicNumeric",
784               SortUsingDeclarations, FormatStyle::SUD_LexicographicNumeric);
785   // For backward compatibility:
786   CHECK_PARSE("SortUsingDeclarations: false", SortUsingDeclarations,
787               FormatStyle::SUD_Never);
788   CHECK_PARSE("SortUsingDeclarations: true", SortUsingDeclarations,
789               FormatStyle::SUD_LexicographicNumeric);
790 
791   // FIXME: This is required because parsing a configuration simply overwrites
792   // the first N elements of the list instead of resetting it.
793   Style.ForEachMacros.clear();
794   std::vector<std::string> BoostForeach;
795   BoostForeach.push_back("BOOST_FOREACH");
796   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
797   std::vector<std::string> BoostAndQForeach;
798   BoostAndQForeach.push_back("BOOST_FOREACH");
799   BoostAndQForeach.push_back("Q_FOREACH");
800   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
801               BoostAndQForeach);
802 
803   Style.IfMacros.clear();
804   std::vector<std::string> CustomIfs;
805   CustomIfs.push_back("MYIF");
806   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
807 
808   Style.AttributeMacros.clear();
809   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
810               std::vector<std::string>{"__capability"});
811   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
812               std::vector<std::string>({"attr1", "attr2"}));
813 
814   Style.StatementAttributeLikeMacros.clear();
815   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
816               StatementAttributeLikeMacros,
817               std::vector<std::string>({"emit", "Q_EMIT"}));
818 
819   Style.StatementMacros.clear();
820   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
821               std::vector<std::string>{"QUNUSED"});
822   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
823               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
824 
825   Style.NamespaceMacros.clear();
826   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
827               std::vector<std::string>{"TESTSUITE"});
828   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
829               std::vector<std::string>({"TESTSUITE", "SUITE"}));
830 
831   Style.WhitespaceSensitiveMacros.clear();
832   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
833               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
834   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
835               WhitespaceSensitiveMacros,
836               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
837   Style.WhitespaceSensitiveMacros.clear();
838   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
839               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
840   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
841               WhitespaceSensitiveMacros,
842               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
843 
844   Style.IncludeStyle.IncludeCategories.clear();
845   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
846       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
847   CHECK_PARSE("IncludeCategories:\n"
848               "  - Regex: abc/.*\n"
849               "    Priority: 2\n"
850               "  - Regex: .*\n"
851               "    Priority: 1\n"
852               "    CaseSensitive: true",
853               IncludeStyle.IncludeCategories, ExpectedCategories);
854   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
855               "abc$");
856   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
857               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
858 
859   Style.SortIncludes = FormatStyle::SI_Never;
860   CHECK_PARSE("SortIncludes: true", SortIncludes,
861               FormatStyle::SI_CaseSensitive);
862   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
863   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
864               FormatStyle::SI_CaseInsensitive);
865   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
866               FormatStyle::SI_CaseSensitive);
867   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
868 
869   Style.RawStringFormats.clear();
870   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
871       {
872           FormatStyle::LK_TextProto,
873           {"pb", "proto"},
874           {"PARSE_TEXT_PROTO"},
875           /*CanonicalDelimiter=*/"",
876           "llvm",
877       },
878       {
879           FormatStyle::LK_Cpp,
880           {"cc", "cpp"},
881           {"C_CODEBLOCK", "CPPEVAL"},
882           /*CanonicalDelimiter=*/"cc",
883           /*BasedOnStyle=*/"",
884       },
885   };
886 
887   CHECK_PARSE("RawStringFormats:\n"
888               "  - Language: TextProto\n"
889               "    Delimiters:\n"
890               "      - 'pb'\n"
891               "      - 'proto'\n"
892               "    EnclosingFunctions:\n"
893               "      - 'PARSE_TEXT_PROTO'\n"
894               "    BasedOnStyle: llvm\n"
895               "  - Language: Cpp\n"
896               "    Delimiters:\n"
897               "      - 'cc'\n"
898               "      - 'cpp'\n"
899               "    EnclosingFunctions:\n"
900               "      - 'C_CODEBLOCK'\n"
901               "      - 'CPPEVAL'\n"
902               "    CanonicalDelimiter: 'cc'",
903               RawStringFormats, ExpectedRawStringFormats);
904 
905   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
906               "  Minimum: 0\n"
907               "  Maximum: 0",
908               SpacesInLineCommentPrefix.Minimum, 0u);
909   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
910   Style.SpacesInLineCommentPrefix.Minimum = 1;
911   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
912               "  Minimum: 2",
913               SpacesInLineCommentPrefix.Minimum, 0u);
914   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
915               "  Maximum: -1",
916               SpacesInLineCommentPrefix.Maximum, -1u);
917   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
918               "  Minimum: 2",
919               SpacesInLineCommentPrefix.Minimum, 2u);
920   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
921               "  Maximum: 1",
922               SpacesInLineCommentPrefix.Maximum, 1u);
923   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
924 
925   Style.SpacesInAngles = FormatStyle::SIAS_Always;
926   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
927   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
928               FormatStyle::SIAS_Always);
929   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
930   // For backward compatibility:
931   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
932   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
933 
934   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
935               FormatStyle::RCPS_WithPreceding);
936   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
937               FormatStyle::RCPS_WithFollowing);
938   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
939               FormatStyle::RCPS_SingleLine);
940   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
941               FormatStyle::RCPS_OwnLine);
942 
943   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
944               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
945   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
946               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
947   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
948               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
949   // For backward compatibility:
950   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
951               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
952   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
953               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
954 
955   CHECK_PARSE("BreakAfterAttributes: Always", BreakAfterAttributes,
956               FormatStyle::ABS_Always);
957   CHECK_PARSE("BreakAfterAttributes: Leave", BreakAfterAttributes,
958               FormatStyle::ABS_Leave);
959   CHECK_PARSE("BreakAfterAttributes: Never", BreakAfterAttributes,
960               FormatStyle::ABS_Never);
961 
962   const auto DefaultLineEnding = FormatStyle::LE_DeriveLF;
963   CHECK_PARSE("LineEnding: LF", LineEnding, FormatStyle::LE_LF);
964   CHECK_PARSE("LineEnding: CRLF", LineEnding, FormatStyle::LE_CRLF);
965   CHECK_PARSE("LineEnding: DeriveCRLF", LineEnding, FormatStyle::LE_DeriveCRLF);
966   CHECK_PARSE("LineEnding: DeriveLF", LineEnding, DefaultLineEnding);
967   // For backward compatibility:
968   CHECK_PARSE("DeriveLineEnding: false", LineEnding, FormatStyle::LE_LF);
969   Style.LineEnding = DefaultLineEnding;
970   CHECK_PARSE("DeriveLineEnding: false\n"
971               "UseCRLF: true",
972               LineEnding, FormatStyle::LE_CRLF);
973   Style.LineEnding = DefaultLineEnding;
974   CHECK_PARSE("UseCRLF: true", LineEnding, FormatStyle::LE_DeriveCRLF);
975 
976   CHECK_PARSE("RemoveParentheses: MultipleParentheses", RemoveParentheses,
977               FormatStyle::RPS_MultipleParentheses);
978   CHECK_PARSE("RemoveParentheses: ReturnStatement", RemoveParentheses,
979               FormatStyle::RPS_ReturnStatement);
980   CHECK_PARSE("RemoveParentheses: Leave", RemoveParentheses,
981               FormatStyle::RPS_Leave);
982 
983   CHECK_PARSE("AllowBreakBeforeNoexceptSpecifier: Always",
984               AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Always);
985   CHECK_PARSE("AllowBreakBeforeNoexceptSpecifier: OnlyWithParen",
986               AllowBreakBeforeNoexceptSpecifier,
987               FormatStyle::BBNSS_OnlyWithParen);
988   CHECK_PARSE("AllowBreakBeforeNoexceptSpecifier: Never",
989               AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Never);
990 }
991 
992 TEST(ConfigParseTest, ParsesConfigurationWithLanguages) {
993   FormatStyle Style = {};
994   Style.Language = FormatStyle::LK_Cpp;
995   CHECK_PARSE("Language: Cpp\n"
996               "IndentWidth: 12",
997               IndentWidth, 12u);
998   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
999                                "IndentWidth: 34",
1000                                &Style),
1001             ParseError::Unsuitable);
1002   FormatStyle BinPackedTCS = {};
1003   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
1004   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
1005                                "InsertTrailingCommas: Wrapped",
1006                                &BinPackedTCS),
1007             ParseError::BinPackTrailingCommaConflict);
1008   EXPECT_EQ(12u, Style.IndentWidth);
1009   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
1010   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
1011 
1012   Style.Language = FormatStyle::LK_JavaScript;
1013   CHECK_PARSE("Language: JavaScript\n"
1014               "IndentWidth: 12",
1015               IndentWidth, 12u);
1016   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
1017   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
1018                                "IndentWidth: 34",
1019                                &Style),
1020             ParseError::Unsuitable);
1021   EXPECT_EQ(23u, Style.IndentWidth);
1022   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
1023   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
1024 
1025   CHECK_PARSE("BasedOnStyle: LLVM\n"
1026               "IndentWidth: 67",
1027               IndentWidth, 67u);
1028 
1029   CHECK_PARSE("---\n"
1030               "Language: JavaScript\n"
1031               "IndentWidth: 12\n"
1032               "---\n"
1033               "Language: Cpp\n"
1034               "IndentWidth: 34\n"
1035               "...\n",
1036               IndentWidth, 12u);
1037 
1038   Style.Language = FormatStyle::LK_Cpp;
1039   CHECK_PARSE("---\n"
1040               "Language: JavaScript\n"
1041               "IndentWidth: 12\n"
1042               "---\n"
1043               "Language: Cpp\n"
1044               "IndentWidth: 34\n"
1045               "...\n",
1046               IndentWidth, 34u);
1047   CHECK_PARSE("---\n"
1048               "IndentWidth: 78\n"
1049               "---\n"
1050               "Language: JavaScript\n"
1051               "IndentWidth: 56\n"
1052               "...\n",
1053               IndentWidth, 78u);
1054 
1055   Style.ColumnLimit = 123;
1056   Style.IndentWidth = 234;
1057   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
1058   Style.TabWidth = 345;
1059   EXPECT_FALSE(parseConfiguration("---\n"
1060                                   "IndentWidth: 456\n"
1061                                   "BreakBeforeBraces: Allman\n"
1062                                   "---\n"
1063                                   "Language: JavaScript\n"
1064                                   "IndentWidth: 111\n"
1065                                   "TabWidth: 111\n"
1066                                   "---\n"
1067                                   "Language: Cpp\n"
1068                                   "BreakBeforeBraces: Stroustrup\n"
1069                                   "TabWidth: 789\n"
1070                                   "...\n",
1071                                   &Style));
1072   EXPECT_EQ(123u, Style.ColumnLimit);
1073   EXPECT_EQ(456u, Style.IndentWidth);
1074   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
1075   EXPECT_EQ(789u, Style.TabWidth);
1076 
1077   EXPECT_EQ(parseConfiguration("---\n"
1078                                "Language: JavaScript\n"
1079                                "IndentWidth: 56\n"
1080                                "---\n"
1081                                "IndentWidth: 78\n"
1082                                "...\n",
1083                                &Style),
1084             ParseError::Error);
1085   EXPECT_EQ(parseConfiguration("---\n"
1086                                "Language: JavaScript\n"
1087                                "IndentWidth: 56\n"
1088                                "---\n"
1089                                "Language: JavaScript\n"
1090                                "IndentWidth: 78\n"
1091                                "...\n",
1092                                &Style),
1093             ParseError::Error);
1094 
1095   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
1096 
1097   Style.Language = FormatStyle::LK_Verilog;
1098   CHECK_PARSE("---\n"
1099               "Language: Verilog\n"
1100               "IndentWidth: 12\n"
1101               "---\n"
1102               "Language: Cpp\n"
1103               "IndentWidth: 34\n"
1104               "...\n",
1105               IndentWidth, 12u);
1106   CHECK_PARSE("---\n"
1107               "IndentWidth: 78\n"
1108               "---\n"
1109               "Language: Verilog\n"
1110               "IndentWidth: 56\n"
1111               "...\n",
1112               IndentWidth, 56u);
1113 }
1114 
1115 TEST(ConfigParseTest, UsesLanguageForBasedOnStyle) {
1116   FormatStyle Style = {};
1117   Style.Language = FormatStyle::LK_JavaScript;
1118   Style.BreakBeforeTernaryOperators = true;
1119   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
1120   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
1121 
1122   Style.BreakBeforeTernaryOperators = true;
1123   EXPECT_EQ(0, parseConfiguration("---\n"
1124                                   "BasedOnStyle: Google\n"
1125                                   "---\n"
1126                                   "Language: JavaScript\n"
1127                                   "IndentWidth: 76\n"
1128                                   "...\n",
1129                                   &Style)
1130                    .value());
1131   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
1132   EXPECT_EQ(76u, Style.IndentWidth);
1133   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
1134 }
1135 
1136 TEST(ConfigParseTest, ConfigurationRoundTripTest) {
1137   FormatStyle Style = getLLVMStyle();
1138   std::string YAML = configurationAsText(Style);
1139   FormatStyle ParsedStyle = {};
1140   ParsedStyle.Language = FormatStyle::LK_Cpp;
1141   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
1142   EXPECT_EQ(Style, ParsedStyle);
1143 }
1144 
1145 TEST(ConfigParseTest, GetStyleWithEmptyFileName) {
1146   llvm::vfs::InMemoryFileSystem FS;
1147   auto Style1 = getStyle("file", "", "Google", "", &FS);
1148   ASSERT_TRUE((bool)Style1);
1149   ASSERT_EQ(*Style1, getGoogleStyle());
1150 }
1151 
1152 TEST(ConfigParseTest, GetStyleOfFile) {
1153   llvm::vfs::InMemoryFileSystem FS;
1154   // Test 1: format file in the same directory.
1155   ASSERT_TRUE(
1156       FS.addFile("/a/.clang-format", 0,
1157                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
1158   ASSERT_TRUE(
1159       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
1160   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
1161   ASSERT_TRUE((bool)Style1);
1162   ASSERT_EQ(*Style1, getLLVMStyle());
1163 
1164   // Test 2.1: fallback to default.
1165   ASSERT_TRUE(
1166       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
1167   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
1168   ASSERT_TRUE((bool)Style2);
1169   ASSERT_EQ(*Style2, getMozillaStyle());
1170 
1171   // Test 2.2: no format on 'none' fallback style.
1172   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
1173   ASSERT_TRUE((bool)Style2);
1174   ASSERT_EQ(*Style2, getNoStyle());
1175 
1176   // Test 2.3: format if config is found with no based style while fallback is
1177   // 'none'.
1178   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
1179                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
1180   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
1181   ASSERT_TRUE((bool)Style2);
1182   ASSERT_EQ(*Style2, getLLVMStyle());
1183 
1184   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
1185   Style2 = getStyle("{}", "a.h", "none", "", &FS);
1186   ASSERT_TRUE((bool)Style2);
1187   ASSERT_EQ(*Style2, getLLVMStyle());
1188 
1189   // Test 3: format file in parent directory.
1190   ASSERT_TRUE(
1191       FS.addFile("/c/.clang-format", 0,
1192                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
1193   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
1194                          llvm::MemoryBuffer::getMemBuffer("int i;")));
1195   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
1196   ASSERT_TRUE((bool)Style3);
1197   ASSERT_EQ(*Style3, getGoogleStyle());
1198 
1199   // Test 4: error on invalid fallback style
1200   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
1201   ASSERT_FALSE((bool)Style4);
1202   llvm::consumeError(Style4.takeError());
1203 
1204   // Test 5: error on invalid yaml on command line
1205   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
1206   ASSERT_FALSE((bool)Style5);
1207   llvm::consumeError(Style5.takeError());
1208 
1209   // Test 6: error on invalid style
1210   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
1211   ASSERT_FALSE((bool)Style6);
1212   llvm::consumeError(Style6.takeError());
1213 
1214   // Test 7: found config file, error on parsing it
1215   ASSERT_TRUE(
1216       FS.addFile("/d/.clang-format", 0,
1217                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
1218                                                   "InvalidKey: InvalidValue")));
1219   ASSERT_TRUE(
1220       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
1221   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
1222   ASSERT_FALSE((bool)Style7a);
1223   llvm::consumeError(Style7a.takeError());
1224 
1225   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
1226   ASSERT_TRUE((bool)Style7b);
1227 
1228   // Test 8: inferred per-language defaults apply.
1229   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
1230   ASSERT_TRUE((bool)StyleTd);
1231   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
1232 
1233   // Test 9.1.1: overwriting a file style, when no parent file exists with no
1234   // fallback style.
1235   ASSERT_TRUE(FS.addFile(
1236       "/e/sub/.clang-format", 0,
1237       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
1238                                        "ColumnLimit: 20")));
1239   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
1240                          llvm::MemoryBuffer::getMemBuffer("int i;")));
1241   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
1242   ASSERT_TRUE(static_cast<bool>(Style9));
1243   ASSERT_EQ(*Style9, [] {
1244     auto Style = getNoStyle();
1245     Style.ColumnLimit = 20;
1246     return Style;
1247   }());
1248 
1249   // Test 9.1.2: propagate more than one level with no parent file.
1250   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
1251                          llvm::MemoryBuffer::getMemBuffer("int i;")));
1252   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
1253                          llvm::MemoryBuffer::getMemBuffer(
1254                              "BasedOnStyle: InheritParentConfig\n"
1255                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
1256   std::vector<std::string> NonDefaultWhiteSpaceMacros =
1257       Style9->WhitespaceSensitiveMacros;
1258   NonDefaultWhiteSpaceMacros[0] = "FOO";
1259   NonDefaultWhiteSpaceMacros[1] = "BAR";
1260 
1261   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
1262   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
1263   ASSERT_TRUE(static_cast<bool>(Style9));
1264   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
1265     auto Style = getNoStyle();
1266     Style.ColumnLimit = 20;
1267     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
1268     return Style;
1269   }());
1270 
1271   // Test 9.2: with LLVM fallback style
1272   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
1273   ASSERT_TRUE(static_cast<bool>(Style9));
1274   ASSERT_EQ(*Style9, [] {
1275     auto Style = getLLVMStyle();
1276     Style.ColumnLimit = 20;
1277     return Style;
1278   }());
1279 
1280   // Test 9.3: with a parent file
1281   ASSERT_TRUE(
1282       FS.addFile("/e/.clang-format", 0,
1283                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
1284                                                   "UseTab: Always")));
1285   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
1286   ASSERT_TRUE(static_cast<bool>(Style9));
1287   ASSERT_EQ(*Style9, [] {
1288     auto Style = getGoogleStyle();
1289     Style.ColumnLimit = 20;
1290     Style.UseTab = FormatStyle::UT_Always;
1291     return Style;
1292   }());
1293 
1294   // Test 9.4: propagate more than one level with a parent file.
1295   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
1296     auto Style = getGoogleStyle();
1297     Style.ColumnLimit = 20;
1298     Style.UseTab = FormatStyle::UT_Always;
1299     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
1300     return Style;
1301   }();
1302 
1303   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
1304   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
1305   ASSERT_TRUE(static_cast<bool>(Style9));
1306   ASSERT_EQ(*Style9, SubSubStyle);
1307 
1308   // Test 9.5: use InheritParentConfig as style name
1309   Style9 =
1310       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
1311   ASSERT_TRUE(static_cast<bool>(Style9));
1312   ASSERT_EQ(*Style9, SubSubStyle);
1313 
1314   // Test 9.6: use command line style with inheritance
1315   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}",
1316                     "/e/sub/sub/code.cpp", "none", "", &FS);
1317   ASSERT_TRUE(static_cast<bool>(Style9));
1318   ASSERT_EQ(*Style9, SubSubStyle);
1319 
1320   // Test 9.7: use command line style with inheritance and own config
1321   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
1322                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
1323                     "/e/sub/code.cpp", "none", "", &FS);
1324   ASSERT_TRUE(static_cast<bool>(Style9));
1325   ASSERT_EQ(*Style9, SubSubStyle);
1326 
1327   // Test 9.8: use inheritance from a file without BasedOnStyle
1328   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
1329                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
1330   ASSERT_TRUE(
1331       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
1332                  llvm::MemoryBuffer::getMemBuffer(
1333                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
1334   // Make sure we do not use the fallback style
1335   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
1336   ASSERT_TRUE(static_cast<bool>(Style9));
1337   ASSERT_EQ(*Style9, [] {
1338     auto Style = getLLVMStyle();
1339     Style.ColumnLimit = 123;
1340     return Style;
1341   }());
1342 
1343   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
1344   ASSERT_TRUE(static_cast<bool>(Style9));
1345   ASSERT_EQ(*Style9, [] {
1346     auto Style = getLLVMStyle();
1347     Style.ColumnLimit = 123;
1348     Style.IndentWidth = 7;
1349     return Style;
1350   }());
1351 
1352   // Test 9.9: use inheritance from a specific config file.
1353   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
1354                     "none", "", &FS);
1355   ASSERT_TRUE(static_cast<bool>(Style9));
1356   ASSERT_EQ(*Style9, SubSubStyle);
1357 }
1358 
1359 TEST(ConfigParseTest, GetStyleOfSpecificFile) {
1360   llvm::vfs::InMemoryFileSystem FS;
1361   // Specify absolute path to a format file in a parent directory.
1362   ASSERT_TRUE(
1363       FS.addFile("/e/.clang-format", 0,
1364                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
1365   ASSERT_TRUE(
1366       FS.addFile("/e/explicit.clang-format", 0,
1367                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
1368   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
1369                          llvm::MemoryBuffer::getMemBuffer("int i;")));
1370   auto Style = getStyle("file:/e/explicit.clang-format",
1371                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
1372   ASSERT_TRUE(static_cast<bool>(Style));
1373   ASSERT_EQ(*Style, getGoogleStyle());
1374 
1375   // Specify relative path to a format file.
1376   ASSERT_TRUE(
1377       FS.addFile("../../e/explicit.clang-format", 0,
1378                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
1379   Style = getStyle("file:../../e/explicit.clang-format",
1380                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
1381   ASSERT_TRUE(static_cast<bool>(Style));
1382   ASSERT_EQ(*Style, getGoogleStyle());
1383 
1384   // Specify path to a format file that does not exist.
1385   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
1386                    "LLVM", "", &FS);
1387   ASSERT_FALSE(static_cast<bool>(Style));
1388   llvm::consumeError(Style.takeError());
1389 
1390   // Specify path to a file on the filesystem.
1391   SmallString<128> FormatFilePath;
1392   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
1393       "FormatFileTest", "tpl", FormatFilePath);
1394   EXPECT_FALSE((bool)ECF);
1395   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
1396   EXPECT_FALSE((bool)ECF);
1397   FormatFileTest << "BasedOnStyle: Google\n";
1398   FormatFileTest.close();
1399 
1400   SmallString<128> TestFilePath;
1401   std::error_code ECT =
1402       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
1403   EXPECT_FALSE((bool)ECT);
1404   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
1405   CodeFileTest << "int i;\n";
1406   CodeFileTest.close();
1407 
1408   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
1409   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
1410 
1411   llvm::sys::fs::remove(FormatFilePath.c_str());
1412   llvm::sys::fs::remove(TestFilePath.c_str());
1413   ASSERT_TRUE(static_cast<bool>(Style));
1414   ASSERT_EQ(*Style, getGoogleStyle());
1415 }
1416 
1417 } // namespace
1418 } // namespace format
1419 } // namespace clang
1420