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