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 "UnwrappedLineFormatter.h"
19 #include "UnwrappedLineParser.h"
20 #include "WhitespaceManager.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Format/Format.h"
25 #include "clang/Lex/Lexer.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/YAMLTraits.h"
31 #include <queue>
32 #include <string>
33 
34 #define DEBUG_TYPE "format-formatter"
35 
36 using clang::format::FormatStyle;
37 
38 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
39 
40 namespace llvm {
41 namespace yaml {
42 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
43   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
44     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
45     IO.enumCase(Value, "Java", FormatStyle::LK_Java);
46     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
47     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
48   }
49 };
50 
51 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
52   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
53     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
54     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
55     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
56     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
57     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
58   }
59 };
60 
61 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
62   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
63     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
64     IO.enumCase(Value, "false", FormatStyle::UT_Never);
65     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
66     IO.enumCase(Value, "true", FormatStyle::UT_Always);
67     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
68   }
69 };
70 
71 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
72   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
73     IO.enumCase(Value, "None", FormatStyle::SFS_None);
74     IO.enumCase(Value, "false", FormatStyle::SFS_None);
75     IO.enumCase(Value, "All", FormatStyle::SFS_All);
76     IO.enumCase(Value, "true", FormatStyle::SFS_All);
77     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
78     IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
79   }
80 };
81 
82 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
83   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
84     IO.enumCase(Value, "All", FormatStyle::BOS_All);
85     IO.enumCase(Value, "true", FormatStyle::BOS_All);
86     IO.enumCase(Value, "None", FormatStyle::BOS_None);
87     IO.enumCase(Value, "false", FormatStyle::BOS_None);
88     IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
89   }
90 };
91 
92 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
93   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
94     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
95     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
96     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
97     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
98     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
99   }
100 };
101 
102 template <>
103 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
104   static void enumeration(IO &IO,
105                           FormatStyle::NamespaceIndentationKind &Value) {
106     IO.enumCase(Value, "None", FormatStyle::NI_None);
107     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
108     IO.enumCase(Value, "All", FormatStyle::NI_All);
109   }
110 };
111 
112 template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
113   static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
114     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
115     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
116     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
117 
118     // For backward compatibility.
119     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
120     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
121   }
122 };
123 
124 template <>
125 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
126   static void enumeration(IO &IO,
127                           FormatStyle::SpaceBeforeParensOptions &Value) {
128     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
129     IO.enumCase(Value, "ControlStatements",
130                 FormatStyle::SBPO_ControlStatements);
131     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
132 
133     // For backward compatibility.
134     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
135     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
136   }
137 };
138 
139 template <> struct MappingTraits<FormatStyle> {
140   static void mapping(IO &IO, FormatStyle &Style) {
141     // When reading, read the language first, we need it for getPredefinedStyle.
142     IO.mapOptional("Language", Style.Language);
143 
144     if (IO.outputting()) {
145       StringRef StylesArray[] = {"LLVM",    "Google", "Chromium",
146                                  "Mozilla", "WebKit", "GNU"};
147       ArrayRef<StringRef> Styles(StylesArray);
148       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
149         StringRef StyleName(Styles[i]);
150         FormatStyle PredefinedStyle;
151         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
152             Style == PredefinedStyle) {
153           IO.mapOptional("# BasedOnStyle", StyleName);
154           break;
155         }
156       }
157     } else {
158       StringRef BasedOnStyle;
159       IO.mapOptional("BasedOnStyle", BasedOnStyle);
160       if (!BasedOnStyle.empty()) {
161         FormatStyle::LanguageKind OldLanguage = Style.Language;
162         FormatStyle::LanguageKind Language =
163             ((FormatStyle *)IO.getContext())->Language;
164         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
165           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
166           return;
167         }
168         Style.Language = OldLanguage;
169       }
170     }
171 
172     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
173     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
174     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
175     IO.mapOptional("AlignOperands", Style.AlignOperands);
176     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
177     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
178                    Style.AllowAllParametersOfDeclarationOnNextLine);
179     IO.mapOptional("AllowShortBlocksOnASingleLine",
180                    Style.AllowShortBlocksOnASingleLine);
181     IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
182                    Style.AllowShortCaseLabelsOnASingleLine);
183     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
184                    Style.AllowShortIfStatementsOnASingleLine);
185     IO.mapOptional("AllowShortLoopsOnASingleLine",
186                    Style.AllowShortLoopsOnASingleLine);
187     IO.mapOptional("AllowShortFunctionsOnASingleLine",
188                    Style.AllowShortFunctionsOnASingleLine);
189     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
190                    Style.AlwaysBreakAfterDefinitionReturnType);
191     IO.mapOptional("AlwaysBreakTemplateDeclarations",
192                    Style.AlwaysBreakTemplateDeclarations);
193     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
194                    Style.AlwaysBreakBeforeMultilineStrings);
195     IO.mapOptional("BreakBeforeBinaryOperators",
196                    Style.BreakBeforeBinaryOperators);
197     IO.mapOptional("BreakBeforeTernaryOperators",
198                    Style.BreakBeforeTernaryOperators);
199     IO.mapOptional("BreakConstructorInitializersBeforeComma",
200                    Style.BreakConstructorInitializersBeforeComma);
201     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
202     IO.mapOptional("BinPackArguments", Style.BinPackArguments);
203     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
204     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
205                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
206     IO.mapOptional("ConstructorInitializerIndentWidth",
207                    Style.ConstructorInitializerIndentWidth);
208     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
209     IO.mapOptional("ExperimentalAutoDetectBinPacking",
210                    Style.ExperimentalAutoDetectBinPacking);
211     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
212     IO.mapOptional("IndentWrappedFunctionNames",
213                    Style.IndentWrappedFunctionNames);
214     IO.mapOptional("IndentFunctionDeclarationAfterType",
215                    Style.IndentWrappedFunctionNames);
216     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
217     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
218                    Style.KeepEmptyLinesAtTheStartOfBlocks);
219     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
220     IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
221     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
222     IO.mapOptional("ObjCSpaceBeforeProtocolList",
223                    Style.ObjCSpaceBeforeProtocolList);
224     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
225                    Style.PenaltyBreakBeforeFirstCallParameter);
226     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
227     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
228     IO.mapOptional("PenaltyBreakFirstLessLess",
229                    Style.PenaltyBreakFirstLessLess);
230     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
231     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
232                    Style.PenaltyReturnTypeOnItsOwnLine);
233     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
234     IO.mapOptional("SpacesBeforeTrailingComments",
235                    Style.SpacesBeforeTrailingComments);
236     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
237     IO.mapOptional("Standard", Style.Standard);
238     IO.mapOptional("IndentWidth", Style.IndentWidth);
239     IO.mapOptional("TabWidth", Style.TabWidth);
240     IO.mapOptional("UseTab", Style.UseTab);
241     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
242     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
243     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
244     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
245     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
246     IO.mapOptional("SpacesInCStyleCastParentheses",
247                    Style.SpacesInCStyleCastParentheses);
248     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
249     IO.mapOptional("SpacesInContainerLiterals",
250                    Style.SpacesInContainerLiterals);
251     IO.mapOptional("SpaceBeforeAssignmentOperators",
252                    Style.SpaceBeforeAssignmentOperators);
253     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
254     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
255     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
256 
257     // For backward compatibility.
258     if (!IO.outputting()) {
259       IO.mapOptional("SpaceAfterControlStatementKeyword",
260                      Style.SpaceBeforeParens);
261       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
262       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
263     }
264     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
265     IO.mapOptional("DisableFormat", Style.DisableFormat);
266   }
267 };
268 
269 // Allows to read vector<FormatStyle> while keeping default values.
270 // IO.getContext() should contain a pointer to the FormatStyle structure, that
271 // will be used to get default values for missing keys.
272 // If the first element has no Language specified, it will be treated as the
273 // default one for the following elements.
274 template <> struct DocumentListTraits<std::vector<FormatStyle>> {
275   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
276     return Seq.size();
277   }
278   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
279                               size_t Index) {
280     if (Index >= Seq.size()) {
281       assert(Index == Seq.size());
282       FormatStyle Template;
283       if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
284         Template = Seq[0];
285       } else {
286         Template = *((const FormatStyle *)IO.getContext());
287         Template.Language = FormatStyle::LK_None;
288       }
289       Seq.resize(Index + 1, Template);
290     }
291     return Seq[Index];
292   }
293 };
294 }
295 }
296 
297 namespace clang {
298 namespace format {
299 
300 const std::error_category &getParseCategory() {
301   static ParseErrorCategory C;
302   return C;
303 }
304 std::error_code make_error_code(ParseError e) {
305   return std::error_code(static_cast<int>(e), getParseCategory());
306 }
307 
308 const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
309   return "clang-format.parse_error";
310 }
311 
312 std::string ParseErrorCategory::message(int EV) const {
313   switch (static_cast<ParseError>(EV)) {
314   case ParseError::Success:
315     return "Success";
316   case ParseError::Error:
317     return "Invalid argument";
318   case ParseError::Unsuitable:
319     return "Unsuitable";
320   }
321   llvm_unreachable("unexpected parse error");
322 }
323 
324 FormatStyle getLLVMStyle() {
325   FormatStyle LLVMStyle;
326   LLVMStyle.Language = FormatStyle::LK_Cpp;
327   LLVMStyle.AccessModifierOffset = -2;
328   LLVMStyle.AlignEscapedNewlinesLeft = false;
329   LLVMStyle.AlignAfterOpenBracket = true;
330   LLVMStyle.AlignOperands = true;
331   LLVMStyle.AlignTrailingComments = true;
332   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
333   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
334   LLVMStyle.AllowShortBlocksOnASingleLine = false;
335   LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
336   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
337   LLVMStyle.AllowShortLoopsOnASingleLine = false;
338   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
339   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
340   LLVMStyle.AlwaysBreakTemplateDeclarations = false;
341   LLVMStyle.BinPackParameters = true;
342   LLVMStyle.BinPackArguments = true;
343   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
344   LLVMStyle.BreakBeforeTernaryOperators = true;
345   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
346   LLVMStyle.BreakConstructorInitializersBeforeComma = false;
347   LLVMStyle.ColumnLimit = 80;
348   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
349   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
350   LLVMStyle.ConstructorInitializerIndentWidth = 4;
351   LLVMStyle.ContinuationIndentWidth = 4;
352   LLVMStyle.Cpp11BracedListStyle = true;
353   LLVMStyle.DerivePointerAlignment = false;
354   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
355   LLVMStyle.ForEachMacros.push_back("foreach");
356   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
357   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
358   LLVMStyle.IndentCaseLabels = false;
359   LLVMStyle.IndentWrappedFunctionNames = false;
360   LLVMStyle.IndentWidth = 2;
361   LLVMStyle.TabWidth = 8;
362   LLVMStyle.MaxEmptyLinesToKeep = 1;
363   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
364   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
365   LLVMStyle.ObjCBlockIndentWidth = 2;
366   LLVMStyle.ObjCSpaceAfterProperty = false;
367   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
368   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
369   LLVMStyle.SpacesBeforeTrailingComments = 1;
370   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
371   LLVMStyle.UseTab = FormatStyle::UT_Never;
372   LLVMStyle.SpacesInParentheses = false;
373   LLVMStyle.SpacesInSquareBrackets = false;
374   LLVMStyle.SpaceInEmptyParentheses = false;
375   LLVMStyle.SpacesInContainerLiterals = true;
376   LLVMStyle.SpacesInCStyleCastParentheses = false;
377   LLVMStyle.SpaceAfterCStyleCast = false;
378   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
379   LLVMStyle.SpaceBeforeAssignmentOperators = true;
380   LLVMStyle.SpacesInAngles = false;
381 
382   LLVMStyle.PenaltyBreakComment = 300;
383   LLVMStyle.PenaltyBreakFirstLessLess = 120;
384   LLVMStyle.PenaltyBreakString = 1000;
385   LLVMStyle.PenaltyExcessCharacter = 1000000;
386   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
387   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
388 
389   LLVMStyle.DisableFormat = false;
390 
391   return LLVMStyle;
392 }
393 
394 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
395   FormatStyle GoogleStyle = getLLVMStyle();
396   GoogleStyle.Language = Language;
397 
398   GoogleStyle.AccessModifierOffset = -1;
399   GoogleStyle.AlignEscapedNewlinesLeft = true;
400   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
401   GoogleStyle.AllowShortLoopsOnASingleLine = true;
402   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
403   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
404   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
405   GoogleStyle.DerivePointerAlignment = true;
406   GoogleStyle.IndentCaseLabels = true;
407   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
408   GoogleStyle.ObjCSpaceAfterProperty = false;
409   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
410   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
411   GoogleStyle.SpacesBeforeTrailingComments = 2;
412   GoogleStyle.Standard = FormatStyle::LS_Auto;
413 
414   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
415   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
416 
417   if (Language == FormatStyle::LK_Java) {
418     GoogleStyle.AlignAfterOpenBracket = false;
419     GoogleStyle.AlignOperands = false;
420     GoogleStyle.AlignTrailingComments = false;
421     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
422     GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
423     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
424     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
425     GoogleStyle.ColumnLimit = 100;
426     GoogleStyle.SpaceAfterCStyleCast = true;
427     GoogleStyle.SpacesBeforeTrailingComments = 1;
428   } else if (Language == FormatStyle::LK_JavaScript) {
429     GoogleStyle.BreakBeforeTernaryOperators = false;
430     GoogleStyle.MaxEmptyLinesToKeep = 3;
431     GoogleStyle.SpacesInContainerLiterals = false;
432     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
433     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
434   } else if (Language == FormatStyle::LK_Proto) {
435     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
436     GoogleStyle.SpacesInContainerLiterals = false;
437   }
438 
439   return GoogleStyle;
440 }
441 
442 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
443   FormatStyle ChromiumStyle = getGoogleStyle(Language);
444   if (Language == FormatStyle::LK_Java) {
445     ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
446     ChromiumStyle.IndentWidth = 4;
447     ChromiumStyle.ContinuationIndentWidth = 8;
448   } else {
449     ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
450     ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
451     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
452     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
453     ChromiumStyle.BinPackParameters = false;
454     ChromiumStyle.DerivePointerAlignment = false;
455   }
456   return ChromiumStyle;
457 }
458 
459 FormatStyle getMozillaStyle() {
460   FormatStyle MozillaStyle = getLLVMStyle();
461   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
462   MozillaStyle.Cpp11BracedListStyle = false;
463   MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
464   MozillaStyle.DerivePointerAlignment = true;
465   MozillaStyle.IndentCaseLabels = true;
466   MozillaStyle.ObjCSpaceAfterProperty = true;
467   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
468   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
469   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
470   MozillaStyle.Standard = FormatStyle::LS_Cpp03;
471   return MozillaStyle;
472 }
473 
474 FormatStyle getWebKitStyle() {
475   FormatStyle Style = getLLVMStyle();
476   Style.AccessModifierOffset = -4;
477   Style.AlignAfterOpenBracket = false;
478   Style.AlignOperands = false;
479   Style.AlignTrailingComments = false;
480   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
481   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
482   Style.BreakConstructorInitializersBeforeComma = true;
483   Style.Cpp11BracedListStyle = false;
484   Style.ColumnLimit = 0;
485   Style.IndentWidth = 4;
486   Style.NamespaceIndentation = FormatStyle::NI_Inner;
487   Style.ObjCBlockIndentWidth = 4;
488   Style.ObjCSpaceAfterProperty = true;
489   Style.PointerAlignment = FormatStyle::PAS_Left;
490   Style.Standard = FormatStyle::LS_Cpp03;
491   return Style;
492 }
493 
494 FormatStyle getGNUStyle() {
495   FormatStyle Style = getLLVMStyle();
496   Style.AlwaysBreakAfterDefinitionReturnType = true;
497   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
498   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
499   Style.BreakBeforeTernaryOperators = true;
500   Style.Cpp11BracedListStyle = false;
501   Style.ColumnLimit = 79;
502   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
503   Style.Standard = FormatStyle::LS_Cpp03;
504   return Style;
505 }
506 
507 FormatStyle getNoStyle() {
508   FormatStyle NoStyle = getLLVMStyle();
509   NoStyle.DisableFormat = true;
510   return NoStyle;
511 }
512 
513 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
514                         FormatStyle *Style) {
515   if (Name.equals_lower("llvm")) {
516     *Style = getLLVMStyle();
517   } else if (Name.equals_lower("chromium")) {
518     *Style = getChromiumStyle(Language);
519   } else if (Name.equals_lower("mozilla")) {
520     *Style = getMozillaStyle();
521   } else if (Name.equals_lower("google")) {
522     *Style = getGoogleStyle(Language);
523   } else if (Name.equals_lower("webkit")) {
524     *Style = getWebKitStyle();
525   } else if (Name.equals_lower("gnu")) {
526     *Style = getGNUStyle();
527   } else if (Name.equals_lower("none")) {
528     *Style = getNoStyle();
529   } else {
530     return false;
531   }
532 
533   Style->Language = Language;
534   return true;
535 }
536 
537 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
538   assert(Style);
539   FormatStyle::LanguageKind Language = Style->Language;
540   assert(Language != FormatStyle::LK_None);
541   if (Text.trim().empty())
542     return make_error_code(ParseError::Error);
543 
544   std::vector<FormatStyle> Styles;
545   llvm::yaml::Input Input(Text);
546   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
547   // values for the fields, keys for which are missing from the configuration.
548   // Mapping also uses the context to get the language to find the correct
549   // base style.
550   Input.setContext(Style);
551   Input >> Styles;
552   if (Input.error())
553     return Input.error();
554 
555   for (unsigned i = 0; i < Styles.size(); ++i) {
556     // Ensures that only the first configuration can skip the Language option.
557     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
558       return make_error_code(ParseError::Error);
559     // Ensure that each language is configured at most once.
560     for (unsigned j = 0; j < i; ++j) {
561       if (Styles[i].Language == Styles[j].Language) {
562         DEBUG(llvm::dbgs()
563               << "Duplicate languages in the config file on positions " << j
564               << " and " << i << "\n");
565         return make_error_code(ParseError::Error);
566       }
567     }
568   }
569   // Look for a suitable configuration starting from the end, so we can
570   // find the configuration for the specific language first, and the default
571   // configuration (which can only be at slot 0) after it.
572   for (int i = Styles.size() - 1; i >= 0; --i) {
573     if (Styles[i].Language == Language ||
574         Styles[i].Language == FormatStyle::LK_None) {
575       *Style = Styles[i];
576       Style->Language = Language;
577       return make_error_code(ParseError::Success);
578     }
579   }
580   return make_error_code(ParseError::Unsuitable);
581 }
582 
583 std::string configurationAsText(const FormatStyle &Style) {
584   std::string Text;
585   llvm::raw_string_ostream Stream(Text);
586   llvm::yaml::Output Output(Stream);
587   // We use the same mapping method for input and output, so we need a non-const
588   // reference here.
589   FormatStyle NonConstStyle = Style;
590   Output << NonConstStyle;
591   return Stream.str();
592 }
593 
594 namespace {
595 
596 class FormatTokenLexer {
597 public:
598   FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
599                    encoding::Encoding Encoding)
600       : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
601         LessStashed(false), Column(0), TrailingWhitespace(0),
602         SourceMgr(SourceMgr), ID(ID), Style(Style),
603         IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
604         Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false) {
605     Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
606                         getFormattingLangOpts(Style)));
607     Lex->SetKeepWhitespaceMode(true);
608 
609     for (const std::string &ForEachMacro : Style.ForEachMacros)
610       ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
611     std::sort(ForEachMacros.begin(), ForEachMacros.end());
612   }
613 
614   ArrayRef<FormatToken *> lex() {
615     assert(Tokens.empty());
616     assert(FirstInLineIndex == 0);
617     do {
618       Tokens.push_back(getNextToken());
619       tryMergePreviousTokens();
620       if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
621         FirstInLineIndex = Tokens.size() - 1;
622     } while (Tokens.back()->Tok.isNot(tok::eof));
623     return Tokens;
624   }
625 
626   const AdditionalKeywords &getKeywords() { return Keywords; }
627 
628 private:
629   void tryMergePreviousTokens() {
630     if (tryMerge_TMacro())
631       return;
632     if (tryMergeConflictMarkers())
633       return;
634     if (tryMergeLessLess())
635       return;
636 
637     if (Style.Language == FormatStyle::LK_JavaScript) {
638       if (tryMergeJSRegexLiteral())
639         return;
640       if (tryMergeEscapeSequence())
641         return;
642       if (tryMergeTemplateString())
643         return;
644 
645       static tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
646       static tok::TokenKind JSNotIdentity[] = {tok::exclaimequal, tok::equal};
647       static tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
648                                               tok::greaterequal};
649       static tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
650       // FIXME: We probably need to change token type to mimic operator with the
651       // correct priority.
652       if (tryMergeTokens(JSIdentity))
653         return;
654       if (tryMergeTokens(JSNotIdentity))
655         return;
656       if (tryMergeTokens(JSShiftEqual))
657         return;
658       if (tryMergeTokens(JSRightArrow))
659         return;
660     }
661   }
662 
663   bool tryMergeLessLess() {
664     // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
665     if (Tokens.size() < 3)
666       return false;
667 
668     bool FourthTokenIsLess = false;
669     if (Tokens.size() > 3)
670       FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
671 
672     auto First = Tokens.end() - 3;
673     if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
674         First[0]->isNot(tok::less) || FourthTokenIsLess)
675       return false;
676 
677     // Only merge if there currently is no whitespace between the two "<".
678     if (First[1]->WhitespaceRange.getBegin() !=
679         First[1]->WhitespaceRange.getEnd())
680       return false;
681 
682     First[0]->Tok.setKind(tok::lessless);
683     First[0]->TokenText = "<<";
684     First[0]->ColumnWidth += 1;
685     Tokens.erase(Tokens.end() - 2);
686     return true;
687   }
688 
689   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
690     if (Tokens.size() < Kinds.size())
691       return false;
692 
693     SmallVectorImpl<FormatToken *>::const_iterator First =
694         Tokens.end() - Kinds.size();
695     if (!First[0]->is(Kinds[0]))
696       return false;
697     unsigned AddLength = 0;
698     for (unsigned i = 1; i < Kinds.size(); ++i) {
699       if (!First[i]->is(Kinds[i]) ||
700           First[i]->WhitespaceRange.getBegin() !=
701               First[i]->WhitespaceRange.getEnd())
702         return false;
703       AddLength += First[i]->TokenText.size();
704     }
705     Tokens.resize(Tokens.size() - Kinds.size() + 1);
706     First[0]->TokenText = StringRef(First[0]->TokenText.data(),
707                                     First[0]->TokenText.size() + AddLength);
708     First[0]->ColumnWidth += AddLength;
709     return true;
710   }
711 
712   // Tries to merge an escape sequence, i.e. a "\\" and the following
713   // character. Use e.g. inside JavaScript regex literals.
714   bool tryMergeEscapeSequence() {
715     if (Tokens.size() < 2)
716       return false;
717     FormatToken *Previous = Tokens[Tokens.size() - 2];
718     if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
719       return false;
720     ++Previous->ColumnWidth;
721     StringRef Text = Previous->TokenText;
722     Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
723     resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
724     Tokens.resize(Tokens.size() - 1);
725     Column = Previous->OriginalColumn + Previous->ColumnWidth;
726     return true;
727   }
728 
729   // Try to determine whether the current token ends a JavaScript regex literal.
730   // We heuristically assume that this is a regex literal if we find two
731   // unescaped slashes on a line and the token before the first slash is one of
732   // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
733   // a division.
734   bool tryMergeJSRegexLiteral() {
735     if (Tokens.size() < 2)
736       return false;
737     // If a regex literal ends in "\//", this gets represented by an unknown
738     // token "\" and a comment.
739     bool MightEndWithEscapedSlash =
740         Tokens.back()->is(tok::comment) &&
741         Tokens.back()->TokenText.startswith("//") &&
742         Tokens[Tokens.size() - 2]->TokenText == "\\";
743     if (!MightEndWithEscapedSlash &&
744         (Tokens.back()->isNot(tok::slash) ||
745          (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
746           Tokens[Tokens.size() - 2]->TokenText == "\\")))
747       return false;
748     unsigned TokenCount = 0;
749     unsigned LastColumn = Tokens.back()->OriginalColumn;
750     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
751       ++TokenCount;
752       if (I[0]->is(tok::slash) && I + 1 != E &&
753           (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
754                          tok::exclaim, tok::l_square, tok::colon, tok::comma,
755                          tok::question, tok::kw_return) ||
756            I[1]->isBinaryOperator())) {
757         if (MightEndWithEscapedSlash) {
758           // This regex literal ends in '\//'. Skip past the '//' of the last
759           // token and re-start lexing from there.
760           SourceLocation Loc = Tokens.back()->Tok.getLocation();
761           resetLexer(SourceMgr.getFileOffset(Loc) + 2);
762         }
763         Tokens.resize(Tokens.size() - TokenCount);
764         Tokens.back()->Tok.setKind(tok::unknown);
765         Tokens.back()->Type = TT_RegexLiteral;
766         Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
767         return true;
768       }
769 
770       // There can't be a newline inside a regex literal.
771       if (I[0]->NewlinesBefore > 0)
772         return false;
773     }
774     return false;
775   }
776 
777   bool tryMergeTemplateString() {
778     if (Tokens.size() < 2)
779       return false;
780 
781     FormatToken *EndBacktick = Tokens.back();
782     if (!(EndBacktick->is(tok::unknown) && EndBacktick->TokenText == "`"))
783       return false;
784 
785     unsigned TokenCount = 0;
786     bool IsMultiline = false;
787     unsigned EndColumnInFirstLine = 0;
788     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
789       ++TokenCount;
790       if (I[0]->NewlinesBefore > 0 || I[0]->IsMultiline)
791         IsMultiline = true;
792 
793       // If there was a preceding template string, this must be the start of a
794       // template string, not the end.
795       if (I[0]->is(TT_TemplateString))
796         return false;
797 
798       if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
799         // Keep track of the rhs offset of the last token to wrap across lines -
800         // its the rhs offset of the first line of the template string, used to
801         // determine its width.
802         if (I[0]->IsMultiline)
803           EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
804         // If the token has newlines, the token before it (if it exists) is the
805         // rhs end of the previous line.
806         if (I[0]->NewlinesBefore > 0 && (I + 1 != E))
807           EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
808 
809         continue;
810       }
811 
812       Tokens.resize(Tokens.size() - TokenCount);
813       Tokens.back()->Type = TT_TemplateString;
814       const char *EndOffset = EndBacktick->TokenText.data() + 1;
815       Tokens.back()->TokenText =
816           StringRef(Tokens.back()->TokenText.data(),
817                     EndOffset - Tokens.back()->TokenText.data());
818       if (IsMultiline) {
819         // ColumnWidth is from backtick to last token in line.
820         // LastLineColumnWidth is 0 to backtick.
821         // x = `some content
822         //     until here`;
823         Tokens.back()->ColumnWidth =
824             EndColumnInFirstLine - Tokens.back()->OriginalColumn;
825         Tokens.back()->LastLineColumnWidth = EndBacktick->OriginalColumn;
826         Tokens.back()->IsMultiline = true;
827       } else {
828         // Token simply spans from start to end, +1 for the ` itself.
829         Tokens.back()->ColumnWidth =
830             EndBacktick->OriginalColumn - Tokens.back()->OriginalColumn + 1;
831       }
832       return true;
833     }
834     return false;
835   }
836 
837   bool tryMerge_TMacro() {
838     if (Tokens.size() < 4)
839       return false;
840     FormatToken *Last = Tokens.back();
841     if (!Last->is(tok::r_paren))
842       return false;
843 
844     FormatToken *String = Tokens[Tokens.size() - 2];
845     if (!String->is(tok::string_literal) || String->IsMultiline)
846       return false;
847 
848     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
849       return false;
850 
851     FormatToken *Macro = Tokens[Tokens.size() - 4];
852     if (Macro->TokenText != "_T")
853       return false;
854 
855     const char *Start = Macro->TokenText.data();
856     const char *End = Last->TokenText.data() + Last->TokenText.size();
857     String->TokenText = StringRef(Start, End - Start);
858     String->IsFirst = Macro->IsFirst;
859     String->LastNewlineOffset = Macro->LastNewlineOffset;
860     String->WhitespaceRange = Macro->WhitespaceRange;
861     String->OriginalColumn = Macro->OriginalColumn;
862     String->ColumnWidth = encoding::columnWidthWithTabs(
863         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
864 
865     Tokens.pop_back();
866     Tokens.pop_back();
867     Tokens.pop_back();
868     Tokens.back() = String;
869     return true;
870   }
871 
872   bool tryMergeConflictMarkers() {
873     if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
874       return false;
875 
876     // Conflict lines look like:
877     // <marker> <text from the vcs>
878     // For example:
879     // >>>>>>> /file/in/file/system at revision 1234
880     //
881     // We merge all tokens in a line that starts with a conflict marker
882     // into a single token with a special token type that the unwrapped line
883     // parser will use to correctly rebuild the underlying code.
884 
885     FileID ID;
886     // Get the position of the first token in the line.
887     unsigned FirstInLineOffset;
888     std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
889         Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
890     StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
891     // Calculate the offset of the start of the current line.
892     auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
893     if (LineOffset == StringRef::npos) {
894       LineOffset = 0;
895     } else {
896       ++LineOffset;
897     }
898 
899     auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
900     StringRef LineStart;
901     if (FirstSpace == StringRef::npos) {
902       LineStart = Buffer.substr(LineOffset);
903     } else {
904       LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
905     }
906 
907     TokenType Type = TT_Unknown;
908     if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
909       Type = TT_ConflictStart;
910     } else if (LineStart == "|||||||" || LineStart == "=======" ||
911                LineStart == "====") {
912       Type = TT_ConflictAlternative;
913     } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
914       Type = TT_ConflictEnd;
915     }
916 
917     if (Type != TT_Unknown) {
918       FormatToken *Next = Tokens.back();
919 
920       Tokens.resize(FirstInLineIndex + 1);
921       // We do not need to build a complete token here, as we will skip it
922       // during parsing anyway (as we must not touch whitespace around conflict
923       // markers).
924       Tokens.back()->Type = Type;
925       Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
926 
927       Tokens.push_back(Next);
928       return true;
929     }
930 
931     return false;
932   }
933 
934   FormatToken *getStashedToken() {
935     // Create a synthesized second '>' or '<' token.
936     Token Tok = FormatTok->Tok;
937     StringRef TokenText = FormatTok->TokenText;
938 
939     unsigned OriginalColumn = FormatTok->OriginalColumn;
940     FormatTok = new (Allocator.Allocate()) FormatToken;
941     FormatTok->Tok = Tok;
942     SourceLocation TokLocation =
943         FormatTok->Tok.getLocation().getLocWithOffset(1);
944     FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
945     FormatTok->TokenText = TokenText;
946     FormatTok->ColumnWidth = 1;
947     FormatTok->OriginalColumn = OriginalColumn;
948     return FormatTok;
949   }
950 
951   FormatToken *getNextToken() {
952     if (GreaterStashed) {
953       GreaterStashed = false;
954       return getStashedToken();
955     }
956     if (LessStashed) {
957       LessStashed = false;
958       return getStashedToken();
959     }
960 
961     FormatTok = new (Allocator.Allocate()) FormatToken;
962     readRawToken(*FormatTok);
963     SourceLocation WhitespaceStart =
964         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
965     FormatTok->IsFirst = IsFirstToken;
966     IsFirstToken = false;
967 
968     // Consume and record whitespace until we find a significant token.
969     unsigned WhitespaceLength = TrailingWhitespace;
970     while (FormatTok->Tok.is(tok::unknown)) {
971       // FIXME: This miscounts tok:unknown tokens that are not just
972       // whitespace, e.g. a '`' character.
973       for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
974         switch (FormatTok->TokenText[i]) {
975         case '\n':
976           ++FormatTok->NewlinesBefore;
977           // FIXME: This is technically incorrect, as it could also
978           // be a literal backslash at the end of the line.
979           if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
980                          (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
981                           FormatTok->TokenText[i - 2] != '\\')))
982             FormatTok->HasUnescapedNewline = true;
983           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
984           Column = 0;
985           break;
986         case '\r':
987           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
988           Column = 0;
989           break;
990         case '\f':
991         case '\v':
992           Column = 0;
993           break;
994         case ' ':
995           ++Column;
996           break;
997         case '\t':
998           Column += Style.TabWidth - Column % Style.TabWidth;
999           break;
1000         case '\\':
1001           if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1002                              FormatTok->TokenText[i + 1] != '\n'))
1003             FormatTok->Type = TT_ImplicitStringLiteral;
1004           break;
1005         default:
1006           FormatTok->Type = TT_ImplicitStringLiteral;
1007           ++Column;
1008           break;
1009         }
1010       }
1011 
1012       if (FormatTok->is(TT_ImplicitStringLiteral))
1013         break;
1014       WhitespaceLength += FormatTok->Tok.getLength();
1015 
1016       readRawToken(*FormatTok);
1017     }
1018 
1019     // In case the token starts with escaped newlines, we want to
1020     // take them into account as whitespace - this pattern is quite frequent
1021     // in macro definitions.
1022     // FIXME: Add a more explicit test.
1023     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1024            FormatTok->TokenText[1] == '\n') {
1025       ++FormatTok->NewlinesBefore;
1026       WhitespaceLength += 2;
1027       Column = 0;
1028       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1029     }
1030 
1031     FormatTok->WhitespaceRange = SourceRange(
1032         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1033 
1034     FormatTok->OriginalColumn = Column;
1035 
1036     TrailingWhitespace = 0;
1037     if (FormatTok->Tok.is(tok::comment)) {
1038       // FIXME: Add the trimmed whitespace to Column.
1039       StringRef UntrimmedText = FormatTok->TokenText;
1040       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1041       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1042     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1043       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1044       FormatTok->Tok.setIdentifierInfo(&Info);
1045       FormatTok->Tok.setKind(Info.getTokenID());
1046       if (Style.Language == FormatStyle::LK_Java &&
1047           FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1048         FormatTok->Tok.setKind(tok::identifier);
1049         FormatTok->Tok.setIdentifierInfo(nullptr);
1050       }
1051     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1052       FormatTok->Tok.setKind(tok::greater);
1053       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1054       GreaterStashed = true;
1055     } else if (FormatTok->Tok.is(tok::lessless)) {
1056       FormatTok->Tok.setKind(tok::less);
1057       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1058       LessStashed = true;
1059     }
1060 
1061     // Now FormatTok is the next non-whitespace token.
1062 
1063     StringRef Text = FormatTok->TokenText;
1064     size_t FirstNewlinePos = Text.find('\n');
1065     if (FirstNewlinePos == StringRef::npos) {
1066       // FIXME: ColumnWidth actually depends on the start column, we need to
1067       // take this into account when the token is moved.
1068       FormatTok->ColumnWidth =
1069           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1070       Column += FormatTok->ColumnWidth;
1071     } else {
1072       FormatTok->IsMultiline = true;
1073       // FIXME: ColumnWidth actually depends on the start column, we need to
1074       // take this into account when the token is moved.
1075       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1076           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1077 
1078       // The last line of the token always starts in column 0.
1079       // Thus, the length can be precomputed even in the presence of tabs.
1080       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1081           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1082           Encoding);
1083       Column = FormatTok->LastLineColumnWidth;
1084     }
1085 
1086     FormatTok->IsForEachMacro =
1087         std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1088                            FormatTok->Tok.getIdentifierInfo());
1089 
1090     return FormatTok;
1091   }
1092 
1093   FormatToken *FormatTok;
1094   bool IsFirstToken;
1095   bool GreaterStashed, LessStashed;
1096   unsigned Column;
1097   unsigned TrailingWhitespace;
1098   std::unique_ptr<Lexer> Lex;
1099   SourceManager &SourceMgr;
1100   FileID ID;
1101   FormatStyle &Style;
1102   IdentifierTable IdentTable;
1103   AdditionalKeywords Keywords;
1104   encoding::Encoding Encoding;
1105   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1106   // Index (in 'Tokens') of the last token that starts a new line.
1107   unsigned FirstInLineIndex;
1108   SmallVector<FormatToken *, 16> Tokens;
1109   SmallVector<IdentifierInfo *, 8> ForEachMacros;
1110 
1111   bool FormattingDisabled;
1112 
1113   void readRawToken(FormatToken &Tok) {
1114     Lex->LexFromRawLexer(Tok.Tok);
1115     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1116                               Tok.Tok.getLength());
1117     // For formatting, treat unterminated string literals like normal string
1118     // literals.
1119     if (Tok.is(tok::unknown)) {
1120       if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1121         Tok.Tok.setKind(tok::string_literal);
1122         Tok.IsUnterminatedLiteral = true;
1123       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1124                  Tok.TokenText == "''") {
1125         Tok.Tok.setKind(tok::char_constant);
1126       }
1127     }
1128 
1129     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1130                                  Tok.TokenText == "/* clang-format on */")) {
1131       FormattingDisabled = false;
1132     }
1133 
1134     Tok.Finalized = FormattingDisabled;
1135 
1136     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1137                                  Tok.TokenText == "/* clang-format off */")) {
1138       FormattingDisabled = true;
1139     }
1140   }
1141 
1142   void resetLexer(unsigned Offset) {
1143     StringRef Buffer = SourceMgr.getBufferData(ID);
1144     Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1145                         getFormattingLangOpts(Style), Buffer.begin(),
1146                         Buffer.begin() + Offset, Buffer.end()));
1147     Lex->SetKeepWhitespaceMode(true);
1148   }
1149 };
1150 
1151 static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1152   switch (Language) {
1153   case FormatStyle::LK_Cpp:
1154     return "C++";
1155   case FormatStyle::LK_Java:
1156     return "Java";
1157   case FormatStyle::LK_JavaScript:
1158     return "JavaScript";
1159   case FormatStyle::LK_Proto:
1160     return "Proto";
1161   default:
1162     return "Unknown";
1163   }
1164 }
1165 
1166 class Formatter : public UnwrappedLineConsumer {
1167 public:
1168   Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
1169             ArrayRef<CharSourceRange> Ranges)
1170       : Style(Style), ID(ID), SourceMgr(SourceMgr),
1171         Whitespaces(SourceMgr, Style,
1172                     inputUsesCRLF(SourceMgr.getBufferData(ID))),
1173         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1174         Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
1175     DEBUG(llvm::dbgs() << "File encoding: "
1176                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1177                                                                : "unknown")
1178                        << "\n");
1179     DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1180                        << "\n");
1181   }
1182 
1183   tooling::Replacements format() {
1184     tooling::Replacements Result;
1185     FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
1186 
1187     UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1188                                *this);
1189     bool StructuralError = Parser.parse();
1190     assert(UnwrappedLines.rbegin()->empty());
1191     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1192          ++Run) {
1193       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1194       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1195       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1196         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1197       }
1198       tooling::Replacements RunResult =
1199           format(AnnotatedLines, StructuralError, Tokens);
1200       DEBUG({
1201         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1202         for (tooling::Replacements::iterator I = RunResult.begin(),
1203                                              E = RunResult.end();
1204              I != E; ++I) {
1205           llvm::dbgs() << I->toString() << "\n";
1206         }
1207       });
1208       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1209         delete AnnotatedLines[i];
1210       }
1211       Result.insert(RunResult.begin(), RunResult.end());
1212       Whitespaces.reset();
1213     }
1214     return Result;
1215   }
1216 
1217   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1218                                bool StructuralError, FormatTokenLexer &Tokens) {
1219     TokenAnnotator Annotator(Style, Tokens.getKeywords());
1220     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1221       Annotator.annotate(*AnnotatedLines[i]);
1222     }
1223     deriveLocalStyle(AnnotatedLines);
1224     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1225       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1226     }
1227     computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1228 
1229     Annotator.setCommentLineLevels(AnnotatedLines);
1230     ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1231                                   Whitespaces, Encoding,
1232                                   BinPackInconclusiveFunctions);
1233     UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
1234                                      Tokens.getKeywords());
1235     Formatter.format(AnnotatedLines, /*DryRun=*/false);
1236     return Whitespaces.generateReplacements();
1237   }
1238 
1239 private:
1240   // Determines which lines are affected by the SourceRanges given as input.
1241   // Returns \c true if at least one line between I and E or one of their
1242   // children is affected.
1243   bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1244                             SmallVectorImpl<AnnotatedLine *>::iterator E) {
1245     bool SomeLineAffected = false;
1246     const AnnotatedLine *PreviousLine = nullptr;
1247     while (I != E) {
1248       AnnotatedLine *Line = *I;
1249       Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1250 
1251       // If a line is part of a preprocessor directive, it needs to be formatted
1252       // if any token within the directive is affected.
1253       if (Line->InPPDirective) {
1254         FormatToken *Last = Line->Last;
1255         SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1256         while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1257           Last = (*PPEnd)->Last;
1258           ++PPEnd;
1259         }
1260 
1261         if (affectsTokenRange(*Line->First, *Last,
1262                               /*IncludeLeadingNewlines=*/false)) {
1263           SomeLineAffected = true;
1264           markAllAsAffected(I, PPEnd);
1265         }
1266         I = PPEnd;
1267         continue;
1268       }
1269 
1270       if (nonPPLineAffected(Line, PreviousLine))
1271         SomeLineAffected = true;
1272 
1273       PreviousLine = Line;
1274       ++I;
1275     }
1276     return SomeLineAffected;
1277   }
1278 
1279   // Determines whether 'Line' is affected by the SourceRanges given as input.
1280   // Returns \c true if line or one if its children is affected.
1281   bool nonPPLineAffected(AnnotatedLine *Line,
1282                          const AnnotatedLine *PreviousLine) {
1283     bool SomeLineAffected = false;
1284     Line->ChildrenAffected =
1285         computeAffectedLines(Line->Children.begin(), Line->Children.end());
1286     if (Line->ChildrenAffected)
1287       SomeLineAffected = true;
1288 
1289     // Stores whether one of the line's tokens is directly affected.
1290     bool SomeTokenAffected = false;
1291     // Stores whether we need to look at the leading newlines of the next token
1292     // in order to determine whether it was affected.
1293     bool IncludeLeadingNewlines = false;
1294 
1295     // Stores whether the first child line of any of this line's tokens is
1296     // affected.
1297     bool SomeFirstChildAffected = false;
1298 
1299     for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1300       // Determine whether 'Tok' was affected.
1301       if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1302         SomeTokenAffected = true;
1303 
1304       // Determine whether the first child of 'Tok' was affected.
1305       if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1306         SomeFirstChildAffected = true;
1307 
1308       IncludeLeadingNewlines = Tok->Children.empty();
1309     }
1310 
1311     // Was this line moved, i.e. has it previously been on the same line as an
1312     // affected line?
1313     bool LineMoved = PreviousLine && PreviousLine->Affected &&
1314                      Line->First->NewlinesBefore == 0;
1315 
1316     bool IsContinuedComment =
1317         Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1318         Line->First->NewlinesBefore < 2 && PreviousLine &&
1319         PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
1320 
1321     if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1322         IsContinuedComment) {
1323       Line->Affected = true;
1324       SomeLineAffected = true;
1325     }
1326     return SomeLineAffected;
1327   }
1328 
1329   // Marks all lines between I and E as well as all their children as affected.
1330   void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1331                          SmallVectorImpl<AnnotatedLine *>::iterator E) {
1332     while (I != E) {
1333       (*I)->Affected = true;
1334       markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1335       ++I;
1336     }
1337   }
1338 
1339   // Returns true if the range from 'First' to 'Last' intersects with one of the
1340   // input ranges.
1341   bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1342                          bool IncludeLeadingNewlines) {
1343     SourceLocation Start = First.WhitespaceRange.getBegin();
1344     if (!IncludeLeadingNewlines)
1345       Start = Start.getLocWithOffset(First.LastNewlineOffset);
1346     SourceLocation End = Last.getStartOfNonWhitespace();
1347     End = End.getLocWithOffset(Last.TokenText.size());
1348     CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1349     return affectsCharSourceRange(Range);
1350   }
1351 
1352   // Returns true if one of the input ranges intersect the leading empty lines
1353   // before 'Tok'.
1354   bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1355     CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1356         Tok.WhitespaceRange.getBegin(),
1357         Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1358     return affectsCharSourceRange(EmptyLineRange);
1359   }
1360 
1361   // Returns true if 'Range' intersects with one of the input ranges.
1362   bool affectsCharSourceRange(const CharSourceRange &Range) {
1363     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1364                                                           E = Ranges.end();
1365          I != E; ++I) {
1366       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1367           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1368         return true;
1369     }
1370     return false;
1371   }
1372 
1373   static bool inputUsesCRLF(StringRef Text) {
1374     return Text.count('\r') * 2 > Text.count('\n');
1375   }
1376 
1377   void
1378   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1379     unsigned CountBoundToVariable = 0;
1380     unsigned CountBoundToType = 0;
1381     bool HasCpp03IncompatibleFormat = false;
1382     bool HasBinPackedFunction = false;
1383     bool HasOnePerLineFunction = false;
1384     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1385       if (!AnnotatedLines[i]->First->Next)
1386         continue;
1387       FormatToken *Tok = AnnotatedLines[i]->First->Next;
1388       while (Tok->Next) {
1389         if (Tok->is(TT_PointerOrReference)) {
1390           bool SpacesBefore =
1391               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1392           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1393                              Tok->Next->WhitespaceRange.getEnd();
1394           if (SpacesBefore && !SpacesAfter)
1395             ++CountBoundToVariable;
1396           else if (!SpacesBefore && SpacesAfter)
1397             ++CountBoundToType;
1398         }
1399 
1400         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1401           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1402             HasCpp03IncompatibleFormat = true;
1403           if (Tok->is(TT_TemplateCloser) &&
1404               Tok->Previous->is(TT_TemplateCloser))
1405             HasCpp03IncompatibleFormat = true;
1406         }
1407 
1408         if (Tok->PackingKind == PPK_BinPacked)
1409           HasBinPackedFunction = true;
1410         if (Tok->PackingKind == PPK_OnePerLine)
1411           HasOnePerLineFunction = true;
1412 
1413         Tok = Tok->Next;
1414       }
1415     }
1416     if (Style.DerivePointerAlignment) {
1417       if (CountBoundToType > CountBoundToVariable)
1418         Style.PointerAlignment = FormatStyle::PAS_Left;
1419       else if (CountBoundToType < CountBoundToVariable)
1420         Style.PointerAlignment = FormatStyle::PAS_Right;
1421     }
1422     if (Style.Standard == FormatStyle::LS_Auto) {
1423       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1424                                                   : FormatStyle::LS_Cpp03;
1425     }
1426     BinPackInconclusiveFunctions =
1427         HasBinPackedFunction || !HasOnePerLineFunction;
1428   }
1429 
1430   void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
1431     assert(!UnwrappedLines.empty());
1432     UnwrappedLines.back().push_back(TheLine);
1433   }
1434 
1435   void finishRun() override {
1436     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
1437   }
1438 
1439   FormatStyle Style;
1440   FileID ID;
1441   SourceManager &SourceMgr;
1442   WhitespaceManager Whitespaces;
1443   SmallVector<CharSourceRange, 8> Ranges;
1444   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
1445 
1446   encoding::Encoding Encoding;
1447   bool BinPackInconclusiveFunctions;
1448 };
1449 
1450 } // end anonymous namespace
1451 
1452 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1453                                SourceManager &SourceMgr,
1454                                ArrayRef<CharSourceRange> Ranges) {
1455   if (Style.DisableFormat)
1456     return tooling::Replacements();
1457   return reformat(Style, SourceMgr,
1458                   SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
1459 }
1460 
1461 tooling::Replacements reformat(const FormatStyle &Style,
1462                                SourceManager &SourceMgr, FileID ID,
1463                                ArrayRef<CharSourceRange> Ranges) {
1464   if (Style.DisableFormat)
1465     return tooling::Replacements();
1466   Formatter formatter(Style, SourceMgr, ID, Ranges);
1467   return formatter.format();
1468 }
1469 
1470 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1471                                ArrayRef<tooling::Range> Ranges,
1472                                StringRef FileName) {
1473   if (Style.DisableFormat)
1474     return tooling::Replacements();
1475 
1476   FileManager Files((FileSystemOptions()));
1477   DiagnosticsEngine Diagnostics(
1478       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1479       new DiagnosticOptions);
1480   SourceManager SourceMgr(Diagnostics, Files);
1481   std::unique_ptr<llvm::MemoryBuffer> Buf =
1482       llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1483   const clang::FileEntry *Entry =
1484       Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1485   SourceMgr.overrideFileContents(Entry, std::move(Buf));
1486   FileID ID =
1487       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1488   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1489   std::vector<CharSourceRange> CharRanges;
1490   for (const tooling::Range &Range : Ranges) {
1491     SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
1492     SourceLocation End = Start.getLocWithOffset(Range.getLength());
1493     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1494   }
1495   return reformat(Style, SourceMgr, ID, CharRanges);
1496 }
1497 
1498 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
1499   LangOptions LangOpts;
1500   LangOpts.CPlusPlus = 1;
1501   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1502   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1503   LangOpts.LineComment = 1;
1504   bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
1505                               Style.Language != FormatStyle::LK_Java;
1506   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
1507   LangOpts.Bool = 1;
1508   LangOpts.ObjC1 = 1;
1509   LangOpts.ObjC2 = 1;
1510   LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
1511   return LangOpts;
1512 }
1513 
1514 const char *StyleOptionHelpDescription =
1515     "Coding style, currently supports:\n"
1516     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
1517     "Use -style=file to load style configuration from\n"
1518     ".clang-format file located in one of the parent\n"
1519     "directories of the source file (or current\n"
1520     "directory for stdin).\n"
1521     "Use -style=\"{key: value, ...}\" to set specific\n"
1522     "parameters, e.g.:\n"
1523     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1524 
1525 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
1526   if (FileName.endswith(".java")) {
1527     return FormatStyle::LK_Java;
1528   } else if (FileName.endswith_lower(".js")) {
1529     return FormatStyle::LK_JavaScript;
1530   } else if (FileName.endswith_lower(".proto") ||
1531              FileName.endswith_lower(".protodevel")) {
1532     return FormatStyle::LK_Proto;
1533   }
1534   return FormatStyle::LK_Cpp;
1535 }
1536 
1537 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1538                      StringRef FallbackStyle) {
1539   FormatStyle Style = getLLVMStyle();
1540   Style.Language = getLanguageByFileName(FileName);
1541   if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
1542     llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1543                  << "\" using LLVM style\n";
1544     return Style;
1545   }
1546 
1547   if (StyleName.startswith("{")) {
1548     // Parse YAML/JSON style from the command line.
1549     if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
1550       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1551                    << FallbackStyle << " style\n";
1552     }
1553     return Style;
1554   }
1555 
1556   if (!StyleName.equals_lower("file")) {
1557     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
1558       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1559                    << " style\n";
1560     return Style;
1561   }
1562 
1563   // Look for .clang-format/_clang-format file in the file's parent directories.
1564   SmallString<128> UnsuitableConfigFiles;
1565   SmallString<128> Path(FileName);
1566   llvm::sys::fs::make_absolute(Path);
1567   for (StringRef Directory = Path; !Directory.empty();
1568        Directory = llvm::sys::path::parent_path(Directory)) {
1569     if (!llvm::sys::fs::is_directory(Directory))
1570       continue;
1571     SmallString<128> ConfigFile(Directory);
1572 
1573     llvm::sys::path::append(ConfigFile, ".clang-format");
1574     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1575     bool IsFile = false;
1576     // Ignore errors from is_regular_file: we only need to know if we can read
1577     // the file or not.
1578     llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1579 
1580     if (!IsFile) {
1581       // Try _clang-format too, since dotfiles are not commonly used on Windows.
1582       ConfigFile = Directory;
1583       llvm::sys::path::append(ConfigFile, "_clang-format");
1584       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1585       llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1586     }
1587 
1588     if (IsFile) {
1589       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1590           llvm::MemoryBuffer::getFile(ConfigFile.c_str());
1591       if (std::error_code EC = Text.getError()) {
1592         llvm::errs() << EC.message() << "\n";
1593         break;
1594       }
1595       if (std::error_code ec =
1596               parseConfiguration(Text.get()->getBuffer(), &Style)) {
1597         if (ec == ParseError::Unsuitable) {
1598           if (!UnsuitableConfigFiles.empty())
1599             UnsuitableConfigFiles.append(", ");
1600           UnsuitableConfigFiles.append(ConfigFile);
1601           continue;
1602         }
1603         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1604                      << "\n";
1605         break;
1606       }
1607       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1608       return Style;
1609     }
1610   }
1611   llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1612                << " style\n";
1613   if (!UnsuitableConfigFiles.empty()) {
1614     llvm::errs() << "Configuration file(s) do(es) not support "
1615                  << getLanguageName(Style.Language) << ": "
1616                  << UnsuitableConfigFiles << "\n";
1617   }
1618   return Style;
1619 }
1620 
1621 } // namespace format
1622 } // namespace clang
1623