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