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