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(SourceManager &SourceMgr,
557                          SmallVectorImpl<CharSourceRange> &Ranges,
558                          ContinuationIndenter *Indenter,
559                          WhitespaceManager *Whitespaces,
560                          const FormatStyle &Style)
561       : SourceMgr(SourceMgr), Ranges(Ranges), Indenter(Indenter),
562         Whitespaces(Whitespaces), Style(Style), Joiner(Style) {}
563 
564   unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
565                   int AdditionalIndent = 0) {
566     assert(!Lines.empty());
567     unsigned Penalty = 0;
568     std::vector<int> IndentForLevel;
569     for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
570       IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
571     bool PreviousLineWasTouched = false;
572     const AnnotatedLine *PreviousLine = NULL;
573     bool FormatPPDirective = false;
574     for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
575                                                           E = Lines.end();
576          I != E; ++I) {
577       const AnnotatedLine &TheLine = **I;
578       const FormatToken *FirstTok = TheLine.First;
579       int Offset = getIndentOffset(*FirstTok);
580 
581       // Check whether this line is part of a formatted preprocessor directive.
582       if (FirstTok->HasUnescapedNewline)
583         FormatPPDirective = false;
584       if (!FormatPPDirective && TheLine.InPPDirective &&
585           (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
586         FormatPPDirective = true;
587 
588       // Determine indent and try to merge multiple unwrapped lines.
589       while (IndentForLevel.size() <= TheLine.Level)
590         IndentForLevel.push_back(-1);
591       IndentForLevel.resize(TheLine.Level + 1);
592       unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
593       if (static_cast<int>(Indent) + Offset >= 0)
594         Indent += Offset;
595       unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
596       if (!DryRun) {
597         for (unsigned i = 0; i < MergedLines; ++i) {
598           join(*I[i], *I[i + 1]);
599         }
600       }
601       I += MergedLines;
602 
603       bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
604       if (TheLine.First->is(tok::eof)) {
605         if (PreviousLineWasTouched && !DryRun) {
606           unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
607           Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
608                                          /*IndentLevel=*/0, /*Spaces=*/0,
609                                          /*TargetColumn=*/0);
610         }
611       } else if (TheLine.Type != LT_Invalid &&
612                  (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
613         unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
614         if (FirstTok->WhitespaceRange.isValid()) {
615           if (!DryRun)
616             formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
617                              Indent, TheLine.InPPDirective);
618         } else {
619           Indent = LevelIndent = FirstTok->OriginalColumn;
620         }
621 
622         // If everything fits on a single line, just put it there.
623         unsigned ColumnLimit = Style.ColumnLimit;
624         if (I + 1 != E) {
625           AnnotatedLine *NextLine = I[1];
626           if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
627             ColumnLimit = getColumnLimit(TheLine.InPPDirective);
628         }
629 
630         if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
631           LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
632           while (State.NextToken != NULL)
633             Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
634         } else if (Style.ColumnLimit == 0) {
635           NoColumnLimitFormatter Formatter(Indenter);
636           if (!DryRun)
637             Formatter.format(Indent, &TheLine);
638         } else {
639           Penalty += format(TheLine, Indent, DryRun);
640         }
641 
642         IndentForLevel[TheLine.Level] = LevelIndent;
643         PreviousLineWasTouched = true;
644       } else {
645         // Format the first token if necessary, and notify the WhitespaceManager
646         // about the unchanged whitespace.
647         for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
648           if (Tok == TheLine.First &&
649               (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
650             unsigned LevelIndent = Tok->OriginalColumn;
651             if (!DryRun) {
652               // Remove trailing whitespace of the previous line if it was
653               // touched.
654               if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
655                 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
656                                  TheLine.InPPDirective);
657               } else {
658                 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
659               }
660             }
661 
662             if (static_cast<int>(LevelIndent) - Offset >= 0)
663               LevelIndent -= Offset;
664             if (Tok->isNot(tok::comment))
665               IndentForLevel[TheLine.Level] = LevelIndent;
666           } else if (!DryRun) {
667             Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
668           }
669         }
670         // If we did not reformat this unwrapped line, the column at the end of
671         // the last token is unchanged - thus, we can calculate the end of the
672         // last token.
673         PreviousLineWasTouched = false;
674       }
675       if (!DryRun) {
676         for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
677           Tok->Finalized = true;
678         }
679       }
680       PreviousLine = *I;
681     }
682     return Penalty;
683   }
684 
685 private:
686   /// \brief Formats an \c AnnotatedLine and returns the penalty.
687   ///
688   /// If \p DryRun is \c false, directly applies the changes.
689   unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
690                   bool DryRun) {
691     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
692 
693     // If the ObjC method declaration does not fit on a line, we should format
694     // it with one arg per line.
695     if (State.Line->Type == LT_ObjCMethodDecl)
696       State.Stack.back().BreakBeforeParameter = true;
697 
698     // Find best solution in solution space.
699     return analyzeSolutionSpace(State, DryRun);
700   }
701 
702   /// \brief An edge in the solution space from \c Previous->State to \c State,
703   /// inserting a newline dependent on the \c NewLine.
704   struct StateNode {
705     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
706         : State(State), NewLine(NewLine), Previous(Previous) {}
707     LineState State;
708     bool NewLine;
709     StateNode *Previous;
710   };
711 
712   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
713   ///
714   /// In case of equal penalties, we want to prefer states that were inserted
715   /// first. During state generation we make sure that we insert states first
716   /// that break the line as late as possible.
717   typedef std::pair<unsigned, unsigned> OrderedPenalty;
718 
719   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
720   /// \c State has the given \c OrderedPenalty.
721   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
722 
723   /// \brief The BFS queue type.
724   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
725                               std::greater<QueueItem> > QueueType;
726 
727   /// \brief Get the offset of the line relatively to the level.
728   ///
729   /// For example, 'public:' labels in classes are offset by 1 or 2
730   /// characters to the left from their level.
731   int getIndentOffset(const FormatToken &RootToken) {
732     if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
733       return Style.AccessModifierOffset;
734     return 0;
735   }
736 
737   /// \brief Add a new line and the required indent before the first Token
738   /// of the \c UnwrappedLine if there was no structural parsing error.
739   void formatFirstToken(FormatToken &RootToken,
740                         const AnnotatedLine *PreviousLine, unsigned IndentLevel,
741                         unsigned Indent, bool InPPDirective) {
742     unsigned Newlines =
743         std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
744     // Remove empty lines before "}" where applicable.
745     if (RootToken.is(tok::r_brace) &&
746         (!RootToken.Next ||
747          (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
748       Newlines = std::min(Newlines, 1u);
749     if (Newlines == 0 && !RootToken.IsFirst)
750       Newlines = 1;
751 
752     // Insert extra new line before access specifiers.
753     if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
754         RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
755       ++Newlines;
756 
757     // Remove empty lines after access specifiers.
758     if (PreviousLine && PreviousLine->First->isAccessSpecifier())
759       Newlines = std::min(1u, Newlines);
760 
761     Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
762                                    Indent, InPPDirective &&
763                                                !RootToken.HasUnescapedNewline);
764   }
765 
766   /// \brief Get the indent of \p Level from \p IndentForLevel.
767   ///
768   /// \p IndentForLevel must contain the indent for the level \c l
769   /// at \p IndentForLevel[l], or a value < 0 if the indent for
770   /// that level is unknown.
771   unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
772     if (IndentForLevel[Level] != -1)
773       return IndentForLevel[Level];
774     if (Level == 0)
775       return 0;
776     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
777   }
778 
779   void join(AnnotatedLine &A, const AnnotatedLine &B) {
780     assert(!A.Last->Next);
781     assert(!B.First->Previous);
782     A.Last->Next = B.First;
783     B.First->Previous = A.Last;
784     B.First->CanBreakBefore = true;
785     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
786     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
787       Tok->TotalLength += LengthA;
788       A.Last = Tok;
789     }
790   }
791 
792   unsigned getColumnLimit(bool InPPDirective) const {
793     // In preprocessor directives reserve two chars for trailing " \"
794     return Style.ColumnLimit - (InPPDirective ? 2 : 0);
795   }
796 
797   bool touchesRanges(const CharSourceRange &Range) {
798     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
799                                                           E = Ranges.end();
800          I != E; ++I) {
801       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
802           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
803         return true;
804     }
805     return false;
806   }
807 
808   bool touchesLine(const AnnotatedLine &TheLine) {
809     const FormatToken *First = TheLine.First;
810     const FormatToken *Last = TheLine.Last;
811     CharSourceRange LineRange = CharSourceRange::getCharRange(
812         First->WhitespaceRange.getBegin().getLocWithOffset(
813             First->LastNewlineOffset),
814         Last->getStartOfNonWhitespace().getLocWithOffset(
815             Last->TokenText.size() - 1));
816     return touchesRanges(LineRange);
817   }
818 
819   bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
820                           SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
821     for (; I != E; ++I) {
822       if ((*I)->First->HasUnescapedNewline)
823         return false;
824       if (touchesLine(**I))
825         return true;
826     }
827     return false;
828   }
829 
830   bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
831     const FormatToken *First = TheLine.First;
832     CharSourceRange LineRange = CharSourceRange::getCharRange(
833         First->WhitespaceRange.getBegin(),
834         First->WhitespaceRange.getBegin().getLocWithOffset(
835             First->LastNewlineOffset));
836     return touchesRanges(LineRange);
837   }
838 
839   /// \brief Analyze the entire solution space starting from \p InitialState.
840   ///
841   /// This implements a variant of Dijkstra's algorithm on the graph that spans
842   /// the solution space (\c LineStates are the nodes). The algorithm tries to
843   /// find the shortest path (the one with lowest penalty) from \p InitialState
844   /// to a state where all tokens are placed. Returns the penalty.
845   ///
846   /// If \p DryRun is \c false, directly applies the changes.
847   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
848     std::set<LineState> Seen;
849 
850     // Increasing count of \c StateNode items we have created. This is used to
851     // create a deterministic order independent of the container.
852     unsigned Count = 0;
853     QueueType Queue;
854 
855     // Insert start element into queue.
856     StateNode *Node =
857         new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
858     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
859     ++Count;
860 
861     unsigned Penalty = 0;
862 
863     // While not empty, take first element and follow edges.
864     while (!Queue.empty()) {
865       Penalty = Queue.top().first.first;
866       StateNode *Node = Queue.top().second;
867       if (Node->State.NextToken == NULL) {
868         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
869         break;
870       }
871       Queue.pop();
872 
873       // Cut off the analysis of certain solutions if the analysis gets too
874       // complex. See description of IgnoreStackForComparison.
875       if (Count > 10000)
876         Node->State.IgnoreStackForComparison = true;
877 
878       if (!Seen.insert(Node->State).second)
879         // State already examined with lower penalty.
880         continue;
881 
882       FormatDecision LastFormat = Node->State.NextToken->Decision;
883       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
884         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
885       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
886         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
887     }
888 
889     if (Queue.empty()) {
890       // We were unable to find a solution, do nothing.
891       // FIXME: Add diagnostic?
892       DEBUG(llvm::dbgs() << "Could not find a solution.\n");
893       return 0;
894     }
895 
896     // Reconstruct the solution.
897     if (!DryRun)
898       reconstructPath(InitialState, Queue.top().second);
899 
900     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
901     DEBUG(llvm::dbgs() << "---\n");
902 
903     return Penalty;
904   }
905 
906   void reconstructPath(LineState &State, StateNode *Current) {
907     std::deque<StateNode *> Path;
908     // We do not need a break before the initial token.
909     while (Current->Previous) {
910       Path.push_front(Current);
911       Current = Current->Previous;
912     }
913     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
914          I != E; ++I) {
915       unsigned Penalty = 0;
916       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
917       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
918 
919       DEBUG({
920         if ((*I)->NewLine) {
921           llvm::dbgs() << "Penalty for placing "
922                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
923                        << Penalty << "\n";
924         }
925       });
926     }
927   }
928 
929   /// \brief Add the following state to the analysis queue \c Queue.
930   ///
931   /// Assume the current state is \p PreviousNode and has been reached with a
932   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
933   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
934                            bool NewLine, unsigned *Count, QueueType *Queue) {
935     if (NewLine && !Indenter->canBreak(PreviousNode->State))
936       return;
937     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
938       return;
939 
940     StateNode *Node = new (Allocator.Allocate())
941         StateNode(PreviousNode->State, NewLine, PreviousNode);
942     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
943       return;
944 
945     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
946 
947     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
948     ++(*Count);
949   }
950 
951   /// \brief If the \p State's next token is an r_brace closing a nested block,
952   /// format the nested block before it.
953   ///
954   /// Returns \c true if all children could be placed successfully and adapts
955   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
956   /// creates changes using \c Whitespaces.
957   ///
958   /// The crucial idea here is that children always get formatted upon
959   /// encountering the closing brace right after the nested block. Now, if we
960   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
961   /// \c false), the entire block has to be kept on the same line (which is only
962   /// possible if it fits on the line, only contains a single statement, etc.
963   ///
964   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
965   /// break after the "{", format all lines with correct indentation and the put
966   /// the closing "}" on yet another new line.
967   ///
968   /// This enables us to keep the simple structure of the
969   /// \c UnwrappedLineFormatter, where we only have two options for each token:
970   /// break or don't break.
971   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
972                       unsigned &Penalty) {
973     FormatToken &Previous = *State.NextToken->Previous;
974     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
975     if (!LBrace || LBrace->isNot(tok::l_brace) ||
976         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
977       // The previous token does not open a block. Nothing to do. We don't
978       // assert so that we can simply call this function for all tokens.
979       return true;
980 
981     if (NewLine) {
982       int AdditionalIndent = State.Stack.back().Indent -
983                              Previous.Children[0]->Level * Style.IndentWidth;
984       Penalty += format(Previous.Children, DryRun, AdditionalIndent);
985       return true;
986     }
987 
988     // Cannot merge multiple statements into a single line.
989     if (Previous.Children.size() > 1)
990       return false;
991 
992     // We can't put the closing "}" on a line with a trailing comment.
993     if (Previous.Children[0]->Last->isTrailingComment())
994       return false;
995 
996     if (!DryRun) {
997       Whitespaces->replaceWhitespace(
998           *Previous.Children[0]->First,
999           /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
1000           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
1001     }
1002     Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
1003 
1004     State.Column += 1 + Previous.Children[0]->Last->TotalLength;
1005     return true;
1006   }
1007 
1008   SourceManager &SourceMgr;
1009   SmallVectorImpl<CharSourceRange> &Ranges;
1010   ContinuationIndenter *Indenter;
1011   WhitespaceManager *Whitespaces;
1012   FormatStyle Style;
1013   LineJoiner Joiner;
1014 
1015   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1016 };
1017 
1018 class FormatTokenLexer {
1019 public:
1020   FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
1021                    encoding::Encoding Encoding)
1022       : FormatTok(NULL), IsFirstToken(true), GreaterStashed(false), Column(0),
1023         TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
1024         IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
1025     Lex.SetKeepWhitespaceMode(true);
1026   }
1027 
1028   ArrayRef<FormatToken *> lex() {
1029     assert(Tokens.empty());
1030     do {
1031       Tokens.push_back(getNextToken());
1032       maybeJoinPreviousTokens();
1033     } while (Tokens.back()->Tok.isNot(tok::eof));
1034     return Tokens;
1035   }
1036 
1037   IdentifierTable &getIdentTable() { return IdentTable; }
1038 
1039 private:
1040   void maybeJoinPreviousTokens() {
1041     if (Tokens.size() < 4)
1042       return;
1043     FormatToken *Last = Tokens.back();
1044     if (!Last->is(tok::r_paren))
1045       return;
1046 
1047     FormatToken *String = Tokens[Tokens.size() - 2];
1048     if (!String->is(tok::string_literal) || String->IsMultiline)
1049       return;
1050 
1051     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1052       return;
1053 
1054     FormatToken *Macro = Tokens[Tokens.size() - 4];
1055     if (Macro->TokenText != "_T")
1056       return;
1057 
1058     const char *Start = Macro->TokenText.data();
1059     const char *End = Last->TokenText.data() + Last->TokenText.size();
1060     String->TokenText = StringRef(Start, End - Start);
1061     String->IsFirst = Macro->IsFirst;
1062     String->LastNewlineOffset = Macro->LastNewlineOffset;
1063     String->WhitespaceRange = Macro->WhitespaceRange;
1064     String->OriginalColumn = Macro->OriginalColumn;
1065     String->ColumnWidth = encoding::columnWidthWithTabs(
1066         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1067 
1068     Tokens.pop_back();
1069     Tokens.pop_back();
1070     Tokens.pop_back();
1071     Tokens.back() = String;
1072   }
1073 
1074   FormatToken *getNextToken() {
1075     if (GreaterStashed) {
1076       // Create a synthesized second '>' token.
1077       // FIXME: Increment Column and set OriginalColumn.
1078       Token Greater = FormatTok->Tok;
1079       FormatTok = new (Allocator.Allocate()) FormatToken;
1080       FormatTok->Tok = Greater;
1081       SourceLocation GreaterLocation =
1082           FormatTok->Tok.getLocation().getLocWithOffset(1);
1083       FormatTok->WhitespaceRange =
1084           SourceRange(GreaterLocation, GreaterLocation);
1085       FormatTok->TokenText = ">";
1086       FormatTok->ColumnWidth = 1;
1087       GreaterStashed = false;
1088       return FormatTok;
1089     }
1090 
1091     FormatTok = new (Allocator.Allocate()) FormatToken;
1092     readRawToken(*FormatTok);
1093     SourceLocation WhitespaceStart =
1094         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1095     FormatTok->IsFirst = IsFirstToken;
1096     IsFirstToken = false;
1097 
1098     // Consume and record whitespace until we find a significant token.
1099     unsigned WhitespaceLength = TrailingWhitespace;
1100     while (FormatTok->Tok.is(tok::unknown)) {
1101       for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1102         switch (FormatTok->TokenText[i]) {
1103         case '\n':
1104           ++FormatTok->NewlinesBefore;
1105           // FIXME: This is technically incorrect, as it could also
1106           // be a literal backslash at the end of the line.
1107           if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1108                          (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1109                           FormatTok->TokenText[i - 2] != '\\')))
1110             FormatTok->HasUnescapedNewline = true;
1111           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1112           Column = 0;
1113           break;
1114         case '\r':
1115         case '\f':
1116         case '\v':
1117           Column = 0;
1118           break;
1119         case ' ':
1120           ++Column;
1121           break;
1122         case '\t':
1123           Column += Style.TabWidth - Column % Style.TabWidth;
1124           break;
1125         case '\\':
1126           ++Column;
1127           if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1128                              FormatTok->TokenText[i + 1] != '\n'))
1129             FormatTok->Type = TT_ImplicitStringLiteral;
1130           break;
1131         default:
1132           FormatTok->Type = TT_ImplicitStringLiteral;
1133           ++Column;
1134           break;
1135         }
1136       }
1137 
1138       if (FormatTok->Type == TT_ImplicitStringLiteral)
1139         break;
1140       WhitespaceLength += FormatTok->Tok.getLength();
1141 
1142       readRawToken(*FormatTok);
1143     }
1144 
1145     // In case the token starts with escaped newlines, we want to
1146     // take them into account as whitespace - this pattern is quite frequent
1147     // in macro definitions.
1148     // FIXME: Add a more explicit test.
1149     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1150            FormatTok->TokenText[1] == '\n') {
1151       // FIXME: ++FormatTok->NewlinesBefore is missing...
1152       WhitespaceLength += 2;
1153       Column = 0;
1154       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1155     }
1156 
1157     FormatTok->WhitespaceRange = SourceRange(
1158         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1159 
1160     FormatTok->OriginalColumn = Column;
1161 
1162     TrailingWhitespace = 0;
1163     if (FormatTok->Tok.is(tok::comment)) {
1164       // FIXME: Add the trimmed whitespace to Column.
1165       StringRef UntrimmedText = FormatTok->TokenText;
1166       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1167       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1168     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1169       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1170       FormatTok->Tok.setIdentifierInfo(&Info);
1171       FormatTok->Tok.setKind(Info.getTokenID());
1172     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1173       FormatTok->Tok.setKind(tok::greater);
1174       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1175       GreaterStashed = true;
1176     }
1177 
1178     // Now FormatTok is the next non-whitespace token.
1179 
1180     StringRef Text = FormatTok->TokenText;
1181     size_t FirstNewlinePos = Text.find('\n');
1182     if (FirstNewlinePos == StringRef::npos) {
1183       // FIXME: ColumnWidth actually depends on the start column, we need to
1184       // take this into account when the token is moved.
1185       FormatTok->ColumnWidth =
1186           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1187       Column += FormatTok->ColumnWidth;
1188     } else {
1189       FormatTok->IsMultiline = true;
1190       // FIXME: ColumnWidth actually depends on the start column, we need to
1191       // take this into account when the token is moved.
1192       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1193           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1194 
1195       // The last line of the token always starts in column 0.
1196       // Thus, the length can be precomputed even in the presence of tabs.
1197       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1198           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1199           Encoding);
1200       Column = FormatTok->LastLineColumnWidth;
1201     }
1202 
1203     return FormatTok;
1204   }
1205 
1206   FormatToken *FormatTok;
1207   bool IsFirstToken;
1208   bool GreaterStashed;
1209   unsigned Column;
1210   unsigned TrailingWhitespace;
1211   Lexer &Lex;
1212   SourceManager &SourceMgr;
1213   FormatStyle &Style;
1214   IdentifierTable IdentTable;
1215   encoding::Encoding Encoding;
1216   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1217   SmallVector<FormatToken *, 16> Tokens;
1218 
1219   void readRawToken(FormatToken &Tok) {
1220     Lex.LexFromRawLexer(Tok.Tok);
1221     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1222                               Tok.Tok.getLength());
1223     // For formatting, treat unterminated string literals like normal string
1224     // literals.
1225     if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1226         Tok.TokenText[0] == '"') {
1227       Tok.Tok.setKind(tok::string_literal);
1228       Tok.IsUnterminatedLiteral = true;
1229     }
1230   }
1231 };
1232 
1233 class Formatter : public UnwrappedLineConsumer {
1234 public:
1235   Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1236             const std::vector<CharSourceRange> &Ranges)
1237       : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
1238         Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
1239         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1240         Encoding(encoding::detectEncoding(Lex.getBuffer())) {
1241     DEBUG(llvm::dbgs() << "File encoding: "
1242                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1243                                                                : "unknown")
1244                        << "\n");
1245   }
1246 
1247   tooling::Replacements format() {
1248     tooling::Replacements Result;
1249     FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
1250 
1251     UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
1252     bool StructuralError = Parser.parse();
1253     assert(UnwrappedLines.rbegin()->empty());
1254     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1255          ++Run) {
1256       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1257       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1258       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1259         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1260       }
1261       tooling::Replacements RunResult =
1262           format(AnnotatedLines, StructuralError, Tokens);
1263       DEBUG({
1264         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1265         for (tooling::Replacements::iterator I = RunResult.begin(),
1266                                              E = RunResult.end();
1267              I != E; ++I) {
1268           llvm::dbgs() << I->toString() << "\n";
1269         }
1270       });
1271       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1272         delete AnnotatedLines[i];
1273       }
1274       Result.insert(RunResult.begin(), RunResult.end());
1275       Whitespaces.reset();
1276     }
1277     return Result;
1278   }
1279 
1280   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1281                                bool StructuralError, FormatTokenLexer &Tokens) {
1282     TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
1283     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1284       Annotator.annotate(*AnnotatedLines[i]);
1285     }
1286     deriveLocalStyle(AnnotatedLines);
1287     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1288       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1289     }
1290 
1291     Annotator.setCommentLineLevels(AnnotatedLines);
1292     ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1293                                   BinPackInconclusiveFunctions);
1294     UnwrappedLineFormatter Formatter(SourceMgr, Ranges, &Indenter, &Whitespaces,
1295                                      Style);
1296     Formatter.format(AnnotatedLines, /*DryRun=*/false);
1297     return Whitespaces.generateReplacements();
1298   }
1299 
1300 private:
1301   static bool inputUsesCRLF(StringRef Text) {
1302     return Text.count('\r') * 2 > Text.count('\n');
1303   }
1304 
1305   void
1306   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1307     unsigned CountBoundToVariable = 0;
1308     unsigned CountBoundToType = 0;
1309     bool HasCpp03IncompatibleFormat = false;
1310     bool HasBinPackedFunction = false;
1311     bool HasOnePerLineFunction = false;
1312     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1313       if (!AnnotatedLines[i]->First->Next)
1314         continue;
1315       FormatToken *Tok = AnnotatedLines[i]->First->Next;
1316       while (Tok->Next) {
1317         if (Tok->Type == TT_PointerOrReference) {
1318           bool SpacesBefore =
1319               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1320           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1321                              Tok->Next->WhitespaceRange.getEnd();
1322           if (SpacesBefore && !SpacesAfter)
1323             ++CountBoundToVariable;
1324           else if (!SpacesBefore && SpacesAfter)
1325             ++CountBoundToType;
1326         }
1327 
1328         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1329           if (Tok->is(tok::coloncolon) &&
1330               Tok->Previous->Type == TT_TemplateOpener)
1331             HasCpp03IncompatibleFormat = true;
1332           if (Tok->Type == TT_TemplateCloser &&
1333               Tok->Previous->Type == TT_TemplateCloser)
1334             HasCpp03IncompatibleFormat = true;
1335         }
1336 
1337         if (Tok->PackingKind == PPK_BinPacked)
1338           HasBinPackedFunction = true;
1339         if (Tok->PackingKind == PPK_OnePerLine)
1340           HasOnePerLineFunction = true;
1341 
1342         Tok = Tok->Next;
1343       }
1344     }
1345     if (Style.DerivePointerBinding) {
1346       if (CountBoundToType > CountBoundToVariable)
1347         Style.PointerBindsToType = true;
1348       else if (CountBoundToType < CountBoundToVariable)
1349         Style.PointerBindsToType = false;
1350     }
1351     if (Style.Standard == FormatStyle::LS_Auto) {
1352       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1353                                                   : FormatStyle::LS_Cpp03;
1354     }
1355     BinPackInconclusiveFunctions =
1356         HasBinPackedFunction || !HasOnePerLineFunction;
1357   }
1358 
1359   virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1360     assert(!UnwrappedLines.empty());
1361     UnwrappedLines.back().push_back(TheLine);
1362   }
1363 
1364   virtual void finishRun() {
1365     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
1366   }
1367 
1368   FormatStyle Style;
1369   Lexer &Lex;
1370   SourceManager &SourceMgr;
1371   WhitespaceManager Whitespaces;
1372   SmallVector<CharSourceRange, 8> Ranges;
1373   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
1374 
1375   encoding::Encoding Encoding;
1376   bool BinPackInconclusiveFunctions;
1377 };
1378 
1379 } // end anonymous namespace
1380 
1381 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1382                                SourceManager &SourceMgr,
1383                                std::vector<CharSourceRange> Ranges) {
1384   Formatter formatter(Style, Lex, SourceMgr, Ranges);
1385   return formatter.format();
1386 }
1387 
1388 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1389                                std::vector<tooling::Range> Ranges,
1390                                StringRef FileName) {
1391   FileManager Files((FileSystemOptions()));
1392   DiagnosticsEngine Diagnostics(
1393       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1394       new DiagnosticOptions);
1395   SourceManager SourceMgr(Diagnostics, Files);
1396   llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1397   const clang::FileEntry *Entry =
1398       Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1399   SourceMgr.overrideFileContents(Entry, Buf);
1400   FileID ID =
1401       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1402   Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1403             getFormattingLangOpts(Style.Standard));
1404   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1405   std::vector<CharSourceRange> CharRanges;
1406   for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1407     SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1408     SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1409     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1410   }
1411   return reformat(Style, Lex, SourceMgr, CharRanges);
1412 }
1413 
1414 LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
1415   LangOptions LangOpts;
1416   LangOpts.CPlusPlus = 1;
1417   LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
1418   LangOpts.LineComment = 1;
1419   LangOpts.Bool = 1;
1420   LangOpts.ObjC1 = 1;
1421   LangOpts.ObjC2 = 1;
1422   return LangOpts;
1423 }
1424 
1425 const char *StyleOptionHelpDescription =
1426     "Coding style, currently supports:\n"
1427     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
1428     "Use -style=file to load style configuration from\n"
1429     ".clang-format file located in one of the parent\n"
1430     "directories of the source file (or current\n"
1431     "directory for stdin).\n"
1432     "Use -style=\"{key: value, ...}\" to set specific\n"
1433     "parameters, e.g.:\n"
1434     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1435 
1436 FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
1437   // Fallback style in case the rest of this function can't determine a style.
1438   StringRef FallbackStyle = "LLVM";
1439   FormatStyle Style;
1440   getPredefinedStyle(FallbackStyle, &Style);
1441 
1442   if (StyleName.startswith("{")) {
1443     // Parse YAML/JSON style from the command line.
1444     if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
1445       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1446                    << FallbackStyle << " style\n";
1447     }
1448     return Style;
1449   }
1450 
1451   if (!StyleName.equals_lower("file")) {
1452     if (!getPredefinedStyle(StyleName, &Style))
1453       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1454                    << " style\n";
1455     return Style;
1456   }
1457 
1458   SmallString<128> Path(FileName);
1459   llvm::sys::fs::make_absolute(Path);
1460   for (StringRef Directory = Path; !Directory.empty();
1461        Directory = llvm::sys::path::parent_path(Directory)) {
1462     if (!llvm::sys::fs::is_directory(Directory))
1463       continue;
1464     SmallString<128> ConfigFile(Directory);
1465 
1466     llvm::sys::path::append(ConfigFile, ".clang-format");
1467     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1468     bool IsFile = false;
1469     // Ignore errors from is_regular_file: we only need to know if we can read
1470     // the file or not.
1471     llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1472 
1473     if (!IsFile) {
1474       // Try _clang-format too, since dotfiles are not commonly used on Windows.
1475       ConfigFile = Directory;
1476       llvm::sys::path::append(ConfigFile, "_clang-format");
1477       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1478       llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1479     }
1480 
1481     if (IsFile) {
1482       OwningPtr<llvm::MemoryBuffer> Text;
1483       if (llvm::error_code ec =
1484               llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
1485         llvm::errs() << ec.message() << "\n";
1486         continue;
1487       }
1488       if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1489         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1490                      << "\n";
1491         continue;
1492       }
1493       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1494       return Style;
1495     }
1496   }
1497   llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1498                << " style\n";
1499   return Style;
1500 }
1501 
1502 } // namespace format
1503 } // namespace clang
1504