1 //===--- Format.cpp - Format C++ code -------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements functions declared in Format.h. This will be
12 /// split into separate files as we go.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "ContinuationIndenter.h"
17 #include "TokenAnnotator.h"
18 #include "UnwrappedLineParser.h"
19 #include "WhitespaceManager.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/DiagnosticOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Format/Format.h"
24 #include "clang/Lex/Lexer.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/YAMLTraits.h"
30 #include <queue>
31 #include <string>
32 
33 #define DEBUG_TYPE "format-formatter"
34 
35 using clang::format::FormatStyle;
36 
37 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38 
39 namespace llvm {
40 namespace yaml {
41 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
44     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
45     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
46   }
47 };
48 
49 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
50   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
51     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
52     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
53     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
54     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
55     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
56   }
57 };
58 
59 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
60   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
61     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
62     IO.enumCase(Value, "false", FormatStyle::UT_Never);
63     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
64     IO.enumCase(Value, "true", FormatStyle::UT_Always);
65     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
66   }
67 };
68 
69 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
70   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
71     IO.enumCase(Value, "None", FormatStyle::SFS_None);
72     IO.enumCase(Value, "false", FormatStyle::SFS_None);
73     IO.enumCase(Value, "All", FormatStyle::SFS_All);
74     IO.enumCase(Value, "true", FormatStyle::SFS_All);
75     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
76   }
77 };
78 
79 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
80   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
81     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
82     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
83     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
84     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
85     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
86   }
87 };
88 
89 template <>
90 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
91   static void enumeration(IO &IO,
92                           FormatStyle::NamespaceIndentationKind &Value) {
93     IO.enumCase(Value, "None", FormatStyle::NI_None);
94     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
95     IO.enumCase(Value, "All", FormatStyle::NI_All);
96   }
97 };
98 
99 template <>
100 struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
101   static void enumeration(IO &IO,
102                           FormatStyle::PointerAlignmentStyle &Value) {
103     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
104     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
105     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
106 
107     // For backward compatibility.
108     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
109     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
110   }
111 };
112 
113 template <>
114 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
115   static void enumeration(IO &IO,
116                           FormatStyle::SpaceBeforeParensOptions &Value) {
117     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
118     IO.enumCase(Value, "ControlStatements",
119                 FormatStyle::SBPO_ControlStatements);
120     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
121 
122     // For backward compatibility.
123     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
124     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
125   }
126 };
127 
128 template <> struct MappingTraits<FormatStyle> {
129   static void mapping(IO &IO, FormatStyle &Style) {
130     // When reading, read the language first, we need it for getPredefinedStyle.
131     IO.mapOptional("Language", Style.Language);
132 
133     if (IO.outputting()) {
134       StringRef StylesArray[] = { "LLVM",    "Google", "Chromium",
135                                   "Mozilla", "WebKit", "GNU" };
136       ArrayRef<StringRef> Styles(StylesArray);
137       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
138         StringRef StyleName(Styles[i]);
139         FormatStyle PredefinedStyle;
140         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
141             Style == PredefinedStyle) {
142           IO.mapOptional("# BasedOnStyle", StyleName);
143           break;
144         }
145       }
146     } else {
147       StringRef BasedOnStyle;
148       IO.mapOptional("BasedOnStyle", BasedOnStyle);
149       if (!BasedOnStyle.empty()) {
150         FormatStyle::LanguageKind OldLanguage = Style.Language;
151         FormatStyle::LanguageKind Language =
152             ((FormatStyle *)IO.getContext())->Language;
153         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
154           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
155           return;
156         }
157         Style.Language = OldLanguage;
158       }
159     }
160 
161     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
162     IO.mapOptional("ConstructorInitializerIndentWidth",
163                    Style.ConstructorInitializerIndentWidth);
164     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
165     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
166     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
167                    Style.AllowAllParametersOfDeclarationOnNextLine);
168     IO.mapOptional("AllowShortBlocksOnASingleLine",
169                    Style.AllowShortBlocksOnASingleLine);
170     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
171                    Style.AllowShortIfStatementsOnASingleLine);
172     IO.mapOptional("AllowShortLoopsOnASingleLine",
173                    Style.AllowShortLoopsOnASingleLine);
174     IO.mapOptional("AllowShortFunctionsOnASingleLine",
175                    Style.AllowShortFunctionsOnASingleLine);
176     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
177                    Style.AlwaysBreakAfterDefinitionReturnType);
178     IO.mapOptional("AlwaysBreakTemplateDeclarations",
179                    Style.AlwaysBreakTemplateDeclarations);
180     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
181                    Style.AlwaysBreakBeforeMultilineStrings);
182     IO.mapOptional("BreakBeforeBinaryOperators",
183                    Style.BreakBeforeBinaryOperators);
184     IO.mapOptional("BreakBeforeTernaryOperators",
185                    Style.BreakBeforeTernaryOperators);
186     IO.mapOptional("BreakConstructorInitializersBeforeComma",
187                    Style.BreakConstructorInitializersBeforeComma);
188     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
189     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
190     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
191                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
192     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
193     IO.mapOptional("ExperimentalAutoDetectBinPacking",
194                    Style.ExperimentalAutoDetectBinPacking);
195     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
196     IO.mapOptional("IndentWrappedFunctionNames",
197                    Style.IndentWrappedFunctionNames);
198     IO.mapOptional("IndentFunctionDeclarationAfterType",
199                    Style.IndentWrappedFunctionNames);
200     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
201     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
202                    Style.KeepEmptyLinesAtTheStartOfBlocks);
203     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
204     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
205     IO.mapOptional("ObjCSpaceBeforeProtocolList",
206                    Style.ObjCSpaceBeforeProtocolList);
207     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
208                    Style.PenaltyBreakBeforeFirstCallParameter);
209     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
210     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
211     IO.mapOptional("PenaltyBreakFirstLessLess",
212                    Style.PenaltyBreakFirstLessLess);
213     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
214     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
215                    Style.PenaltyReturnTypeOnItsOwnLine);
216     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
217     IO.mapOptional("SpacesBeforeTrailingComments",
218                    Style.SpacesBeforeTrailingComments);
219     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
220     IO.mapOptional("Standard", Style.Standard);
221     IO.mapOptional("IndentWidth", Style.IndentWidth);
222     IO.mapOptional("TabWidth", Style.TabWidth);
223     IO.mapOptional("UseTab", Style.UseTab);
224     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
225     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
226     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
227     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
228     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
229     IO.mapOptional("SpacesInCStyleCastParentheses",
230                    Style.SpacesInCStyleCastParentheses);
231     IO.mapOptional("SpacesInContainerLiterals",
232                    Style.SpacesInContainerLiterals);
233     IO.mapOptional("SpaceBeforeAssignmentOperators",
234                    Style.SpaceBeforeAssignmentOperators);
235     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
236     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
237     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
238 
239     // For backward compatibility.
240     if (!IO.outputting()) {
241       IO.mapOptional("SpaceAfterControlStatementKeyword",
242                      Style.SpaceBeforeParens);
243       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
244       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
245     }
246     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
247     IO.mapOptional("DisableFormat", Style.DisableFormat);
248   }
249 };
250 
251 // Allows to read vector<FormatStyle> while keeping default values.
252 // IO.getContext() should contain a pointer to the FormatStyle structure, that
253 // will be used to get default values for missing keys.
254 // If the first element has no Language specified, it will be treated as the
255 // default one for the following elements.
256 template <> struct DocumentListTraits<std::vector<FormatStyle> > {
257   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
258     return Seq.size();
259   }
260   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
261                               size_t Index) {
262     if (Index >= Seq.size()) {
263       assert(Index == Seq.size());
264       FormatStyle Template;
265       if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
266         Template = Seq[0];
267       } else {
268         Template = *((const FormatStyle *)IO.getContext());
269         Template.Language = FormatStyle::LK_None;
270       }
271       Seq.resize(Index + 1, Template);
272     }
273     return Seq[Index];
274   }
275 };
276 }
277 }
278 
279 namespace clang {
280 namespace format {
281 
282 const std::error_category &getParseCategory() {
283   static ParseErrorCategory C;
284   return C;
285 }
286 std::error_code make_error_code(ParseError e) {
287   return std::error_code(static_cast<int>(e), getParseCategory());
288 }
289 
290 const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
291   return "clang-format.parse_error";
292 }
293 
294 std::string ParseErrorCategory::message(int EV) const {
295   switch (static_cast<ParseError>(EV)) {
296   case ParseError::Success:
297     return "Success";
298   case ParseError::Error:
299     return "Invalid argument";
300   case ParseError::Unsuitable:
301     return "Unsuitable";
302   }
303   llvm_unreachable("unexpected parse error");
304 }
305 
306 FormatStyle getLLVMStyle() {
307   FormatStyle LLVMStyle;
308   LLVMStyle.Language = FormatStyle::LK_Cpp;
309   LLVMStyle.AccessModifierOffset = -2;
310   LLVMStyle.AlignEscapedNewlinesLeft = false;
311   LLVMStyle.AlignTrailingComments = true;
312   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
313   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
314   LLVMStyle.AllowShortBlocksOnASingleLine = false;
315   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
316   LLVMStyle.AllowShortLoopsOnASingleLine = false;
317   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
318   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
319   LLVMStyle.AlwaysBreakTemplateDeclarations = false;
320   LLVMStyle.BinPackParameters = true;
321   LLVMStyle.BreakBeforeBinaryOperators = false;
322   LLVMStyle.BreakBeforeTernaryOperators = true;
323   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
324   LLVMStyle.BreakConstructorInitializersBeforeComma = false;
325   LLVMStyle.ColumnLimit = 80;
326   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
327   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
328   LLVMStyle.ConstructorInitializerIndentWidth = 4;
329   LLVMStyle.ContinuationIndentWidth = 4;
330   LLVMStyle.Cpp11BracedListStyle = true;
331   LLVMStyle.DerivePointerAlignment = false;
332   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
333   LLVMStyle.ForEachMacros.push_back("foreach");
334   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
335   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
336   LLVMStyle.IndentCaseLabels = false;
337   LLVMStyle.IndentWrappedFunctionNames = false;
338   LLVMStyle.IndentWidth = 2;
339   LLVMStyle.TabWidth = 8;
340   LLVMStyle.MaxEmptyLinesToKeep = 1;
341   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
342   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
343   LLVMStyle.ObjCSpaceAfterProperty = false;
344   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
345   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
346   LLVMStyle.SpacesBeforeTrailingComments = 1;
347   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
348   LLVMStyle.UseTab = FormatStyle::UT_Never;
349   LLVMStyle.SpacesInParentheses = false;
350   LLVMStyle.SpacesInSquareBrackets = false;
351   LLVMStyle.SpaceInEmptyParentheses = false;
352   LLVMStyle.SpacesInContainerLiterals = true;
353   LLVMStyle.SpacesInCStyleCastParentheses = false;
354   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
355   LLVMStyle.SpaceBeforeAssignmentOperators = true;
356   LLVMStyle.SpacesInAngles = false;
357 
358   LLVMStyle.PenaltyBreakComment = 300;
359   LLVMStyle.PenaltyBreakFirstLessLess = 120;
360   LLVMStyle.PenaltyBreakString = 1000;
361   LLVMStyle.PenaltyExcessCharacter = 1000000;
362   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
363   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
364 
365   LLVMStyle.DisableFormat = false;
366 
367   return LLVMStyle;
368 }
369 
370 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
371   FormatStyle GoogleStyle = getLLVMStyle();
372   GoogleStyle.Language = Language;
373 
374   GoogleStyle.AccessModifierOffset = -1;
375   GoogleStyle.AlignEscapedNewlinesLeft = true;
376   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
377   GoogleStyle.AllowShortLoopsOnASingleLine = true;
378   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
379   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
380   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
381   GoogleStyle.DerivePointerAlignment = true;
382   GoogleStyle.IndentCaseLabels = true;
383   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
384   GoogleStyle.ObjCSpaceAfterProperty = false;
385   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
386   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
387   GoogleStyle.SpacesBeforeTrailingComments = 2;
388   GoogleStyle.Standard = FormatStyle::LS_Auto;
389 
390   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
391   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
392 
393   if (Language == FormatStyle::LK_JavaScript) {
394     GoogleStyle.BreakBeforeTernaryOperators = false;
395     GoogleStyle.MaxEmptyLinesToKeep = 3;
396     GoogleStyle.SpacesInContainerLiterals = false;
397   } else if (Language == FormatStyle::LK_Proto) {
398     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
399     GoogleStyle.SpacesInContainerLiterals = false;
400   }
401 
402   return GoogleStyle;
403 }
404 
405 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
406   FormatStyle ChromiumStyle = getGoogleStyle(Language);
407   ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
408   ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
409   ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
410   ChromiumStyle.AllowShortLoopsOnASingleLine = false;
411   ChromiumStyle.BinPackParameters = false;
412   ChromiumStyle.DerivePointerAlignment = false;
413   ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
414   return ChromiumStyle;
415 }
416 
417 FormatStyle getMozillaStyle() {
418   FormatStyle MozillaStyle = getLLVMStyle();
419   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
420   MozillaStyle.Cpp11BracedListStyle = false;
421   MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
422   MozillaStyle.DerivePointerAlignment = true;
423   MozillaStyle.IndentCaseLabels = true;
424   MozillaStyle.ObjCSpaceAfterProperty = true;
425   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
426   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
427   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
428   MozillaStyle.Standard = FormatStyle::LS_Cpp03;
429   return MozillaStyle;
430 }
431 
432 FormatStyle getWebKitStyle() {
433   FormatStyle Style = getLLVMStyle();
434   Style.AccessModifierOffset = -4;
435   Style.AlignTrailingComments = false;
436   Style.BreakBeforeBinaryOperators = true;
437   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
438   Style.BreakConstructorInitializersBeforeComma = true;
439   Style.Cpp11BracedListStyle = false;
440   Style.ColumnLimit = 0;
441   Style.IndentWidth = 4;
442   Style.NamespaceIndentation = FormatStyle::NI_Inner;
443   Style.ObjCSpaceAfterProperty = true;
444   Style.PointerAlignment = FormatStyle::PAS_Left;
445   Style.Standard = FormatStyle::LS_Cpp03;
446   return Style;
447 }
448 
449 FormatStyle getGNUStyle() {
450   FormatStyle Style = getLLVMStyle();
451   Style.AlwaysBreakAfterDefinitionReturnType = true;
452   Style.BreakBeforeBinaryOperators = true;
453   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
454   Style.BreakBeforeTernaryOperators = true;
455   Style.Cpp11BracedListStyle = false;
456   Style.ColumnLimit = 79;
457   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
458   Style.Standard = FormatStyle::LS_Cpp03;
459   return Style;
460 }
461 
462 FormatStyle getNoStyle() {
463   FormatStyle NoStyle = getLLVMStyle();
464   NoStyle.DisableFormat = true;
465   return NoStyle;
466 }
467 
468 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
469                         FormatStyle *Style) {
470   if (Name.equals_lower("llvm")) {
471     *Style = getLLVMStyle();
472   } else if (Name.equals_lower("chromium")) {
473     *Style = getChromiumStyle(Language);
474   } else if (Name.equals_lower("mozilla")) {
475     *Style = getMozillaStyle();
476   } else if (Name.equals_lower("google")) {
477     *Style = getGoogleStyle(Language);
478   } else if (Name.equals_lower("webkit")) {
479     *Style = getWebKitStyle();
480   } else if (Name.equals_lower("gnu")) {
481     *Style = getGNUStyle();
482   } else if (Name.equals_lower("none")) {
483     *Style = getNoStyle();
484   } else {
485     return false;
486   }
487 
488   Style->Language = Language;
489   return true;
490 }
491 
492 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
493   assert(Style);
494   FormatStyle::LanguageKind Language = Style->Language;
495   assert(Language != FormatStyle::LK_None);
496   if (Text.trim().empty())
497     return make_error_code(ParseError::Error);
498 
499   std::vector<FormatStyle> Styles;
500   llvm::yaml::Input Input(Text);
501   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
502   // values for the fields, keys for which are missing from the configuration.
503   // Mapping also uses the context to get the language to find the correct
504   // base style.
505   Input.setContext(Style);
506   Input >> Styles;
507   if (Input.error())
508     return Input.error();
509 
510   for (unsigned i = 0; i < Styles.size(); ++i) {
511     // Ensures that only the first configuration can skip the Language option.
512     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
513       return make_error_code(ParseError::Error);
514     // Ensure that each language is configured at most once.
515     for (unsigned j = 0; j < i; ++j) {
516       if (Styles[i].Language == Styles[j].Language) {
517         DEBUG(llvm::dbgs()
518               << "Duplicate languages in the config file on positions " << j
519               << " and " << i << "\n");
520         return make_error_code(ParseError::Error);
521       }
522     }
523   }
524   // Look for a suitable configuration starting from the end, so we can
525   // find the configuration for the specific language first, and the default
526   // configuration (which can only be at slot 0) after it.
527   for (int i = Styles.size() - 1; i >= 0; --i) {
528     if (Styles[i].Language == Language ||
529         Styles[i].Language == FormatStyle::LK_None) {
530       *Style = Styles[i];
531       Style->Language = Language;
532       return make_error_code(ParseError::Success);
533     }
534   }
535   return make_error_code(ParseError::Unsuitable);
536 }
537 
538 std::string configurationAsText(const FormatStyle &Style) {
539   std::string Text;
540   llvm::raw_string_ostream Stream(Text);
541   llvm::yaml::Output Output(Stream);
542   // We use the same mapping method for input and output, so we need a non-const
543   // reference here.
544   FormatStyle NonConstStyle = Style;
545   Output << NonConstStyle;
546   return Stream.str();
547 }
548 
549 namespace {
550 
551 class NoColumnLimitFormatter {
552 public:
553   NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
554 
555   /// \brief Formats the line starting at \p State, simply keeping all of the
556   /// input's line breaking decisions.
557   void format(unsigned FirstIndent, const AnnotatedLine *Line) {
558     LineState State =
559         Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
560     while (State.NextToken) {
561       bool Newline =
562           Indenter->mustBreak(State) ||
563           (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
564       Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
565     }
566   }
567 
568 private:
569   ContinuationIndenter *Indenter;
570 };
571 
572 class LineJoiner {
573 public:
574   LineJoiner(const FormatStyle &Style) : Style(Style) {}
575 
576   /// \brief Calculates how many lines can be merged into 1 starting at \p I.
577   unsigned
578   tryFitMultipleLinesInOne(unsigned Indent,
579                            SmallVectorImpl<AnnotatedLine *>::const_iterator I,
580                            SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
581     // We can never merge stuff if there are trailing line comments.
582     const AnnotatedLine *TheLine = *I;
583     if (TheLine->Last->Type == TT_LineComment)
584       return 0;
585 
586     if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
587       return 0;
588 
589     unsigned Limit =
590         Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
591     // If we already exceed the column limit, we set 'Limit' to 0. The different
592     // tryMerge..() functions can then decide whether to still do merging.
593     Limit = TheLine->Last->TotalLength > Limit
594                 ? 0
595                 : Limit - TheLine->Last->TotalLength;
596 
597     if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
598       return 0;
599 
600     // FIXME: TheLine->Level != 0 might or might not be the right check to do.
601     // If necessary, change to something smarter.
602     bool MergeShortFunctions =
603         Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
604         (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
605          TheLine->Level != 0);
606 
607     if (TheLine->Last->Type == TT_FunctionLBrace &&
608         TheLine->First != TheLine->Last) {
609       return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
610     }
611     if (TheLine->Last->is(tok::l_brace)) {
612       return Style.BreakBeforeBraces == FormatStyle::BS_Attach
613                  ? tryMergeSimpleBlock(I, E, Limit)
614                  : 0;
615     }
616     if (I[1]->First->Type == TT_FunctionLBrace &&
617         Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
618       // Check for Limit <= 2 to account for the " {".
619       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
620         return 0;
621       Limit -= 2;
622 
623       unsigned MergedLines = 0;
624       if (MergeShortFunctions) {
625         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
626         // If we managed to merge the block, count the function header, which is
627         // on a separate line.
628         if (MergedLines > 0)
629           ++MergedLines;
630       }
631       return MergedLines;
632     }
633     if (TheLine->First->is(tok::kw_if)) {
634       return Style.AllowShortIfStatementsOnASingleLine
635                  ? tryMergeSimpleControlStatement(I, E, Limit)
636                  : 0;
637     }
638     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
639       return Style.AllowShortLoopsOnASingleLine
640                  ? tryMergeSimpleControlStatement(I, E, Limit)
641                  : 0;
642     }
643     if (TheLine->InPPDirective &&
644         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
645       return tryMergeSimplePPDirective(I, E, Limit);
646     }
647     return 0;
648   }
649 
650 private:
651   unsigned
652   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
653                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
654                             unsigned Limit) {
655     if (Limit == 0)
656       return 0;
657     if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
658       return 0;
659     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
660       return 0;
661     if (1 + I[1]->Last->TotalLength > Limit)
662       return 0;
663     return 1;
664   }
665 
666   unsigned tryMergeSimpleControlStatement(
667       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
668       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
669     if (Limit == 0)
670       return 0;
671     if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
672          Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
673         (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
674       return 0;
675     if (I[1]->InPPDirective != (*I)->InPPDirective ||
676         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
677       return 0;
678     Limit = limitConsideringMacros(I + 1, E, Limit);
679     AnnotatedLine &Line = **I;
680     if (Line.Last->isNot(tok::r_paren))
681       return 0;
682     if (1 + I[1]->Last->TotalLength > Limit)
683       return 0;
684     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
685                              tok::kw_while) ||
686         I[1]->First->Type == TT_LineComment)
687       return 0;
688     // Only inline simple if's (no nested if or else).
689     if (I + 2 != E && Line.First->is(tok::kw_if) &&
690         I[2]->First->is(tok::kw_else))
691       return 0;
692     return 1;
693   }
694 
695   unsigned
696   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
697                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
698                       unsigned Limit) {
699     AnnotatedLine &Line = **I;
700 
701     // Don't merge ObjC @ keywords and methods.
702     if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
703       return 0;
704 
705     // Check that the current line allows merging. This depends on whether we
706     // are in a control flow statements as well as several style flags.
707     if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
708       return 0;
709     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
710                             tok::kw_catch, tok::kw_for, tok::r_brace)) {
711       if (!Style.AllowShortBlocksOnASingleLine)
712         return 0;
713       if (!Style.AllowShortIfStatementsOnASingleLine &&
714           Line.First->is(tok::kw_if))
715         return 0;
716       if (!Style.AllowShortLoopsOnASingleLine &&
717           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
718         return 0;
719       // FIXME: Consider an option to allow short exception handling clauses on
720       // a single line.
721       if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
722         return 0;
723     }
724 
725     FormatToken *Tok = I[1]->First;
726     if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
727         (Tok->getNextNonComment() == nullptr ||
728          Tok->getNextNonComment()->is(tok::semi))) {
729       // We merge empty blocks even if the line exceeds the column limit.
730       Tok->SpacesRequiredBefore = 0;
731       Tok->CanBreakBefore = true;
732       return 1;
733     } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
734       // We don't merge short records.
735       if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
736         return 0;
737 
738       // Check that we still have three lines and they fit into the limit.
739       if (I + 2 == E || I[2]->Type == LT_Invalid)
740         return 0;
741       Limit = limitConsideringMacros(I + 2, E, Limit);
742 
743       if (!nextTwoLinesFitInto(I, Limit))
744         return 0;
745 
746       // Second, check that the next line does not contain any braces - if it
747       // does, readability declines when putting it into a single line.
748       if (I[1]->Last->Type == TT_LineComment)
749         return 0;
750       do {
751         if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
752           return 0;
753         Tok = Tok->Next;
754       } while (Tok);
755 
756       // Last, check that the third line starts with a closing brace.
757       Tok = I[2]->First;
758       if (Tok->isNot(tok::r_brace))
759         return 0;
760 
761       return 2;
762     }
763     return 0;
764   }
765 
766   /// Returns the modified column limit for \p I if it is inside a macro and
767   /// needs a trailing '\'.
768   unsigned
769   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
770                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
771                          unsigned Limit) {
772     if (I[0]->InPPDirective && I + 1 != E &&
773         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
774       return Limit < 2 ? 0 : Limit - 2;
775     }
776     return Limit;
777   }
778 
779   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
780                            unsigned Limit) {
781     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
782       return false;
783     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
784   }
785 
786   bool containsMustBreak(const AnnotatedLine *Line) {
787     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
788       if (Tok->MustBreakBefore)
789         return true;
790     }
791     return false;
792   }
793 
794   const FormatStyle &Style;
795 };
796 
797 class UnwrappedLineFormatter {
798 public:
799   UnwrappedLineFormatter(ContinuationIndenter *Indenter,
800                          WhitespaceManager *Whitespaces,
801                          const FormatStyle &Style)
802       : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
803         Joiner(Style) {}
804 
805   unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
806                   int AdditionalIndent = 0, bool FixBadIndentation = false) {
807     // Try to look up already computed penalty in DryRun-mode.
808     std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
809         &Lines, AdditionalIndent);
810     auto CacheIt = PenaltyCache.find(CacheKey);
811     if (DryRun && CacheIt != PenaltyCache.end())
812       return CacheIt->second;
813 
814     assert(!Lines.empty());
815     unsigned Penalty = 0;
816     std::vector<int> IndentForLevel;
817     for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
818       IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
819     const AnnotatedLine *PreviousLine = nullptr;
820     for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
821                                                           E = Lines.end();
822          I != E; ++I) {
823       const AnnotatedLine &TheLine = **I;
824       const FormatToken *FirstTok = TheLine.First;
825       int Offset = getIndentOffset(*FirstTok);
826 
827       // Determine indent and try to merge multiple unwrapped lines.
828       unsigned Indent;
829       if (TheLine.InPPDirective) {
830         Indent = TheLine.Level * Style.IndentWidth;
831       } else {
832         while (IndentForLevel.size() <= TheLine.Level)
833           IndentForLevel.push_back(-1);
834         IndentForLevel.resize(TheLine.Level + 1);
835         Indent = getIndent(IndentForLevel, TheLine.Level);
836       }
837       unsigned LevelIndent = Indent;
838       if (static_cast<int>(Indent) + Offset >= 0)
839         Indent += Offset;
840 
841       // Merge multiple lines if possible.
842       unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
843       if (MergedLines > 0 && Style.ColumnLimit == 0) {
844         // Disallow line merging if there is a break at the start of one of the
845         // input lines.
846         for (unsigned i = 0; i < MergedLines; ++i) {
847           if (I[i + 1]->First->NewlinesBefore > 0)
848             MergedLines = 0;
849         }
850       }
851       if (!DryRun) {
852         for (unsigned i = 0; i < MergedLines; ++i) {
853           join(*I[i], *I[i + 1]);
854         }
855       }
856       I += MergedLines;
857 
858       bool FixIndentation =
859           FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
860       if (TheLine.First->is(tok::eof)) {
861         if (PreviousLine && PreviousLine->Affected && !DryRun) {
862           // Remove the file's trailing whitespace.
863           unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
864           Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
865                                          /*IndentLevel=*/0, /*Spaces=*/0,
866                                          /*TargetColumn=*/0);
867         }
868       } else if (TheLine.Type != LT_Invalid &&
869                  (TheLine.Affected || FixIndentation)) {
870         if (FirstTok->WhitespaceRange.isValid()) {
871           if (!DryRun)
872             formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
873                              Indent, TheLine.InPPDirective);
874         } else {
875           Indent = LevelIndent = FirstTok->OriginalColumn;
876         }
877 
878         // If everything fits on a single line, just put it there.
879         unsigned ColumnLimit = Style.ColumnLimit;
880         if (I + 1 != E) {
881           AnnotatedLine *NextLine = I[1];
882           if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
883             ColumnLimit = getColumnLimit(TheLine.InPPDirective);
884         }
885 
886         if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
887           LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
888           while (State.NextToken) {
889             formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
890             Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
891           }
892         } else if (Style.ColumnLimit == 0) {
893           // FIXME: Implement nested blocks for ColumnLimit = 0.
894           NoColumnLimitFormatter Formatter(Indenter);
895           if (!DryRun)
896             Formatter.format(Indent, &TheLine);
897         } else {
898           Penalty += format(TheLine, Indent, DryRun);
899         }
900 
901         if (!TheLine.InPPDirective)
902           IndentForLevel[TheLine.Level] = LevelIndent;
903       } else if (TheLine.ChildrenAffected) {
904         format(TheLine.Children, DryRun);
905       } else {
906         // Format the first token if necessary, and notify the WhitespaceManager
907         // about the unchanged whitespace.
908         for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
909           if (Tok == TheLine.First &&
910               (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
911             unsigned LevelIndent = Tok->OriginalColumn;
912             if (!DryRun) {
913               // Remove trailing whitespace of the previous line.
914               if ((PreviousLine && PreviousLine->Affected) ||
915                   TheLine.LeadingEmptyLinesAffected) {
916                 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
917                                  TheLine.InPPDirective);
918               } else {
919                 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
920               }
921             }
922 
923             if (static_cast<int>(LevelIndent) - Offset >= 0)
924               LevelIndent -= Offset;
925             if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
926               IndentForLevel[TheLine.Level] = LevelIndent;
927           } else if (!DryRun) {
928             Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
929           }
930         }
931       }
932       if (!DryRun) {
933         for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
934           Tok->Finalized = true;
935         }
936       }
937       PreviousLine = *I;
938     }
939     PenaltyCache[CacheKey] = Penalty;
940     return Penalty;
941   }
942 
943 private:
944   /// \brief Formats an \c AnnotatedLine and returns the penalty.
945   ///
946   /// If \p DryRun is \c false, directly applies the changes.
947   unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
948                   bool DryRun) {
949     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
950 
951     // If the ObjC method declaration does not fit on a line, we should format
952     // it with one arg per line.
953     if (State.Line->Type == LT_ObjCMethodDecl)
954       State.Stack.back().BreakBeforeParameter = true;
955 
956     // Find best solution in solution space.
957     return analyzeSolutionSpace(State, DryRun);
958   }
959 
960   /// \brief An edge in the solution space from \c Previous->State to \c State,
961   /// inserting a newline dependent on the \c NewLine.
962   struct StateNode {
963     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
964         : State(State), NewLine(NewLine), Previous(Previous) {}
965     LineState State;
966     bool NewLine;
967     StateNode *Previous;
968   };
969 
970   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
971   ///
972   /// In case of equal penalties, we want to prefer states that were inserted
973   /// first. During state generation we make sure that we insert states first
974   /// that break the line as late as possible.
975   typedef std::pair<unsigned, unsigned> OrderedPenalty;
976 
977   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
978   /// \c State has the given \c OrderedPenalty.
979   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
980 
981   /// \brief The BFS queue type.
982   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
983                               std::greater<QueueItem> > QueueType;
984 
985   /// \brief Get the offset of the line relatively to the level.
986   ///
987   /// For example, 'public:' labels in classes are offset by 1 or 2
988   /// characters to the left from their level.
989   int getIndentOffset(const FormatToken &RootToken) {
990     if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
991       return Style.AccessModifierOffset;
992     return 0;
993   }
994 
995   /// \brief Add a new line and the required indent before the first Token
996   /// of the \c UnwrappedLine if there was no structural parsing error.
997   void formatFirstToken(FormatToken &RootToken,
998                         const AnnotatedLine *PreviousLine, unsigned IndentLevel,
999                         unsigned Indent, bool InPPDirective) {
1000     unsigned Newlines =
1001         std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1002     // Remove empty lines before "}" where applicable.
1003     if (RootToken.is(tok::r_brace) &&
1004         (!RootToken.Next ||
1005          (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1006       Newlines = std::min(Newlines, 1u);
1007     if (Newlines == 0 && !RootToken.IsFirst)
1008       Newlines = 1;
1009     if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1010       Newlines = 0;
1011 
1012     // Remove empty lines after "{".
1013     if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1014         PreviousLine->Last->is(tok::l_brace) &&
1015         PreviousLine->First->isNot(tok::kw_namespace))
1016       Newlines = 1;
1017 
1018     // Insert extra new line before access specifiers.
1019     if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1020         RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1021       ++Newlines;
1022 
1023     // Remove empty lines after access specifiers.
1024     if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1025       Newlines = std::min(1u, Newlines);
1026 
1027     Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1028                                    Indent, InPPDirective &&
1029                                                !RootToken.HasUnescapedNewline);
1030   }
1031 
1032   /// \brief Get the indent of \p Level from \p IndentForLevel.
1033   ///
1034   /// \p IndentForLevel must contain the indent for the level \c l
1035   /// at \p IndentForLevel[l], or a value < 0 if the indent for
1036   /// that level is unknown.
1037   unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1038     if (IndentForLevel[Level] != -1)
1039       return IndentForLevel[Level];
1040     if (Level == 0)
1041       return 0;
1042     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1043   }
1044 
1045   void join(AnnotatedLine &A, const AnnotatedLine &B) {
1046     assert(!A.Last->Next);
1047     assert(!B.First->Previous);
1048     if (B.Affected)
1049       A.Affected = true;
1050     A.Last->Next = B.First;
1051     B.First->Previous = A.Last;
1052     B.First->CanBreakBefore = true;
1053     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1054     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1055       Tok->TotalLength += LengthA;
1056       A.Last = Tok;
1057     }
1058   }
1059 
1060   unsigned getColumnLimit(bool InPPDirective) const {
1061     // In preprocessor directives reserve two chars for trailing " \"
1062     return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1063   }
1064 
1065   struct CompareLineStatePointers {
1066     bool operator()(LineState *obj1, LineState *obj2) const {
1067       return *obj1 < *obj2;
1068     }
1069   };
1070 
1071   /// \brief Analyze the entire solution space starting from \p InitialState.
1072   ///
1073   /// This implements a variant of Dijkstra's algorithm on the graph that spans
1074   /// the solution space (\c LineStates are the nodes). The algorithm tries to
1075   /// find the shortest path (the one with lowest penalty) from \p InitialState
1076   /// to a state where all tokens are placed. Returns the penalty.
1077   ///
1078   /// If \p DryRun is \c false, directly applies the changes.
1079   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
1080     std::set<LineState *, CompareLineStatePointers> Seen;
1081 
1082     // Increasing count of \c StateNode items we have created. This is used to
1083     // create a deterministic order independent of the container.
1084     unsigned Count = 0;
1085     QueueType Queue;
1086 
1087     // Insert start element into queue.
1088     StateNode *Node =
1089         new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1090     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1091     ++Count;
1092 
1093     unsigned Penalty = 0;
1094 
1095     // While not empty, take first element and follow edges.
1096     while (!Queue.empty()) {
1097       Penalty = Queue.top().first.first;
1098       StateNode *Node = Queue.top().second;
1099       if (!Node->State.NextToken) {
1100         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
1101         break;
1102       }
1103       Queue.pop();
1104 
1105       // Cut off the analysis of certain solutions if the analysis gets too
1106       // complex. See description of IgnoreStackForComparison.
1107       if (Count > 10000)
1108         Node->State.IgnoreStackForComparison = true;
1109 
1110       if (!Seen.insert(&Node->State).second)
1111         // State already examined with lower penalty.
1112         continue;
1113 
1114       FormatDecision LastFormat = Node->State.NextToken->Decision;
1115       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1116         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1117       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1118         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1119     }
1120 
1121     if (Queue.empty()) {
1122       // We were unable to find a solution, do nothing.
1123       // FIXME: Add diagnostic?
1124       DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1125       return 0;
1126     }
1127 
1128     // Reconstruct the solution.
1129     if (!DryRun)
1130       reconstructPath(InitialState, Queue.top().second);
1131 
1132     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1133     DEBUG(llvm::dbgs() << "---\n");
1134 
1135     return Penalty;
1136   }
1137 
1138   void reconstructPath(LineState &State, StateNode *Current) {
1139     std::deque<StateNode *> Path;
1140     // We do not need a break before the initial token.
1141     while (Current->Previous) {
1142       Path.push_front(Current);
1143       Current = Current->Previous;
1144     }
1145     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1146          I != E; ++I) {
1147       unsigned Penalty = 0;
1148       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1149       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1150 
1151       DEBUG({
1152         if ((*I)->NewLine) {
1153           llvm::dbgs() << "Penalty for placing "
1154                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1155                        << Penalty << "\n";
1156         }
1157       });
1158     }
1159   }
1160 
1161   /// \brief Add the following state to the analysis queue \c Queue.
1162   ///
1163   /// Assume the current state is \p PreviousNode and has been reached with a
1164   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1165   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1166                            bool NewLine, unsigned *Count, QueueType *Queue) {
1167     if (NewLine && !Indenter->canBreak(PreviousNode->State))
1168       return;
1169     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1170       return;
1171 
1172     StateNode *Node = new (Allocator.Allocate())
1173         StateNode(PreviousNode->State, NewLine, PreviousNode);
1174     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1175       return;
1176 
1177     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1178 
1179     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1180     ++(*Count);
1181   }
1182 
1183   /// \brief If the \p State's next token is an r_brace closing a nested block,
1184   /// format the nested block before it.
1185   ///
1186   /// Returns \c true if all children could be placed successfully and adapts
1187   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1188   /// creates changes using \c Whitespaces.
1189   ///
1190   /// The crucial idea here is that children always get formatted upon
1191   /// encountering the closing brace right after the nested block. Now, if we
1192   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1193   /// \c false), the entire block has to be kept on the same line (which is only
1194   /// possible if it fits on the line, only contains a single statement, etc.
1195   ///
1196   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1197   /// break after the "{", format all lines with correct indentation and the put
1198   /// the closing "}" on yet another new line.
1199   ///
1200   /// This enables us to keep the simple structure of the
1201   /// \c UnwrappedLineFormatter, where we only have two options for each token:
1202   /// break or don't break.
1203   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1204                       unsigned &Penalty) {
1205     FormatToken &Previous = *State.NextToken->Previous;
1206     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1207     if (!LBrace || LBrace->isNot(tok::l_brace) ||
1208         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
1209       // The previous token does not open a block. Nothing to do. We don't
1210       // assert so that we can simply call this function for all tokens.
1211       return true;
1212 
1213     if (NewLine) {
1214       int AdditionalIndent =
1215           State.FirstIndent - State.Line->Level * Style.IndentWidth;
1216       if (State.Stack.size() < 2 ||
1217           !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1218         AdditionalIndent = State.Stack.back().Indent -
1219                            Previous.Children[0]->Level * Style.IndentWidth;
1220       }
1221 
1222       Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1223                         /*FixBadIndentation=*/true);
1224       return true;
1225     }
1226 
1227     // Cannot merge multiple statements into a single line.
1228     if (Previous.Children.size() > 1)
1229       return false;
1230 
1231     // Cannot merge into one line if this line ends on a comment.
1232     if (Previous.is(tok::comment))
1233       return false;
1234 
1235     // We can't put the closing "}" on a line with a trailing comment.
1236     if (Previous.Children[0]->Last->isTrailingComment())
1237       return false;
1238 
1239     // If the child line exceeds the column limit, we wouldn't want to merge it.
1240     // We add +2 for the trailing " }".
1241     if (Style.ColumnLimit > 0 &&
1242         Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1243             Style.ColumnLimit)
1244       return false;
1245 
1246     if (!DryRun) {
1247       Whitespaces->replaceWhitespace(
1248           *Previous.Children[0]->First,
1249           /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
1250           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
1251     }
1252     Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
1253 
1254     State.Column += 1 + Previous.Children[0]->Last->TotalLength;
1255     return true;
1256   }
1257 
1258   ContinuationIndenter *Indenter;
1259   WhitespaceManager *Whitespaces;
1260   FormatStyle Style;
1261   LineJoiner Joiner;
1262 
1263   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1264 
1265   // Cache to store the penalty of formatting a vector of AnnotatedLines
1266   // starting from a specific additional offset. Improves performance if there
1267   // are many nested blocks.
1268   std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1269            unsigned> PenaltyCache;
1270 };
1271 
1272 class FormatTokenLexer {
1273 public:
1274   FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
1275                    encoding::Encoding Encoding)
1276       : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1277         Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1278         Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
1279         FirstInLineIndex(0), FormattingDisabled(false) {
1280     Lex.SetKeepWhitespaceMode(true);
1281 
1282     for (const std::string &ForEachMacro : Style.ForEachMacros)
1283       ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1284     std::sort(ForEachMacros.begin(), ForEachMacros.end());
1285   }
1286 
1287   ArrayRef<FormatToken *> lex() {
1288     assert(Tokens.empty());
1289     assert(FirstInLineIndex == 0);
1290     do {
1291       Tokens.push_back(getNextToken());
1292       tryMergePreviousTokens();
1293       if (Tokens.back()->NewlinesBefore > 0)
1294         FirstInLineIndex = Tokens.size() - 1;
1295     } while (Tokens.back()->Tok.isNot(tok::eof));
1296     return Tokens;
1297   }
1298 
1299   IdentifierTable &getIdentTable() { return IdentTable; }
1300 
1301 private:
1302   void tryMergePreviousTokens() {
1303     if (tryMerge_TMacro())
1304       return;
1305     if (tryMergeConflictMarkers())
1306       return;
1307 
1308     if (Style.Language == FormatStyle::LK_JavaScript) {
1309       if (tryMergeEscapeSequence())
1310         return;
1311       if (tryMergeJSRegexLiteral())
1312         return;
1313 
1314       static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1315       static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1316       static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1317                                                tok::greaterequal };
1318       static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
1319       // FIXME: We probably need to change token type to mimic operator with the
1320       // correct priority.
1321       if (tryMergeTokens(JSIdentity))
1322         return;
1323       if (tryMergeTokens(JSNotIdentity))
1324         return;
1325       if (tryMergeTokens(JSShiftEqual))
1326         return;
1327       if (tryMergeTokens(JSRightArrow))
1328         return;
1329     }
1330   }
1331 
1332   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1333     if (Tokens.size() < Kinds.size())
1334       return false;
1335 
1336     SmallVectorImpl<FormatToken *>::const_iterator First =
1337         Tokens.end() - Kinds.size();
1338     if (!First[0]->is(Kinds[0]))
1339       return false;
1340     unsigned AddLength = 0;
1341     for (unsigned i = 1; i < Kinds.size(); ++i) {
1342       if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1343                                          First[i]->WhitespaceRange.getEnd())
1344         return false;
1345       AddLength += First[i]->TokenText.size();
1346     }
1347     Tokens.resize(Tokens.size() - Kinds.size() + 1);
1348     First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1349                                     First[0]->TokenText.size() + AddLength);
1350     First[0]->ColumnWidth += AddLength;
1351     return true;
1352   }
1353 
1354   // Tries to merge an escape sequence, i.e. a "\\" and the following
1355   // character. Use e.g. inside JavaScript regex literals.
1356   bool tryMergeEscapeSequence() {
1357     if (Tokens.size() < 2)
1358       return false;
1359     FormatToken *Previous = Tokens[Tokens.size() - 2];
1360     if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1361         Tokens.back()->NewlinesBefore != 0)
1362       return false;
1363     Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1364     StringRef Text = Previous->TokenText;
1365     Previous->TokenText =
1366         StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1367     Tokens.resize(Tokens.size() - 1);
1368     return true;
1369   }
1370 
1371   // Try to determine whether the current token ends a JavaScript regex literal.
1372   // We heuristically assume that this is a regex literal if we find two
1373   // unescaped slashes on a line and the token before the first slash is one of
1374   // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1375   // a division.
1376   bool tryMergeJSRegexLiteral() {
1377     if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
1378         (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1379          Tokens[Tokens.size() - 2]->TokenText == "\\"))
1380       return false;
1381     unsigned TokenCount = 0;
1382     unsigned LastColumn = Tokens.back()->OriginalColumn;
1383     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1384       ++TokenCount;
1385       if (I[0]->is(tok::slash) && I + 1 != E &&
1386           (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1387                          tok::exclaim, tok::l_square, tok::colon, tok::comma,
1388                          tok::question, tok::kw_return) ||
1389            I[1]->isBinaryOperator())) {
1390         Tokens.resize(Tokens.size() - TokenCount);
1391         Tokens.back()->Tok.setKind(tok::unknown);
1392         Tokens.back()->Type = TT_RegexLiteral;
1393         Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1394         return true;
1395       }
1396 
1397       // There can't be a newline inside a regex literal.
1398       if (I[0]->NewlinesBefore > 0)
1399         return false;
1400     }
1401     return false;
1402   }
1403 
1404   bool tryMerge_TMacro() {
1405     if (Tokens.size() < 4)
1406       return false;
1407     FormatToken *Last = Tokens.back();
1408     if (!Last->is(tok::r_paren))
1409       return false;
1410 
1411     FormatToken *String = Tokens[Tokens.size() - 2];
1412     if (!String->is(tok::string_literal) || String->IsMultiline)
1413       return false;
1414 
1415     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1416       return false;
1417 
1418     FormatToken *Macro = Tokens[Tokens.size() - 4];
1419     if (Macro->TokenText != "_T")
1420       return false;
1421 
1422     const char *Start = Macro->TokenText.data();
1423     const char *End = Last->TokenText.data() + Last->TokenText.size();
1424     String->TokenText = StringRef(Start, End - Start);
1425     String->IsFirst = Macro->IsFirst;
1426     String->LastNewlineOffset = Macro->LastNewlineOffset;
1427     String->WhitespaceRange = Macro->WhitespaceRange;
1428     String->OriginalColumn = Macro->OriginalColumn;
1429     String->ColumnWidth = encoding::columnWidthWithTabs(
1430         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1431 
1432     Tokens.pop_back();
1433     Tokens.pop_back();
1434     Tokens.pop_back();
1435     Tokens.back() = String;
1436     return true;
1437   }
1438 
1439   bool tryMergeConflictMarkers() {
1440     if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1441       return false;
1442 
1443     // Conflict lines look like:
1444     // <marker> <text from the vcs>
1445     // For example:
1446     // >>>>>>> /file/in/file/system at revision 1234
1447     //
1448     // We merge all tokens in a line that starts with a conflict marker
1449     // into a single token with a special token type that the unwrapped line
1450     // parser will use to correctly rebuild the underlying code.
1451 
1452     FileID ID;
1453     // Get the position of the first token in the line.
1454     unsigned FirstInLineOffset;
1455     std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1456         Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1457     StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1458     // Calculate the offset of the start of the current line.
1459     auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1460     if (LineOffset == StringRef::npos) {
1461       LineOffset = 0;
1462     } else {
1463       ++LineOffset;
1464     }
1465 
1466     auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1467     StringRef LineStart;
1468     if (FirstSpace == StringRef::npos) {
1469       LineStart = Buffer.substr(LineOffset);
1470     } else {
1471       LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1472     }
1473 
1474     TokenType Type = TT_Unknown;
1475     if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1476       Type = TT_ConflictStart;
1477     } else if (LineStart == "|||||||" || LineStart == "=======" ||
1478                LineStart == "====") {
1479       Type = TT_ConflictAlternative;
1480     } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1481       Type = TT_ConflictEnd;
1482     }
1483 
1484     if (Type != TT_Unknown) {
1485       FormatToken *Next = Tokens.back();
1486 
1487       Tokens.resize(FirstInLineIndex + 1);
1488       // We do not need to build a complete token here, as we will skip it
1489       // during parsing anyway (as we must not touch whitespace around conflict
1490       // markers).
1491       Tokens.back()->Type = Type;
1492       Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1493 
1494       Tokens.push_back(Next);
1495       return true;
1496     }
1497 
1498     return false;
1499   }
1500 
1501   FormatToken *getNextToken() {
1502     if (GreaterStashed) {
1503       // Create a synthesized second '>' token.
1504       // FIXME: Increment Column and set OriginalColumn.
1505       Token Greater = FormatTok->Tok;
1506       FormatTok = new (Allocator.Allocate()) FormatToken;
1507       FormatTok->Tok = Greater;
1508       SourceLocation GreaterLocation =
1509           FormatTok->Tok.getLocation().getLocWithOffset(1);
1510       FormatTok->WhitespaceRange =
1511           SourceRange(GreaterLocation, GreaterLocation);
1512       FormatTok->TokenText = ">";
1513       FormatTok->ColumnWidth = 1;
1514       GreaterStashed = false;
1515       return FormatTok;
1516     }
1517 
1518     FormatTok = new (Allocator.Allocate()) FormatToken;
1519     readRawToken(*FormatTok);
1520     SourceLocation WhitespaceStart =
1521         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1522     FormatTok->IsFirst = IsFirstToken;
1523     IsFirstToken = false;
1524 
1525     // Consume and record whitespace until we find a significant token.
1526     unsigned WhitespaceLength = TrailingWhitespace;
1527     while (FormatTok->Tok.is(tok::unknown)) {
1528       for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1529         switch (FormatTok->TokenText[i]) {
1530         case '\n':
1531           ++FormatTok->NewlinesBefore;
1532           // FIXME: This is technically incorrect, as it could also
1533           // be a literal backslash at the end of the line.
1534           if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1535                          (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1536                           FormatTok->TokenText[i - 2] != '\\')))
1537             FormatTok->HasUnescapedNewline = true;
1538           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1539           Column = 0;
1540           break;
1541         case '\r':
1542         case '\f':
1543         case '\v':
1544           Column = 0;
1545           break;
1546         case ' ':
1547           ++Column;
1548           break;
1549         case '\t':
1550           Column += Style.TabWidth - Column % Style.TabWidth;
1551           break;
1552         case '\\':
1553           ++Column;
1554           if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1555                              FormatTok->TokenText[i + 1] != '\n'))
1556             FormatTok->Type = TT_ImplicitStringLiteral;
1557           break;
1558         default:
1559           FormatTok->Type = TT_ImplicitStringLiteral;
1560           ++Column;
1561           break;
1562         }
1563       }
1564 
1565       if (FormatTok->Type == TT_ImplicitStringLiteral)
1566         break;
1567       WhitespaceLength += FormatTok->Tok.getLength();
1568 
1569       readRawToken(*FormatTok);
1570     }
1571 
1572     // In case the token starts with escaped newlines, we want to
1573     // take them into account as whitespace - this pattern is quite frequent
1574     // in macro definitions.
1575     // FIXME: Add a more explicit test.
1576     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1577            FormatTok->TokenText[1] == '\n') {
1578       ++FormatTok->NewlinesBefore;
1579       WhitespaceLength += 2;
1580       Column = 0;
1581       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1582     }
1583 
1584     FormatTok->WhitespaceRange = SourceRange(
1585         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1586 
1587     FormatTok->OriginalColumn = Column;
1588 
1589     TrailingWhitespace = 0;
1590     if (FormatTok->Tok.is(tok::comment)) {
1591       // FIXME: Add the trimmed whitespace to Column.
1592       StringRef UntrimmedText = FormatTok->TokenText;
1593       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1594       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1595     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1596       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1597       FormatTok->Tok.setIdentifierInfo(&Info);
1598       FormatTok->Tok.setKind(Info.getTokenID());
1599     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1600       FormatTok->Tok.setKind(tok::greater);
1601       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1602       GreaterStashed = true;
1603     }
1604 
1605     // Now FormatTok is the next non-whitespace token.
1606 
1607     StringRef Text = FormatTok->TokenText;
1608     size_t FirstNewlinePos = Text.find('\n');
1609     if (FirstNewlinePos == StringRef::npos) {
1610       // FIXME: ColumnWidth actually depends on the start column, we need to
1611       // take this into account when the token is moved.
1612       FormatTok->ColumnWidth =
1613           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1614       Column += FormatTok->ColumnWidth;
1615     } else {
1616       FormatTok->IsMultiline = true;
1617       // FIXME: ColumnWidth actually depends on the start column, we need to
1618       // take this into account when the token is moved.
1619       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1620           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1621 
1622       // The last line of the token always starts in column 0.
1623       // Thus, the length can be precomputed even in the presence of tabs.
1624       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1625           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1626           Encoding);
1627       Column = FormatTok->LastLineColumnWidth;
1628     }
1629 
1630     FormatTok->IsForEachMacro =
1631         std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1632                            FormatTok->Tok.getIdentifierInfo());
1633 
1634     return FormatTok;
1635   }
1636 
1637   FormatToken *FormatTok;
1638   bool IsFirstToken;
1639   bool GreaterStashed;
1640   unsigned Column;
1641   unsigned TrailingWhitespace;
1642   Lexer &Lex;
1643   SourceManager &SourceMgr;
1644   FormatStyle &Style;
1645   IdentifierTable IdentTable;
1646   encoding::Encoding Encoding;
1647   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1648   // Index (in 'Tokens') of the last token that starts a new line.
1649   unsigned FirstInLineIndex;
1650   SmallVector<FormatToken *, 16> Tokens;
1651   SmallVector<IdentifierInfo *, 8> ForEachMacros;
1652 
1653   bool FormattingDisabled;
1654 
1655   void readRawToken(FormatToken &Tok) {
1656     Lex.LexFromRawLexer(Tok.Tok);
1657     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1658                               Tok.Tok.getLength());
1659     // For formatting, treat unterminated string literals like normal string
1660     // literals.
1661     if (Tok.is(tok::unknown)) {
1662       if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1663         Tok.Tok.setKind(tok::string_literal);
1664         Tok.IsUnterminatedLiteral = true;
1665       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1666                  Tok.TokenText == "''") {
1667         Tok.Tok.setKind(tok::char_constant);
1668       }
1669     }
1670     if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format on")
1671       FormattingDisabled = false;
1672     Tok.Finalized = FormattingDisabled;
1673     if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format off")
1674       FormattingDisabled = true;
1675   }
1676 };
1677 
1678 static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1679   switch (Language) {
1680   case FormatStyle::LK_Cpp:
1681     return "C++";
1682   case FormatStyle::LK_JavaScript:
1683     return "JavaScript";
1684   case FormatStyle::LK_Proto:
1685     return "Proto";
1686   default:
1687     return "Unknown";
1688   }
1689 }
1690 
1691 class Formatter : public UnwrappedLineConsumer {
1692 public:
1693   Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1694             const std::vector<CharSourceRange> &Ranges)
1695       : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
1696         Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
1697         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1698         Encoding(encoding::detectEncoding(Lex.getBuffer())) {
1699     DEBUG(llvm::dbgs() << "File encoding: "
1700                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1701                                                                : "unknown")
1702                        << "\n");
1703     DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1704                        << "\n");
1705   }
1706 
1707   tooling::Replacements format() {
1708     tooling::Replacements Result;
1709     FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
1710 
1711     UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
1712     bool StructuralError = Parser.parse();
1713     assert(UnwrappedLines.rbegin()->empty());
1714     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1715          ++Run) {
1716       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1717       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1718       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1719         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1720       }
1721       tooling::Replacements RunResult =
1722           format(AnnotatedLines, StructuralError, Tokens);
1723       DEBUG({
1724         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1725         for (tooling::Replacements::iterator I = RunResult.begin(),
1726                                              E = RunResult.end();
1727              I != E; ++I) {
1728           llvm::dbgs() << I->toString() << "\n";
1729         }
1730       });
1731       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1732         delete AnnotatedLines[i];
1733       }
1734       Result.insert(RunResult.begin(), RunResult.end());
1735       Whitespaces.reset();
1736     }
1737     return Result;
1738   }
1739 
1740   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1741                                bool StructuralError, FormatTokenLexer &Tokens) {
1742     TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
1743     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1744       Annotator.annotate(*AnnotatedLines[i]);
1745     }
1746     deriveLocalStyle(AnnotatedLines);
1747     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1748       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1749     }
1750     computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1751 
1752     Annotator.setCommentLineLevels(AnnotatedLines);
1753     ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1754                                   BinPackInconclusiveFunctions);
1755     UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
1756     Formatter.format(AnnotatedLines, /*DryRun=*/false);
1757     return Whitespaces.generateReplacements();
1758   }
1759 
1760 private:
1761   // Determines which lines are affected by the SourceRanges given as input.
1762   // Returns \c true if at least one line between I and E or one of their
1763   // children is affected.
1764   bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1765                             SmallVectorImpl<AnnotatedLine *>::iterator E) {
1766     bool SomeLineAffected = false;
1767     const AnnotatedLine *PreviousLine = nullptr;
1768     while (I != E) {
1769       AnnotatedLine *Line = *I;
1770       Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1771 
1772       // If a line is part of a preprocessor directive, it needs to be formatted
1773       // if any token within the directive is affected.
1774       if (Line->InPPDirective) {
1775         FormatToken *Last = Line->Last;
1776         SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1777         while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1778           Last = (*PPEnd)->Last;
1779           ++PPEnd;
1780         }
1781 
1782         if (affectsTokenRange(*Line->First, *Last,
1783                               /*IncludeLeadingNewlines=*/false)) {
1784           SomeLineAffected = true;
1785           markAllAsAffected(I, PPEnd);
1786         }
1787         I = PPEnd;
1788         continue;
1789       }
1790 
1791       if (nonPPLineAffected(Line, PreviousLine))
1792         SomeLineAffected = true;
1793 
1794       PreviousLine = Line;
1795       ++I;
1796     }
1797     return SomeLineAffected;
1798   }
1799 
1800   // Determines whether 'Line' is affected by the SourceRanges given as input.
1801   // Returns \c true if line or one if its children is affected.
1802   bool nonPPLineAffected(AnnotatedLine *Line,
1803                          const AnnotatedLine *PreviousLine) {
1804     bool SomeLineAffected = false;
1805     Line->ChildrenAffected =
1806         computeAffectedLines(Line->Children.begin(), Line->Children.end());
1807     if (Line->ChildrenAffected)
1808       SomeLineAffected = true;
1809 
1810     // Stores whether one of the line's tokens is directly affected.
1811     bool SomeTokenAffected = false;
1812     // Stores whether we need to look at the leading newlines of the next token
1813     // in order to determine whether it was affected.
1814     bool IncludeLeadingNewlines = false;
1815 
1816     // Stores whether the first child line of any of this line's tokens is
1817     // affected.
1818     bool SomeFirstChildAffected = false;
1819 
1820     for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1821       // Determine whether 'Tok' was affected.
1822       if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1823         SomeTokenAffected = true;
1824 
1825       // Determine whether the first child of 'Tok' was affected.
1826       if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1827         SomeFirstChildAffected = true;
1828 
1829       IncludeLeadingNewlines = Tok->Children.empty();
1830     }
1831 
1832     // Was this line moved, i.e. has it previously been on the same line as an
1833     // affected line?
1834     bool LineMoved = PreviousLine && PreviousLine->Affected &&
1835                      Line->First->NewlinesBefore == 0;
1836 
1837     bool IsContinuedComment =
1838         Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1839         Line->First->NewlinesBefore < 2 && PreviousLine &&
1840         PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
1841 
1842     if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1843         IsContinuedComment) {
1844       Line->Affected = true;
1845       SomeLineAffected = true;
1846     }
1847     return SomeLineAffected;
1848   }
1849 
1850   // Marks all lines between I and E as well as all their children as affected.
1851   void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1852                          SmallVectorImpl<AnnotatedLine *>::iterator E) {
1853     while (I != E) {
1854       (*I)->Affected = true;
1855       markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1856       ++I;
1857     }
1858   }
1859 
1860   // Returns true if the range from 'First' to 'Last' intersects with one of the
1861   // input ranges.
1862   bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1863                          bool IncludeLeadingNewlines) {
1864     SourceLocation Start = First.WhitespaceRange.getBegin();
1865     if (!IncludeLeadingNewlines)
1866       Start = Start.getLocWithOffset(First.LastNewlineOffset);
1867     SourceLocation End = Last.getStartOfNonWhitespace();
1868     if (Last.TokenText.size() > 0)
1869       End = End.getLocWithOffset(Last.TokenText.size() - 1);
1870     CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1871     return affectsCharSourceRange(Range);
1872   }
1873 
1874   // Returns true if one of the input ranges intersect the leading empty lines
1875   // before 'Tok'.
1876   bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1877     CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1878         Tok.WhitespaceRange.getBegin(),
1879         Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1880     return affectsCharSourceRange(EmptyLineRange);
1881   }
1882 
1883   // Returns true if 'Range' intersects with one of the input ranges.
1884   bool affectsCharSourceRange(const CharSourceRange &Range) {
1885     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1886                                                           E = Ranges.end();
1887          I != E; ++I) {
1888       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1889           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1890         return true;
1891     }
1892     return false;
1893   }
1894 
1895   static bool inputUsesCRLF(StringRef Text) {
1896     return Text.count('\r') * 2 > Text.count('\n');
1897   }
1898 
1899   void
1900   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1901     unsigned CountBoundToVariable = 0;
1902     unsigned CountBoundToType = 0;
1903     bool HasCpp03IncompatibleFormat = false;
1904     bool HasBinPackedFunction = false;
1905     bool HasOnePerLineFunction = false;
1906     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1907       if (!AnnotatedLines[i]->First->Next)
1908         continue;
1909       FormatToken *Tok = AnnotatedLines[i]->First->Next;
1910       while (Tok->Next) {
1911         if (Tok->Type == TT_PointerOrReference) {
1912           bool SpacesBefore =
1913               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1914           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1915                              Tok->Next->WhitespaceRange.getEnd();
1916           if (SpacesBefore && !SpacesAfter)
1917             ++CountBoundToVariable;
1918           else if (!SpacesBefore && SpacesAfter)
1919             ++CountBoundToType;
1920         }
1921 
1922         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1923           if (Tok->is(tok::coloncolon) &&
1924               Tok->Previous->Type == TT_TemplateOpener)
1925             HasCpp03IncompatibleFormat = true;
1926           if (Tok->Type == TT_TemplateCloser &&
1927               Tok->Previous->Type == TT_TemplateCloser)
1928             HasCpp03IncompatibleFormat = true;
1929         }
1930 
1931         if (Tok->PackingKind == PPK_BinPacked)
1932           HasBinPackedFunction = true;
1933         if (Tok->PackingKind == PPK_OnePerLine)
1934           HasOnePerLineFunction = true;
1935 
1936         Tok = Tok->Next;
1937       }
1938     }
1939     if (Style.DerivePointerAlignment) {
1940       if (CountBoundToType > CountBoundToVariable)
1941         Style.PointerAlignment = FormatStyle::PAS_Left;
1942       else if (CountBoundToType < CountBoundToVariable)
1943         Style.PointerAlignment = FormatStyle::PAS_Right;
1944     }
1945     if (Style.Standard == FormatStyle::LS_Auto) {
1946       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1947                                                   : FormatStyle::LS_Cpp03;
1948     }
1949     BinPackInconclusiveFunctions =
1950         HasBinPackedFunction || !HasOnePerLineFunction;
1951   }
1952 
1953   void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
1954     assert(!UnwrappedLines.empty());
1955     UnwrappedLines.back().push_back(TheLine);
1956   }
1957 
1958   void finishRun() override {
1959     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
1960   }
1961 
1962   FormatStyle Style;
1963   Lexer &Lex;
1964   SourceManager &SourceMgr;
1965   WhitespaceManager Whitespaces;
1966   SmallVector<CharSourceRange, 8> Ranges;
1967   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
1968 
1969   encoding::Encoding Encoding;
1970   bool BinPackInconclusiveFunctions;
1971 };
1972 
1973 } // end anonymous namespace
1974 
1975 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1976                                SourceManager &SourceMgr,
1977                                std::vector<CharSourceRange> Ranges) {
1978   if (Style.DisableFormat) {
1979     tooling::Replacements EmptyResult;
1980     return EmptyResult;
1981   }
1982 
1983   Formatter formatter(Style, Lex, SourceMgr, Ranges);
1984   return formatter.format();
1985 }
1986 
1987 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1988                                std::vector<tooling::Range> Ranges,
1989                                StringRef FileName) {
1990   FileManager Files((FileSystemOptions()));
1991   DiagnosticsEngine Diagnostics(
1992       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1993       new DiagnosticOptions);
1994   SourceManager SourceMgr(Diagnostics, Files);
1995   std::unique_ptr<llvm::MemoryBuffer> Buf =
1996       llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1997   const clang::FileEntry *Entry =
1998       Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1999   SourceMgr.overrideFileContents(Entry, std::move(Buf));
2000   FileID ID =
2001       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
2002   Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
2003             getFormattingLangOpts(Style.Standard));
2004   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2005   std::vector<CharSourceRange> CharRanges;
2006   for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
2007     SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
2008     SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
2009     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2010   }
2011   return reformat(Style, Lex, SourceMgr, CharRanges);
2012 }
2013 
2014 LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
2015   LangOptions LangOpts;
2016   LangOpts.CPlusPlus = 1;
2017   LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2018   LangOpts.CPlusPlus14 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2019   LangOpts.LineComment = 1;
2020   LangOpts.CXXOperatorNames = 1;
2021   LangOpts.Bool = 1;
2022   LangOpts.ObjC1 = 1;
2023   LangOpts.ObjC2 = 1;
2024   return LangOpts;
2025 }
2026 
2027 const char *StyleOptionHelpDescription =
2028     "Coding style, currently supports:\n"
2029     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
2030     "Use -style=file to load style configuration from\n"
2031     ".clang-format file located in one of the parent\n"
2032     "directories of the source file (or current\n"
2033     "directory for stdin).\n"
2034     "Use -style=\"{key: value, ...}\" to set specific\n"
2035     "parameters, e.g.:\n"
2036     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2037 
2038 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
2039   if (FileName.endswith_lower(".js")) {
2040     return FormatStyle::LK_JavaScript;
2041   } else if (FileName.endswith_lower(".proto") ||
2042              FileName.endswith_lower(".protodevel")) {
2043     return FormatStyle::LK_Proto;
2044   }
2045   return FormatStyle::LK_Cpp;
2046 }
2047 
2048 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2049                      StringRef FallbackStyle) {
2050   FormatStyle Style = getLLVMStyle();
2051   Style.Language = getLanguageByFileName(FileName);
2052   if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
2053     llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2054                  << "\" using LLVM style\n";
2055     return Style;
2056   }
2057 
2058   if (StyleName.startswith("{")) {
2059     // Parse YAML/JSON style from the command line.
2060     if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
2061       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2062                    << FallbackStyle << " style\n";
2063     }
2064     return Style;
2065   }
2066 
2067   if (!StyleName.equals_lower("file")) {
2068     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
2069       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2070                    << " style\n";
2071     return Style;
2072   }
2073 
2074   // Look for .clang-format/_clang-format file in the file's parent directories.
2075   SmallString<128> UnsuitableConfigFiles;
2076   SmallString<128> Path(FileName);
2077   llvm::sys::fs::make_absolute(Path);
2078   for (StringRef Directory = Path; !Directory.empty();
2079        Directory = llvm::sys::path::parent_path(Directory)) {
2080     if (!llvm::sys::fs::is_directory(Directory))
2081       continue;
2082     SmallString<128> ConfigFile(Directory);
2083 
2084     llvm::sys::path::append(ConfigFile, ".clang-format");
2085     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2086     bool IsFile = false;
2087     // Ignore errors from is_regular_file: we only need to know if we can read
2088     // the file or not.
2089     llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2090 
2091     if (!IsFile) {
2092       // Try _clang-format too, since dotfiles are not commonly used on Windows.
2093       ConfigFile = Directory;
2094       llvm::sys::path::append(ConfigFile, "_clang-format");
2095       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2096       llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2097     }
2098 
2099     if (IsFile) {
2100       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2101           llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2102       if (std::error_code EC = Text.getError()) {
2103         llvm::errs() << EC.message() << "\n";
2104         break;
2105       }
2106       if (std::error_code ec =
2107               parseConfiguration(Text.get()->getBuffer(), &Style)) {
2108         if (ec == ParseError::Unsuitable) {
2109           if (!UnsuitableConfigFiles.empty())
2110             UnsuitableConfigFiles.append(", ");
2111           UnsuitableConfigFiles.append(ConfigFile);
2112           continue;
2113         }
2114         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2115                      << "\n";
2116         break;
2117       }
2118       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2119       return Style;
2120     }
2121   }
2122   llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2123                << " style\n";
2124   if (!UnsuitableConfigFiles.empty()) {
2125     llvm::errs() << "Configuration file(s) do(es) not support "
2126                  << getLanguageName(Style.Language) << ": "
2127                  << UnsuitableConfigFiles << "\n";
2128   }
2129   return Style;
2130 }
2131 
2132 } // namespace format
2133 } // namespace clang
2134