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