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