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 "TokenAnnotator.h"
19 #include "UnwrappedLineParser.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/OperatorPrecedence.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Format/Format.h"
24 #include "clang/Frontend/TextDiagnosticPrinter.h"
25 #include "clang/Lex/Lexer.h"
26 #include "llvm/Support/Debug.h"
27 #include <string>
28 
29 // Uncomment to get debug output from tests:
30 // #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
31 
32 namespace clang {
33 namespace format {
34 
35 FormatStyle getLLVMStyle() {
36   FormatStyle LLVMStyle;
37   LLVMStyle.ColumnLimit = 80;
38   LLVMStyle.MaxEmptyLinesToKeep = 1;
39   LLVMStyle.PointerBindsToType = false;
40   LLVMStyle.DerivePointerBinding = false;
41   LLVMStyle.AccessModifierOffset = -2;
42   LLVMStyle.Standard = FormatStyle::LS_Cpp03;
43   LLVMStyle.IndentCaseLabels = false;
44   LLVMStyle.SpacesBeforeTrailingComments = 1;
45   LLVMStyle.BinPackParameters = true;
46   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
47   LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
48   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
49   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
50   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
51   LLVMStyle.PenaltyExcessCharacter = 1000000;
52   return LLVMStyle;
53 }
54 
55 FormatStyle getGoogleStyle() {
56   FormatStyle GoogleStyle;
57   GoogleStyle.ColumnLimit = 80;
58   GoogleStyle.MaxEmptyLinesToKeep = 1;
59   GoogleStyle.PointerBindsToType = true;
60   GoogleStyle.DerivePointerBinding = true;
61   GoogleStyle.AccessModifierOffset = -1;
62   GoogleStyle.Standard = FormatStyle::LS_Auto;
63   GoogleStyle.IndentCaseLabels = true;
64   GoogleStyle.SpacesBeforeTrailingComments = 2;
65   GoogleStyle.BinPackParameters = false;
66   GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
67   GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
68   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
69   GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
70   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
71   GoogleStyle.PenaltyExcessCharacter = 1000000;
72   return GoogleStyle;
73 }
74 
75 FormatStyle getChromiumStyle() {
76   FormatStyle ChromiumStyle = getGoogleStyle();
77   ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
78   ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
79   ChromiumStyle.DerivePointerBinding = false;
80   return ChromiumStyle;
81 }
82 
83 static bool isTrailingComment(const AnnotatedToken &Tok) {
84   return Tok.is(tok::comment) &&
85          (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86 }
87 
88 /// \brief Manages the whitespaces around tokens and their replacements.
89 ///
90 /// This includes special handling for certain constructs, e.g. the alignment of
91 /// trailing line comments.
92 class WhitespaceManager {
93 public:
94   WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
95 
96   /// \brief Replaces the whitespace in front of \p Tok. Only call once for
97   /// each \c AnnotatedToken.
98   void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
99                          unsigned Spaces, unsigned WhitespaceStartColumn,
100                          const FormatStyle &Style) {
101     // 2+ newlines mean an empty line separating logic scopes.
102     if (NewLines >= 2)
103       alignComments();
104 
105     // Align line comments if they are trailing or if they continue other
106     // trailing comments.
107     if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
108       if (Style.ColumnLimit >=
109           Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
110         Comments.push_back(StoredComment());
111         Comments.back().Tok = Tok.FormatTok;
112         Comments.back().Spaces = Spaces;
113         Comments.back().NewLines = NewLines;
114         if (NewLines == 0)
115           Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
116         else
117           Comments.back().MinColumn = Spaces;
118         Comments.back().MaxColumn =
119             Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
120         return;
121       }
122     }
123 
124     // If this line does not have a trailing comment, align the stored comments.
125     if (Tok.Children.empty() && !isTrailingComment(Tok))
126       alignComments();
127     storeReplacement(Tok.FormatTok,
128                      std::string(NewLines, '\n') + std::string(Spaces, ' '));
129   }
130 
131   /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
132   /// backslashes to escape newlines inside a preprocessor directive.
133   ///
134   /// This function and \c replaceWhitespace have the same behavior if
135   /// \c Newlines == 0.
136   void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
137                            unsigned Spaces, unsigned WhitespaceStartColumn,
138                            const FormatStyle &Style) {
139     std::string NewLineText;
140     if (NewLines > 0) {
141       unsigned Offset =
142           std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
143       for (unsigned i = 0; i < NewLines; ++i) {
144         NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
145         NewLineText += "\\\n";
146         Offset = 0;
147       }
148     }
149     storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
150   }
151 
152   /// \brief Returns all the \c Replacements created during formatting.
153   const tooling::Replacements &generateReplacements() {
154     alignComments();
155     return Replaces;
156   }
157 
158 private:
159   /// \brief Structure to store a comment for later layout and alignment.
160   struct StoredComment {
161     FormatToken Tok;
162     unsigned MinColumn;
163     unsigned MaxColumn;
164     unsigned NewLines;
165     unsigned Spaces;
166   };
167   SmallVector<StoredComment, 16> Comments;
168   typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
169 
170   /// \brief Try to align all stashed comments.
171   void alignComments() {
172     unsigned MinColumn = 0;
173     unsigned MaxColumn = UINT_MAX;
174     comment_iterator Start = Comments.begin();
175     for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
176          ++I) {
177       if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
178         alignComments(Start, I, MinColumn);
179         MinColumn = I->MinColumn;
180         MaxColumn = I->MaxColumn;
181         Start = I;
182       } else {
183         MinColumn = std::max(MinColumn, I->MinColumn);
184         MaxColumn = std::min(MaxColumn, I->MaxColumn);
185       }
186     }
187     alignComments(Start, Comments.end(), MinColumn);
188     Comments.clear();
189   }
190 
191   /// \brief Put all the comments between \p I and \p E into \p Column.
192   void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
193     while (I != E) {
194       unsigned Spaces = I->Spaces + Column - I->MinColumn;
195       storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
196                        std::string(Spaces, ' '));
197       ++I;
198     }
199   }
200 
201   /// \brief Stores \p Text as the replacement for the whitespace in front of
202   /// \p Tok.
203   void storeReplacement(const FormatToken &Tok, const std::string Text) {
204     // Don't create a replacement, if it does not change anything.
205     if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
206                   Tok.WhiteSpaceLength) == Text)
207       return;
208 
209     Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
210                                          Tok.WhiteSpaceLength, Text));
211   }
212 
213   SourceManager &SourceMgr;
214   tooling::Replacements Replaces;
215 };
216 
217 class UnwrappedLineFormatter {
218 public:
219   UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
220                          const AnnotatedLine &Line, unsigned FirstIndent,
221                          const AnnotatedToken &RootToken,
222                          WhitespaceManager &Whitespaces, bool StructuralError)
223       : Style(Style), SourceMgr(SourceMgr), Line(Line),
224         FirstIndent(FirstIndent), RootToken(RootToken),
225         Whitespaces(Whitespaces) {
226   }
227 
228   /// \brief Formats an \c UnwrappedLine.
229   ///
230   /// \returns The column after the last token in the last line of the
231   /// \c UnwrappedLine.
232   unsigned format() {
233     // Initialize state dependent on indent.
234     LineState State;
235     State.Column = FirstIndent;
236     State.NextToken = &RootToken;
237     State.Stack.push_back(
238         ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
239                    /*HasMultiParameterLine=*/ false));
240     State.VariablePos = 0;
241     State.LineContainsContinuedForLoopSection = false;
242 
243     DEBUG({
244       DebugTokenState(*State.NextToken);
245     });
246 
247     // The first token has already been indented and thus consumed.
248     moveStateToNextToken(State);
249 
250     // If everything fits on a single line, just put it there.
251     if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
252       while (State.NextToken != NULL) {
253         addTokenToState(false, false, State);
254       }
255       return State.Column;
256     }
257 
258     // Find best solution in solution space.
259     return analyzeSolutionSpace(State);
260   }
261 
262 private:
263   void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
264     const Token &Tok = AnnotatedTok.FormatTok.Tok;
265     llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
266                               Tok.getLength());
267     llvm::errs();
268   }
269 
270   struct ParenState {
271     ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
272                bool HasMultiParameterLine)
273         : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
274           FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
275           AvoidBinPacking(AvoidBinPacking), BreakAfterComma(false),
276           HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {
277     }
278 
279     /// \brief The position to which a specific parenthesis level needs to be
280     /// indented.
281     unsigned Indent;
282 
283     /// \brief The position of the last space on each level.
284     ///
285     /// Used e.g. to break like:
286     /// functionCall(Parameter, otherCall(
287     ///                             OtherParameter));
288     unsigned LastSpace;
289 
290     /// \brief This is the column of the first token after an assignment.
291     unsigned AssignmentColumn;
292 
293     /// \brief The position the first "<<" operator encountered on each level.
294     ///
295     /// Used to align "<<" operators. 0 if no such operator has been encountered
296     /// on a level.
297     unsigned FirstLessLess;
298 
299     /// \brief Whether a newline needs to be inserted before the block's closing
300     /// brace.
301     ///
302     /// We only want to insert a newline before the closing brace if there also
303     /// was a newline after the beginning left brace.
304     bool BreakBeforeClosingBrace;
305 
306     /// \brief The column of a \c ? in a conditional expression;
307     unsigned QuestionColumn;
308 
309     /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
310     /// lines, in this context.
311     bool AvoidBinPacking;
312 
313     /// \brief Break after the next comma (or all the commas in this context if
314     /// \c AvoidBinPacking is \c true).
315     bool BreakAfterComma;
316 
317     /// \brief This context already has a line with more than one parameter.
318     bool HasMultiParameterLine;
319 
320     /// \brief The position of the colon in an ObjC method declaration/call.
321     unsigned ColonPos;
322 
323     bool operator<(const ParenState &Other) const {
324       if (Indent != Other.Indent)
325         return Indent < Other.Indent;
326       if (LastSpace != Other.LastSpace)
327         return LastSpace < Other.LastSpace;
328       if (AssignmentColumn != Other.AssignmentColumn)
329         return AssignmentColumn < Other.AssignmentColumn;
330       if (FirstLessLess != Other.FirstLessLess)
331         return FirstLessLess < Other.FirstLessLess;
332       if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
333         return BreakBeforeClosingBrace;
334       if (QuestionColumn != Other.QuestionColumn)
335         return QuestionColumn < Other.QuestionColumn;
336       if (AvoidBinPacking != Other.AvoidBinPacking)
337         return AvoidBinPacking;
338       if (BreakAfterComma != Other.BreakAfterComma)
339         return BreakAfterComma;
340       if (HasMultiParameterLine != Other.HasMultiParameterLine)
341         return HasMultiParameterLine;
342       if (ColonPos != Other.ColonPos)
343         return ColonPos < Other.ColonPos;
344       return false;
345     }
346   };
347 
348   /// \brief The current state when indenting a unwrapped line.
349   ///
350   /// As the indenting tries different combinations this is copied by value.
351   struct LineState {
352     /// \brief The number of used columns in the current line.
353     unsigned Column;
354 
355     /// \brief The token that needs to be next formatted.
356     const AnnotatedToken *NextToken;
357 
358     /// \brief The column of the first variable name in a variable declaration.
359     ///
360     /// Used to align further variables if necessary.
361     unsigned VariablePos;
362 
363     /// \brief \c true if this line contains a continued for-loop section.
364     bool LineContainsContinuedForLoopSection;
365 
366     /// \brief A stack keeping track of properties applying to parenthesis
367     /// levels.
368     std::vector<ParenState> Stack;
369 
370     /// \brief Comparison operator to be able to used \c LineState in \c map.
371     bool operator<(const LineState &Other) const {
372       if (Other.NextToken != NextToken)
373         return Other.NextToken > NextToken;
374       if (Other.Column != Column)
375         return Other.Column > Column;
376       if (Other.VariablePos != VariablePos)
377         return Other.VariablePos < VariablePos;
378       if (Other.LineContainsContinuedForLoopSection !=
379           LineContainsContinuedForLoopSection)
380         return LineContainsContinuedForLoopSection;
381       return Other.Stack < Stack;
382     }
383   };
384 
385   /// \brief Appends the next token to \p State and updates information
386   /// necessary for indentation.
387   ///
388   /// Puts the token on the current line if \p Newline is \c true and adds a
389   /// line break and necessary indentation otherwise.
390   ///
391   /// If \p DryRun is \c false, also creates and stores the required
392   /// \c Replacement.
393   void addTokenToState(bool Newline, bool DryRun, LineState &State) {
394     const AnnotatedToken &Current = *State.NextToken;
395     const AnnotatedToken &Previous = *State.NextToken->Parent;
396     assert(State.Stack.size());
397     unsigned ParenLevel = State.Stack.size() - 1;
398 
399     if (Current.Type == TT_ImplicitStringLiteral) {
400       State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
401                       State.NextToken->FormatTok.TokenLength;
402       if (State.NextToken->Children.empty())
403         State.NextToken = NULL;
404       else
405         State.NextToken = &State.NextToken->Children[0];
406       return;
407     }
408 
409     if (Newline) {
410       unsigned WhitespaceStartColumn = State.Column;
411       if (Current.is(tok::r_brace)) {
412         State.Column = Line.Level * 2;
413       } else if (Current.is(tok::string_literal) &&
414                  Previous.is(tok::string_literal)) {
415         State.Column = State.Column - Previous.FormatTok.TokenLength;
416       } else if (Current.is(tok::lessless) &&
417                  State.Stack[ParenLevel].FirstLessLess != 0) {
418         State.Column = State.Stack[ParenLevel].FirstLessLess;
419       } else if (ParenLevel != 0 &&
420                  (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
421                   Current.is(tok::period) || Current.is(tok::arrow) ||
422                   Current.is(tok::question))) {
423         // Indent and extra 4 spaces after if we know the current expression is
424         // continued.  Don't do that on the top level, as we already indent 4
425         // there.
426         State.Column = std::max(State.Stack.back().LastSpace,
427                                 State.Stack.back().Indent) + 4;
428       } else if (Current.Type == TT_ConditionalExpr) {
429         State.Column = State.Stack.back().QuestionColumn;
430       } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
431                  ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
432                   ParenLevel == 0)) {
433         State.Column = State.VariablePos;
434       } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
435                  Current.Type == TT_StartOfName) {
436         State.Column = State.Stack[ParenLevel].Indent - 4;
437       } else if (Previous.Type == TT_BinaryOperator &&
438                  State.Stack.back().AssignmentColumn != 0) {
439         State.Column = State.Stack.back().AssignmentColumn;
440       } else if (Current.Type == TT_ObjCSelectorName) {
441         if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
442           State.Column =
443               State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
444         } else {
445           State.Column = State.Stack.back().Indent;
446           State.Stack.back().ColonPos =
447               State.Column + Current.FormatTok.TokenLength;
448         }
449       } else if (Previous.Type == TT_ObjCMethodExpr) {
450         State.Column = State.Stack.back().Indent + 4;
451       } else {
452         State.Column = State.Stack[ParenLevel].Indent;
453       }
454 
455       if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
456         State.Stack.back().BreakAfterComma = false;
457 
458       if (RootToken.is(tok::kw_for))
459         State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
460 
461       if (!DryRun) {
462         if (!Line.InPPDirective)
463           Whitespaces.replaceWhitespace(Current, 1, State.Column,
464                                         WhitespaceStartColumn, Style);
465         else
466           Whitespaces.replacePPWhitespace(Current, 1, State.Column,
467                                           WhitespaceStartColumn, Style);
468       }
469 
470       State.Stack[ParenLevel].LastSpace = State.Column;
471       if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
472         State.Stack[ParenLevel].Indent += 2;
473     } else {
474       if (Current.is(tok::equal) &&
475           (RootToken.is(tok::kw_for) || ParenLevel == 0))
476         State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
477 
478       unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
479       if (State.NextToken->Type == TT_LineComment)
480         Spaces = Style.SpacesBeforeTrailingComments;
481 
482       if (!DryRun)
483         Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
484 
485       if (Current.Type == TT_ObjCSelectorName &&
486           State.Stack.back().ColonPos == 0) {
487         if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
488             State.Column + Spaces + Current.FormatTok.TokenLength)
489           State.Stack.back().ColonPos =
490               State.Stack.back().Indent + Current.LongestObjCSelectorName;
491         else
492           State.Stack.back().ColonPos =
493               State.Column + Spaces + Current.FormatTok.TokenLength;
494       }
495 
496       // FIXME: Do we need to do this for assignments nested in other
497       // expressions?
498       if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
499           !isTrailingComment(Current) &&
500           (getPrecedence(Previous) == prec::Assignment ||
501            Previous.is(tok::kw_return)))
502         State.Stack.back().AssignmentColumn = State.Column + Spaces;
503       if (Current.Type != TT_LineComment &&
504           (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
505            State.NextToken->Parent->Type == TT_TemplateOpener))
506         State.Stack[ParenLevel].Indent = State.Column + Spaces;
507       if (Previous.is(tok::comma) && !isTrailingComment(Current))
508         State.Stack[ParenLevel].HasMultiParameterLine = true;
509 
510       State.Column += Spaces;
511       if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
512         // Treat the condition inside an if as if it was a second function
513         // parameter, i.e. let nested calls have an indent of 4.
514         State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
515       else if (Previous.is(tok::comma) && ParenLevel != 0)
516         // Top-level spaces are exempt as that mostly leads to better results.
517         State.Stack.back().LastSpace = State.Column;
518       else if ((Previous.Type == TT_BinaryOperator ||
519                 Previous.Type == TT_ConditionalExpr ||
520                 Previous.Type == TT_CtorInitializerColon) &&
521                getPrecedence(Previous) != prec::Assignment)
522         State.Stack.back().LastSpace = State.Column;
523       else if (Previous.ParameterCount > 1 &&
524                (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
525                 Previous.is(tok::l_brace) ||
526                 Previous.Type == TT_TemplateOpener))
527         // If this function has multiple parameters, indent nested calls from
528         // the start of the first parameter.
529         State.Stack.back().LastSpace = State.Column;
530     }
531 
532     // If we break after an {, we should also break before the corresponding }.
533     if (Newline && Previous.is(tok::l_brace))
534       State.Stack.back().BreakBeforeClosingBrace = true;
535 
536     if (State.Stack.back().AvoidBinPacking && Newline &&
537         (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
538       // If we are breaking after '(', '{', '<', this is not bin packing unless
539       // AllowAllParametersOfDeclarationOnNextLine is false.
540       if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
541            Previous.Type != TT_TemplateOpener) ||
542           (!Style.AllowAllParametersOfDeclarationOnNextLine &&
543            Line.MustBeDeclaration))
544         State.Stack.back().BreakAfterComma = true;
545 
546       // Any break on this level means that the parent level has been broken
547       // and we need to avoid bin packing there.
548       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
549         if (Line.First.isNot(tok::kw_for) || i != 1)
550           State.Stack[i].BreakAfterComma = true;
551       }
552     }
553 
554     moveStateToNextToken(State);
555   }
556 
557   /// \brief Mark the next token as consumed in \p State and modify its stacks
558   /// accordingly.
559   void moveStateToNextToken(LineState &State) {
560     const AnnotatedToken &Current = *State.NextToken;
561     assert(State.Stack.size());
562 
563     if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
564       State.Stack.back().FirstLessLess = State.Column;
565     if (Current.is(tok::question))
566       State.Stack.back().QuestionColumn = State.Column;
567     if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
568         !Current.MatchingParen->MustBreakBefore) {
569       AnnotatedToken *End = Current.MatchingParen;
570       while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
571         End = &End->Children[0];
572       }
573       unsigned Length = End->TotalLength - Current.TotalLength + 1;
574       if (Length + State.Column > getColumnLimit())
575         State.Stack.back().BreakAfterComma = true;
576     }
577 
578     // If we encounter an opening (, [, { or <, we add a level to our stacks to
579     // prepare for the following tokens.
580     if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
581         Current.is(tok::l_brace) ||
582         State.NextToken->Type == TT_TemplateOpener) {
583       unsigned NewIndent;
584       bool AvoidBinPacking;
585       if (Current.is(tok::l_brace)) {
586         NewIndent = 2 + State.Stack.back().LastSpace;
587         AvoidBinPacking = false;
588       } else {
589         NewIndent = 4 + State.Stack.back().LastSpace;
590         AvoidBinPacking = !Style.BinPackParameters;
591       }
592       State.Stack.push_back(
593           ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
594                      State.Stack.back().HasMultiParameterLine));
595     }
596 
597     // If we encounter a closing ), ], } or >, we can remove a level from our
598     // stacks.
599     if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
600         (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
601         State.NextToken->Type == TT_TemplateCloser) {
602       State.Stack.pop_back();
603     }
604 
605     if (State.NextToken->Children.empty())
606       State.NextToken = NULL;
607     else
608       State.NextToken = &State.NextToken->Children[0];
609 
610     State.Column += Current.FormatTok.TokenLength;
611   }
612 
613   unsigned getColumnLimit() {
614     return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
615   }
616 
617   /// \brief An edge in the solution space starting from the \c LineState and
618   /// inserting a newline dependent on the \c bool.
619   typedef std::pair<bool, const LineState *> Edge;
620 
621   /// \brief An item in the prioritized BFS search queue. The \c LineState was
622   /// reached using the \c Edge.
623   typedef std::pair<LineState, Edge> QueueItem;
624 
625   /// \brief Analyze the entire solution space starting from \p InitialState.
626   ///
627   /// This implements a variant of Dijkstra's algorithm on the graph that spans
628   /// the solution space (\c LineStates are the nodes). The algorithm tries to
629   /// find the shortest path (the one with lowest penalty) from \p InitialState
630   /// to a state where all tokens are placed.
631   unsigned analyzeSolutionSpace(const LineState &InitialState) {
632     // Insert start element into queue.
633     std::multimap<unsigned, QueueItem> Queue;
634     Queue.insert(std::pair<unsigned, QueueItem>(
635         0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
636     std::map<LineState, Edge> Seen;
637 
638     // While not empty, take first element and follow edges.
639     while (!Queue.empty()) {
640       unsigned Penalty = Queue.begin()->first;
641       QueueItem Item = Queue.begin()->second;
642       if (Item.first.NextToken == NULL) {
643         DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
644         break;
645       }
646       Queue.erase(Queue.begin());
647 
648       if (Seen.find(Item.first) != Seen.end())
649         continue; // State already examined with lower penalty.
650 
651       const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
652           Item.first,
653           Edge(Item.second.first, Item.second.second))).first->first;
654 
655       addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
656       addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
657     }
658 
659     if (Queue.empty())
660       // We were unable to find a solution, do nothing.
661       // FIXME: Add diagnostic?
662       return 0;
663 
664     // Reconstruct the solution.
665     // FIXME: Add debugging output.
666     Edge *CurrentEdge = &Queue.begin()->second.second;
667     while (CurrentEdge->second != NULL) {
668       LineState CurrentState = *CurrentEdge->second;
669       if (CurrentEdge->first) {
670         DEBUG(llvm::errs() << "Penalty for splitting before "
671                            << CurrentState.NextToken->FormatTok.Tok.getName()
672                            << ": " << CurrentState.NextToken->SplitPenalty
673                            << "\n");
674       }
675       addTokenToState(CurrentEdge->first, false, CurrentState);
676       CurrentEdge = &Seen[*CurrentEdge->second];
677     }
678     DEBUG(llvm::errs() << "---\n");
679 
680     // Return the column after the last token of the solution.
681     return Queue.begin()->second.first.Column;
682   }
683 
684   /// \brief Add the following state to the analysis queue \p Queue.
685   ///
686   /// Assume the current state is \p OldState and has been reached with a
687   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
688   void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
689                            bool NewLine,
690                            std::multimap<unsigned, QueueItem> &Queue) {
691     if (NewLine && !canBreak(OldState))
692       return;
693     if (!NewLine && mustBreak(OldState))
694       return;
695     LineState State(OldState);
696     if (NewLine)
697       Penalty += State.NextToken->SplitPenalty;
698     addTokenToState(NewLine, true, State);
699     if (State.Column > getColumnLimit()) {
700       unsigned ExcessCharacters = State.Column - getColumnLimit();
701       Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
702     }
703     Queue.insert(std::pair<unsigned, QueueItem>(
704         Penalty, QueueItem(State, Edge(NewLine, &OldState))));
705   }
706 
707   /// \brief Returns \c true, if a line break after \p State is allowed.
708   bool canBreak(const LineState &State) {
709     if (!State.NextToken->CanBreakBefore &&
710         !(State.NextToken->is(tok::r_brace) &&
711           State.Stack.back().BreakBeforeClosingBrace))
712       return false;
713     // Trying to insert a parameter on a new line if there are already more than
714     // one parameter on the current line is bin packing.
715     if (State.Stack.back().HasMultiParameterLine &&
716         State.Stack.back().AvoidBinPacking)
717       return false;
718     return true;
719   }
720 
721   /// \brief Returns \c true, if a line break after \p State is mandatory.
722   bool mustBreak(const LineState &State) {
723     if (State.NextToken->MustBreakBefore)
724       return true;
725     if (State.NextToken->is(tok::r_brace) &&
726         State.Stack.back().BreakBeforeClosingBrace)
727       return true;
728     if (State.NextToken->Parent->is(tok::semi) &&
729         State.LineContainsContinuedForLoopSection)
730       return true;
731     if (State.NextToken->Parent->is(tok::comma) &&
732         State.Stack.back().BreakAfterComma &&
733         !isTrailingComment(*State.NextToken))
734       return true;
735     if (State.NextToken->Type == TT_ObjCSelectorName &&
736         State.Stack.back().ColonPos != 0)
737       return true;
738     if ((State.NextToken->Type == TT_CtorInitializerColon ||
739          (State.NextToken->Parent->ClosesTemplateDeclaration &&
740           State.Stack.size() == 1)))
741       return true;
742     return false;
743   }
744 
745   FormatStyle Style;
746   SourceManager &SourceMgr;
747   const AnnotatedLine &Line;
748   const unsigned FirstIndent;
749   const AnnotatedToken &RootToken;
750   WhitespaceManager &Whitespaces;
751 };
752 
753 class LexerBasedFormatTokenSource : public FormatTokenSource {
754 public:
755   LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
756       : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
757         IdentTable(Lex.getLangOpts()) {
758     Lex.SetKeepWhitespaceMode(true);
759   }
760 
761   virtual FormatToken getNextToken() {
762     if (GreaterStashed) {
763       FormatTok.NewlinesBefore = 0;
764       FormatTok.WhiteSpaceStart =
765           FormatTok.Tok.getLocation().getLocWithOffset(1);
766       FormatTok.WhiteSpaceLength = 0;
767       GreaterStashed = false;
768       return FormatTok;
769     }
770 
771     FormatTok = FormatToken();
772     Lex.LexFromRawLexer(FormatTok.Tok);
773     StringRef Text = rawTokenText(FormatTok.Tok);
774     FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
775     if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
776       FormatTok.IsFirst = true;
777 
778     // Consume and record whitespace until we find a significant token.
779     while (FormatTok.Tok.is(tok::unknown)) {
780       FormatTok.NewlinesBefore += Text.count('\n');
781       FormatTok.HasUnescapedNewline =
782           Text.count("\\\n") != FormatTok.NewlinesBefore;
783       FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
784 
785       if (FormatTok.Tok.is(tok::eof))
786         return FormatTok;
787       Lex.LexFromRawLexer(FormatTok.Tok);
788       Text = rawTokenText(FormatTok.Tok);
789     }
790 
791     // Now FormatTok is the next non-whitespace token.
792     FormatTok.TokenLength = Text.size();
793 
794     // In case the token starts with escaped newlines, we want to
795     // take them into account as whitespace - this pattern is quite frequent
796     // in macro definitions.
797     // FIXME: What do we want to do with other escaped spaces, and escaped
798     // spaces or newlines in the middle of tokens?
799     // FIXME: Add a more explicit test.
800     unsigned i = 0;
801     while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
802       // FIXME: ++FormatTok.NewlinesBefore is missing...
803       FormatTok.WhiteSpaceLength += 2;
804       FormatTok.TokenLength -= 2;
805       i += 2;
806     }
807 
808     if (FormatTok.Tok.is(tok::raw_identifier)) {
809       IdentifierInfo &Info = IdentTable.get(Text);
810       FormatTok.Tok.setIdentifierInfo(&Info);
811       FormatTok.Tok.setKind(Info.getTokenID());
812     }
813 
814     if (FormatTok.Tok.is(tok::greatergreater)) {
815       FormatTok.Tok.setKind(tok::greater);
816       GreaterStashed = true;
817     }
818 
819     return FormatTok;
820   }
821 
822 private:
823   FormatToken FormatTok;
824   bool GreaterStashed;
825   Lexer &Lex;
826   SourceManager &SourceMgr;
827   IdentifierTable IdentTable;
828 
829   /// Returns the text of \c FormatTok.
830   StringRef rawTokenText(Token &Tok) {
831     return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
832                      Tok.getLength());
833   }
834 };
835 
836 class Formatter : public UnwrappedLineConsumer {
837 public:
838   Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
839             SourceManager &SourceMgr,
840             const std::vector<CharSourceRange> &Ranges)
841       : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
842         Whitespaces(SourceMgr), Ranges(Ranges) {
843   }
844 
845   virtual ~Formatter() {}
846 
847   void deriveLocalStyle() {
848     unsigned CountBoundToVariable = 0;
849     unsigned CountBoundToType = 0;
850     bool HasCpp03IncompatibleFormat = false;
851     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
852       if (AnnotatedLines[i].First.Children.empty())
853         continue;
854       AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
855       while (!Tok->Children.empty()) {
856         if (Tok->Type == TT_PointerOrReference) {
857           bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
858           bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
859           if (SpacesBefore && !SpacesAfter)
860             ++CountBoundToVariable;
861           else if (!SpacesBefore && SpacesAfter)
862             ++CountBoundToType;
863         }
864 
865         if (Tok->Type == TT_TemplateCloser && Tok->Parent->Type ==
866             TT_TemplateCloser && Tok->FormatTok.WhiteSpaceLength == 0)
867           HasCpp03IncompatibleFormat = true;
868         Tok = &Tok->Children[0];
869       }
870     }
871     if (Style.DerivePointerBinding) {
872       if (CountBoundToType > CountBoundToVariable)
873         Style.PointerBindsToType = true;
874       else if (CountBoundToType < CountBoundToVariable)
875         Style.PointerBindsToType = false;
876     }
877     if (Style.Standard == FormatStyle::LS_Auto) {
878       Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
879                                                   : FormatStyle::LS_Cpp03;
880     }
881   }
882 
883   tooling::Replacements format() {
884     LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
885     UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
886     StructuralError = Parser.parse();
887     unsigned PreviousEndOfLineColumn = 0;
888     TokenAnnotator Annotator(Style, SourceMgr, Lex);
889     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
890       Annotator.annotate(AnnotatedLines[i]);
891     }
892     deriveLocalStyle();
893     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
894       Annotator.calculateFormattingInformation(AnnotatedLines[i]);
895     }
896     for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
897                                               E = AnnotatedLines.end();
898          I != E; ++I) {
899       const AnnotatedLine &TheLine = *I;
900       if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
901         unsigned Indent =
902             formatFirstToken(TheLine.First, TheLine.Level,
903                              TheLine.InPPDirective, PreviousEndOfLineColumn);
904         tryFitMultipleLinesInOne(Indent, I, E);
905         UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
906                                          TheLine.First, Whitespaces,
907                                          StructuralError);
908         PreviousEndOfLineColumn = Formatter.format();
909       } else {
910         // If we did not reformat this unwrapped line, the column at the end of
911         // the last token is unchanged - thus, we can calculate the end of the
912         // last token, and return the result.
913         PreviousEndOfLineColumn =
914             SourceMgr.getSpellingColumnNumber(
915                 TheLine.Last->FormatTok.Tok.getLocation()) +
916             Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
917                                    SourceMgr, Lex.getLangOpts()) - 1;
918       }
919     }
920     return Whitespaces.generateReplacements();
921   }
922 
923 private:
924   /// \brief Tries to merge lines into one.
925   ///
926   /// This will change \c Line and \c AnnotatedLine to contain the merged line,
927   /// if possible; note that \c I will be incremented when lines are merged.
928   ///
929   /// Returns whether the resulting \c Line can fit in a single line.
930   void tryFitMultipleLinesInOne(unsigned Indent,
931                                 std::vector<AnnotatedLine>::iterator &I,
932                                 std::vector<AnnotatedLine>::iterator E) {
933     unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
934 
935     // We can never merge stuff if there are trailing line comments.
936     if (I->Last->Type == TT_LineComment)
937       return;
938 
939     // Check whether the UnwrappedLine can be put onto a single line. If
940     // so, this is bound to be the optimal solution (by definition) and we
941     // don't need to analyze the entire solution space.
942     if (I->Last->TotalLength > Limit)
943       return;
944     Limit -= I->Last->TotalLength;
945 
946     if (I + 1 == E || (I + 1)->Type == LT_Invalid)
947       return;
948 
949     if (I->Last->is(tok::l_brace)) {
950       tryMergeSimpleBlock(I, E, Limit);
951     } else if (I->First.is(tok::kw_if)) {
952       tryMergeSimpleIf(I, E, Limit);
953     } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
954                                     I->First.FormatTok.IsFirst)) {
955       tryMergeSimplePPDirective(I, E, Limit);
956     }
957     return;
958   }
959 
960   void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
961                                  std::vector<AnnotatedLine>::iterator E,
962                                  unsigned Limit) {
963     AnnotatedLine &Line = *I;
964     if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
965       return;
966     if (I + 2 != E && (I + 2)->InPPDirective &&
967         !(I + 2)->First.FormatTok.HasUnescapedNewline)
968       return;
969     if (1 + (I + 1)->Last->TotalLength > Limit)
970       return;
971     join(Line, *(++I));
972   }
973 
974   void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
975                         std::vector<AnnotatedLine>::iterator E,
976                         unsigned Limit) {
977     if (!Style.AllowShortIfStatementsOnASingleLine)
978       return;
979     if ((I + 1)->InPPDirective != I->InPPDirective ||
980         ((I + 1)->InPPDirective &&
981          (I + 1)->First.FormatTok.HasUnescapedNewline))
982       return;
983     AnnotatedLine &Line = *I;
984     if (Line.Last->isNot(tok::r_paren))
985       return;
986     if (1 + (I + 1)->Last->TotalLength > Limit)
987       return;
988     if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
989       return;
990     // Only inline simple if's (no nested if or else).
991     if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
992       return;
993     join(Line, *(++I));
994   }
995 
996   void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
997                            std::vector<AnnotatedLine>::iterator E,
998                            unsigned Limit) {
999     // First, check that the current line allows merging. This is the case if
1000     // we're not in a control flow statement and the last token is an opening
1001     // brace.
1002     AnnotatedLine &Line = *I;
1003     bool AllowedTokens =
1004         Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1005         Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1006         Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1007         Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
1008         // This gets rid of all ObjC @ keywords and methods.
1009         Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1010         Line.First.isNot(tok::plus);
1011     if (!AllowedTokens)
1012       return;
1013 
1014     AnnotatedToken *Tok = &(I + 1)->First;
1015     if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1016         !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1017       Tok->SpaceRequiredBefore = false;
1018       join(Line, *(I + 1));
1019       I += 1;
1020     } else {
1021       // Check that we still have three lines and they fit into the limit.
1022       if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1023           !nextTwoLinesFitInto(I, Limit))
1024         return;
1025 
1026       // Second, check that the next line does not contain any braces - if it
1027       // does, readability declines when putting it into a single line.
1028       if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1029         return;
1030       do {
1031         if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1032           return;
1033         Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1034       } while (Tok != NULL);
1035 
1036       // Last, check that the third line contains a single closing brace.
1037       Tok = &(I + 2)->First;
1038       if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1039           Tok->MustBreakBefore)
1040         return;
1041 
1042       join(Line, *(I + 1));
1043       join(Line, *(I + 2));
1044       I += 2;
1045     }
1046   }
1047 
1048   bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1049                            unsigned Limit) {
1050     return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1051            Limit;
1052   }
1053 
1054   void join(AnnotatedLine &A, const AnnotatedLine &B) {
1055     A.Last->Children.push_back(B.First);
1056     while (!A.Last->Children.empty()) {
1057       A.Last->Children[0].Parent = A.Last;
1058       A.Last = &A.Last->Children[0];
1059     }
1060   }
1061 
1062   bool touchesRanges(const AnnotatedLine &TheLine) {
1063     const FormatToken *First = &TheLine.First.FormatTok;
1064     const FormatToken *Last = &TheLine.Last->FormatTok;
1065     CharSourceRange LineRange = CharSourceRange::getTokenRange(
1066         First->Tok.getLocation(), Last->Tok.getLocation());
1067     for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1068       if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1069                                                Ranges[i].getBegin()) &&
1070           !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1071                                                LineRange.getBegin()))
1072         return true;
1073     }
1074     return false;
1075   }
1076 
1077   virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1078     AnnotatedLines.push_back(AnnotatedLine(TheLine));
1079   }
1080 
1081   /// \brief Add a new line and the required indent before the first Token
1082   /// of the \c UnwrappedLine if there was no structural parsing error.
1083   /// Returns the indent level of the \c UnwrappedLine.
1084   unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1085                             bool InPPDirective,
1086                             unsigned PreviousEndOfLineColumn) {
1087     const FormatToken &Tok = RootToken.FormatTok;
1088     if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1089       return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1090 
1091     unsigned Newlines =
1092         std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1093     if (Newlines == 0 && !Tok.IsFirst)
1094       Newlines = 1;
1095     unsigned Indent = Level * 2;
1096 
1097     bool IsAccessModifier = false;
1098     if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1099         RootToken.is(tok::kw_private))
1100       IsAccessModifier = true;
1101     else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1102              (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1103               RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1104               RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1105               RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1106       IsAccessModifier = true;
1107 
1108     if (IsAccessModifier &&
1109         static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1110       Indent += Style.AccessModifierOffset;
1111     if (!InPPDirective || Tok.HasUnescapedNewline) {
1112       Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
1113     } else {
1114       Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1115                                       PreviousEndOfLineColumn, Style);
1116     }
1117     return Indent;
1118   }
1119 
1120   DiagnosticsEngine &Diag;
1121   FormatStyle Style;
1122   Lexer &Lex;
1123   SourceManager &SourceMgr;
1124   WhitespaceManager Whitespaces;
1125   std::vector<CharSourceRange> Ranges;
1126   std::vector<AnnotatedLine> AnnotatedLines;
1127   bool StructuralError;
1128 };
1129 
1130 tooling::Replacements
1131 reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1132          std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
1133   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1134   OwningPtr<DiagnosticConsumer> DiagPrinter;
1135   if (DiagClient == 0) {
1136     DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1137     DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1138     DiagClient = DiagPrinter.get();
1139   }
1140   DiagnosticsEngine Diagnostics(
1141       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1142       DiagClient, false);
1143   Diagnostics.setSourceManager(&SourceMgr);
1144   Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
1145   return formatter.format();
1146 }
1147 
1148 LangOptions getFormattingLangOpts() {
1149   LangOptions LangOpts;
1150   LangOpts.CPlusPlus = 1;
1151   LangOpts.CPlusPlus11 = 1;
1152   LangOpts.Bool = 1;
1153   LangOpts.ObjC1 = 1;
1154   LangOpts.ObjC2 = 1;
1155   return LangOpts;
1156 }
1157 
1158 } // namespace format
1159 } // namespace clang
1160