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