blob: 18a853f1e4bd84f027b0fb05de242252381f095d [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- 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///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Daniel Jasperf7935112012-12-03 18:12:45 +000031namespace clang {
32namespace format {
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034FormatStyle getLLVMStyle() {
35 FormatStyle LLVMStyle;
36 LLVMStyle.ColumnLimit = 80;
37 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000038 LLVMStyle.PointerBindsToType = false;
39 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000040 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000041 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000046 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000047 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000048 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000049 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000050 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperf7935112012-12-03 18:12:45 +000051 return LLVMStyle;
52}
53
54FormatStyle getGoogleStyle() {
55 FormatStyle GoogleStyle;
56 GoogleStyle.ColumnLimit = 80;
57 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000058 GoogleStyle.PointerBindsToType = true;
59 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000060 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000061 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000062 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000063 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000064 GoogleStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000070 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperf7935112012-12-03 18:12:45 +000071 return GoogleStyle;
72}
73
Daniel Jasper1b750ed2013-01-14 16:24:39 +000074FormatStyle getChromiumStyle() {
75 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000076 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000077 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000078 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
79 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000080 return ChromiumStyle;
81}
82
Daniel Jasper94f0e132013-02-06 20:07:35 +000083static bool isTrailingComment(const AnnotatedToken &Tok) {
84 return Tok.is(tok::comment) &&
85 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86}
87
Daniel Jasperacc33662013-02-08 08:22:00 +000088// Returns the length of everything up to the first possible line break after
89// the ), ], } or > matching \c Tok.
90static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
91 if (Tok.MatchingParen == NULL)
92 return 0;
93 AnnotatedToken *End = Tok.MatchingParen;
94 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
95 End = &End->Children[0];
96 }
97 return End->TotalLength - Tok.TotalLength + 1;
98}
99
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000100/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000101///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000102/// This includes special handling for certain constructs, e.g. the alignment of
103/// trailing line comments.
104class WhitespaceManager {
105public:
106 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
107
108 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
109 /// each \c AnnotatedToken.
110 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
111 unsigned Spaces, unsigned WhitespaceStartColumn,
112 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000113 // 2+ newlines mean an empty line separating logic scopes.
114 if (NewLines >= 2)
115 alignComments();
116
117 // Align line comments if they are trailing or if they continue other
118 // trailing comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000119 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000120 if (Style.ColumnLimit >=
121 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
122 Comments.push_back(StoredComment());
123 Comments.back().Tok = Tok.FormatTok;
124 Comments.back().Spaces = Spaces;
125 Comments.back().NewLines = NewLines;
Daniel Jasperf79f9352013-02-06 22:04:05 +0000126 if (NewLines == 0)
127 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
128 else
129 Comments.back().MinColumn = Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000130 Comments.back().MaxColumn =
Daniel Jasper525264c2013-02-13 19:25:54 +0000131 Style.ColumnLimit - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000132 return;
133 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000134 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000135
136 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000137 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000138 alignComments();
Manuel Klimek1998ea22013-02-20 10:15:13 +0000139 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000140 }
141
142 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
143 /// backslashes to escape newlines inside a preprocessor directive.
144 ///
145 /// This function and \c replaceWhitespace have the same behavior if
146 /// \c Newlines == 0.
147 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
148 unsigned Spaces, unsigned WhitespaceStartColumn,
149 const FormatStyle &Style) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000150 storeReplacement(
151 Tok.FormatTok,
152 getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style));
153 }
154
155 /// \brief Inserts a line break into the middle of a token.
156 ///
157 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
158 /// break and \p Postfix before the rest of the token starts in the next line.
159 ///
160 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
161 /// used to generate the correct line break.
162 void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix,
163 StringRef Postfix, bool InPPDirective, unsigned Spaces,
164 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
165 std::string NewLineText;
166 if (!InPPDirective)
167 NewLineText = getNewLineText(1, Spaces);
168 else
169 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style);
170 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
171 SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart
172 .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset);
173 Replaces.insert(
174 tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText));
175 }
176
177 /// \brief Returns all the \c Replacements created during formatting.
178 const tooling::Replacements &generateReplacements() {
179 alignComments();
180 return Replaces;
181 }
182
183private:
184 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
185 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
186 }
187
188 std::string
189 getNewLineText(unsigned NewLines, unsigned Spaces,
190 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000191 std::string NewLineText;
192 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000193 unsigned Offset =
194 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000195 for (unsigned i = 0; i < NewLines; ++i) {
196 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
197 NewLineText += "\\\n";
198 Offset = 0;
199 }
200 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000201 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000202 }
203
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000204 /// \brief Structure to store a comment for later layout and alignment.
205 struct StoredComment {
206 FormatToken Tok;
207 unsigned MinColumn;
208 unsigned MaxColumn;
209 unsigned NewLines;
210 unsigned Spaces;
211 };
212 SmallVector<StoredComment, 16> Comments;
213 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
214
215 /// \brief Try to align all stashed comments.
216 void alignComments() {
217 unsigned MinColumn = 0;
218 unsigned MaxColumn = UINT_MAX;
219 comment_iterator Start = Comments.begin();
220 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
221 ++I) {
222 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
223 alignComments(Start, I, MinColumn);
224 MinColumn = I->MinColumn;
225 MaxColumn = I->MaxColumn;
226 Start = I;
227 } else {
228 MinColumn = std::max(MinColumn, I->MinColumn);
229 MaxColumn = std::min(MaxColumn, I->MaxColumn);
230 }
231 }
232 alignComments(Start, Comments.end(), MinColumn);
233 Comments.clear();
234 }
235
236 /// \brief Put all the comments between \p I and \p E into \p Column.
237 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
238 while (I != E) {
239 unsigned Spaces = I->Spaces + Column - I->MinColumn;
240 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper400adc62013-02-08 15:28:42 +0000241 std::string(Spaces, ' '));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000242 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000243 }
244 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000245
246 /// \brief Stores \p Text as the replacement for the whitespace in front of
247 /// \p Tok.
248 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000249 // Don't create a replacement, if it does not change anything.
250 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
251 Tok.WhiteSpaceLength) == Text)
252 return;
253
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000254 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
255 Tok.WhiteSpaceLength, Text));
256 }
257
258 SourceManager &SourceMgr;
259 tooling::Replacements Replaces;
260};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000261
Daniel Jasperf7935112012-12-03 18:12:45 +0000262class UnwrappedLineFormatter {
263public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000264 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000265 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000266 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000267 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000268 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000269 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000270 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000271
Manuel Klimek1abf7892013-01-04 23:34:14 +0000272 /// \brief Formats an \c UnwrappedLine.
273 ///
274 /// \returns The column after the last token in the last line of the
275 /// \c UnwrappedLine.
276 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000277 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000278 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000279 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000280 State.NextToken = &RootToken;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000281 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
282 !Style.BinPackParameters,
283 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000284 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000285 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000286 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000287 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000288 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000289
Manuel Klimek24998102013-01-16 14:55:28 +0000290 DEBUG({
291 DebugTokenState(*State.NextToken);
292 });
293
Daniel Jaspere9de2602012-12-06 09:56:08 +0000294 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000295 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000296
Daniel Jasper4b866272013-02-01 11:00:45 +0000297 // If everything fits on a single line, just put it there.
298 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
299 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000300 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000301 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000302 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000303 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000304
Daniel Jasperacc33662013-02-08 08:22:00 +0000305 // If the ObjC method declaration does not fit on a line, we should format
306 // it with one arg per line.
307 if (Line.Type == LT_ObjCMethodDecl)
308 State.Stack.back().BreakBeforeParameter = true;
309
Daniel Jasper4b866272013-02-01 11:00:45 +0000310 // Find best solution in solution space.
311 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000312 }
313
314private:
Manuel Klimek24998102013-01-16 14:55:28 +0000315 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
316 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000317 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
318 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000319 llvm::errs();
320 }
321
Daniel Jasper337816e2013-01-11 10:22:12 +0000322 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000323 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
324 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000325 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
326 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000327 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000328 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000329
Daniel Jasperf7935112012-12-03 18:12:45 +0000330 /// \brief The position to which a specific parenthesis level needs to be
331 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000332 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000333
Daniel Jaspere9de2602012-12-06 09:56:08 +0000334 /// \brief The position of the last space on each level.
335 ///
336 /// Used e.g. to break like:
337 /// functionCall(Parameter, otherCall(
338 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000339 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000340
Daniel Jaspere9de2602012-12-06 09:56:08 +0000341 /// \brief The position the first "<<" operator encountered on each level.
342 ///
343 /// Used to align "<<" operators. 0 if no such operator has been encountered
344 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000345 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000346
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000347 /// \brief Whether a newline needs to be inserted before the block's closing
348 /// brace.
349 ///
350 /// We only want to insert a newline before the closing brace if there also
351 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000352 bool BreakBeforeClosingBrace;
353
Daniel Jasperca6623b2013-01-28 12:45:14 +0000354 /// \brief The column of a \c ? in a conditional expression;
355 unsigned QuestionColumn;
356
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000357 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
358 /// lines, in this context.
359 bool AvoidBinPacking;
360
361 /// \brief Break after the next comma (or all the commas in this context if
362 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000363 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000364
365 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000366 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000367
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000368 /// \brief The position of the colon in an ObjC method declaration/call.
369 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000370
Daniel Jasper337816e2013-01-11 10:22:12 +0000371 bool operator<(const ParenState &Other) const {
372 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000373 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000374 if (LastSpace != Other.LastSpace)
375 return LastSpace < Other.LastSpace;
376 if (FirstLessLess != Other.FirstLessLess)
377 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000378 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
379 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000380 if (QuestionColumn != Other.QuestionColumn)
381 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000382 if (AvoidBinPacking != Other.AvoidBinPacking)
383 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000384 if (BreakBeforeParameter != Other.BreakBeforeParameter)
385 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000386 if (HasMultiParameterLine != Other.HasMultiParameterLine)
387 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000388 if (ColonPos != Other.ColonPos)
389 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000390 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000391 }
392 };
393
394 /// \brief The current state when indenting a unwrapped line.
395 ///
396 /// As the indenting tries different combinations this is copied by value.
397 struct LineState {
398 /// \brief The number of used columns in the current line.
399 unsigned Column;
400
401 /// \brief The token that needs to be next formatted.
402 const AnnotatedToken *NextToken;
403
Daniel Jasperbbc84152013-01-29 11:27:30 +0000404 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000405 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000406 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000407 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000408
409 /// \brief \c true if this line contains a continued for-loop section.
410 bool LineContainsContinuedForLoopSection;
411
Daniel Jasper400adc62013-02-08 15:28:42 +0000412 /// \brief The level of nesting inside (), [], <> and {}.
413 unsigned ParenLevel;
414
Daniel Jasper40c36c52013-02-18 11:05:07 +0000415 /// \brief The \c ParenLevel at the start of this line.
416 unsigned StartOfLineLevel;
417
Manuel Klimek02f640a2013-02-20 15:25:48 +0000418 /// \brief The start column of the string literal, if we're in a string
419 /// literal sequence, 0 otherwise.
420 unsigned StartOfStringLiteral;
421
Daniel Jasper337816e2013-01-11 10:22:12 +0000422 /// \brief A stack keeping track of properties applying to parenthesis
423 /// levels.
424 std::vector<ParenState> Stack;
425
426 /// \brief Comparison operator to be able to used \c LineState in \c map.
427 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000428 if (NextToken != Other.NextToken)
429 return NextToken < Other.NextToken;
430 if (Column != Other.Column)
431 return Column < Other.Column;
432 if (VariablePos != Other.VariablePos)
433 return VariablePos < Other.VariablePos;
434 if (LineContainsContinuedForLoopSection !=
435 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000436 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000437 if (ParenLevel != Other.ParenLevel)
438 return ParenLevel < Other.ParenLevel;
439 if (StartOfLineLevel != Other.StartOfLineLevel)
440 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000441 if (StartOfStringLiteral != Other.StartOfStringLiteral)
442 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000443 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000444 }
445 };
446
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000447 /// \brief Appends the next token to \p State and updates information
448 /// necessary for indentation.
449 ///
450 /// Puts the token on the current line if \p Newline is \c true and adds a
451 /// line break and necessary indentation otherwise.
452 ///
453 /// If \p DryRun is \c false, also creates and stores the required
454 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000455 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000456 const AnnotatedToken &Current = *State.NextToken;
457 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000458 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000459
Daniel Jasper4b866272013-02-01 11:00:45 +0000460 if (Current.Type == TT_ImplicitStringLiteral) {
461 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
462 State.NextToken->FormatTok.TokenLength;
463 if (State.NextToken->Children.empty())
464 State.NextToken = NULL;
465 else
466 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000467 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000468 }
469
Daniel Jasperf7935112012-12-03 18:12:45 +0000470 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000471 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000472 if (Current.is(tok::r_brace)) {
473 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000474 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000475 State.StartOfStringLiteral != 0) {
476 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000477 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000478 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000479 State.Stack.back().FirstLessLess != 0) {
480 State.Column = State.Stack.back().FirstLessLess;
481 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000482 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000483 Current.is(tok::period) || Current.is(tok::arrow) ||
484 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000485 // Indent and extra 4 spaces after if we know the current expression is
486 // continued. Don't do that on the top level, as we already indent 4
487 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000488 State.Column = std::max(State.Stack.back().LastSpace,
489 State.Stack.back().Indent) + 4;
490 } else if (Current.Type == TT_ConditionalExpr) {
491 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000492 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000493 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
494 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000495 State.Column = State.VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000496 } else if (Previous.ClosesTemplateDeclaration ||
497 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000498 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000499 } else if (Current.Type == TT_ObjCSelectorName) {
500 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
501 State.Column =
502 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
503 } else {
504 State.Column = State.Stack.back().Indent;
505 State.Stack.back().ColonPos =
506 State.Column + Current.FormatTok.TokenLength;
507 }
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000508 } else if (Previous.Type == TT_ObjCMethodExpr ||
509 Current.Type == TT_StartOfName) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000510 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000511 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000512 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000513 }
514
Daniel Jasper54a86022013-02-15 11:07:25 +0000515 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000516 State.Stack.back().BreakBeforeParameter = true;
517 if ((Previous.is(tok::comma) || Previous.is(tok::semi)) &&
518 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000519 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000520
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000521 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000522 unsigned NewLines = 1;
523 if (Current.Type == TT_LineComment)
524 NewLines =
525 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
526 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000527 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000528 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000529 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000530 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000531 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000532 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000533 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000534
Daniel Jasper400adc62013-02-08 15:28:42 +0000535 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000536 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000537 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000538 State.Stack.back().Indent += 2;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000539
540 // Any break on this level means that the parent level has been broken
541 // and we need to avoid bin packing there.
542 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
543 State.Stack[i].BreakBeforeParameter = true;
544 }
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000545 if (Current.is(tok::period) || Current.is(tok::arrow))
546 State.Stack.back().BreakBeforeParameter = true;
547
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000548 // If we break after {, we should also break before the corresponding }.
549 if (Previous.is(tok::l_brace))
550 State.Stack.back().BreakBeforeClosingBrace = true;
551
552 if (State.Stack.back().AvoidBinPacking) {
553 // If we are breaking after '(', '{', '<', this is not bin packing
554 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000555 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000556 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
557 Line.MustBeDeclaration))
558 State.Stack.back().BreakBeforeParameter = true;
559 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000560 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000561 // FIXME: Put VariablePos into ParenState and remove second part of if().
562 if (Current.is(tok::equal) &&
563 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000564 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000565
Daniel Jaspereef30492013-02-11 12:36:37 +0000566 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000567
Daniel Jasperf7935112012-12-03 18:12:45 +0000568 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000569 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000570
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000571 if (Current.Type == TT_ObjCSelectorName &&
572 State.Stack.back().ColonPos == 0) {
573 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
574 State.Column + Spaces + Current.FormatTok.TokenLength)
575 State.Stack.back().ColonPos =
576 State.Stack.back().Indent + Current.LongestObjCSelectorName;
577 else
578 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000579 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000580 }
581
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000582 if (Current.Type != TT_LineComment &&
583 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
584 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000585 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000586 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000587 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000588
Daniel Jaspere9de2602012-12-06 09:56:08 +0000589 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000590 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
591 // Treat the condition inside an if as if it was a second function
592 // parameter, i.e. let nested calls have an indent of 4.
593 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000594 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000595 // Top-level spaces are exempt as that mostly leads to better results.
596 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000597 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000598 Previous.Type == TT_ConditionalExpr ||
599 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000600 getPrecedence(Previous) != prec::Assignment)
601 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000602 else if (Previous.Type == TT_InheritanceColon)
603 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000604 else if (Previous.ParameterCount > 1 &&
605 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000606 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000607 Previous.Type == TT_TemplateOpener))
608 // If this function has multiple parameters, indent nested calls from
609 // the start of the first parameter.
610 State.Stack.back().LastSpace = State.Column;
Daniel Jaspere53beb22013-02-18 13:52:06 +0000611 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
612 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
613 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000614 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000615
Manuel Klimek1998ea22013-02-20 10:15:13 +0000616 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000617 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000618
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000619 /// \brief Mark the next token as consumed in \p State and modify its stacks
620 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000621 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000622 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000623 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000624
Daniel Jaspereead02b2013-02-14 08:42:54 +0000625 if (Current.Type == TT_InheritanceColon)
626 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000627 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
628 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000629 if (Current.is(tok::question))
630 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000631 if (Current.Type == TT_CtorInitializerColon) {
632 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
633 State.Stack.back().AvoidBinPacking = true;
634 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000635 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000636
Daniel Jasper400adc62013-02-08 15:28:42 +0000637 // Insert scopes created by fake parenthesis.
638 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
639 ParenState NewParenState = State.Stack.back();
640 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000641 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000642 State.Stack.push_back(NewParenState);
643 }
644
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000645 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000646 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000647 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
648 Current.is(tok::l_brace) ||
649 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000650 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000651 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000652 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000653 NewIndent = 2 + State.Stack.back().LastSpace;
654 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000655 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000656 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasperead41b62013-02-28 09:39:12 +0000657 AvoidBinPacking =
658 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000659 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000660 State.Stack.push_back(
661 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
662 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000663 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000664 }
665
Daniel Jasperacc33662013-02-08 08:22:00 +0000666 // If this '[' opens an ObjC call, determine whether all parameters fit into
667 // one line and put one per line if they don't.
668 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
669 Current.MatchingParen != NULL) {
670 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
671 State.Stack.back().BreakBeforeParameter = true;
672 }
673
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000674 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000675 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000676 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
677 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
678 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000679 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000680 --State.ParenLevel;
681 }
682
683 // Remove scopes created by fake parenthesis.
684 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
685 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000686 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000687
Manuel Klimek0c915712013-02-20 15:32:58 +0000688 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000689 State.StartOfStringLiteral = State.Column;
690 } else if (Current.isNot(tok::comment)) {
691 State.StartOfStringLiteral = 0;
692 }
693
Manuel Klimek1998ea22013-02-20 10:15:13 +0000694 State.Column += Current.FormatTok.TokenLength;
695
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000696 if (State.NextToken->Children.empty())
697 State.NextToken = NULL;
698 else
699 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000700
Manuel Klimek1998ea22013-02-20 10:15:13 +0000701 return breakProtrudingToken(Current, State, DryRun);
702 }
703
704 /// \brief If the current token sticks out over the end of the line, break
705 /// it if possible.
706 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
707 bool DryRun) {
708 if (Current.isNot(tok::string_literal))
709 return 0;
710
711 unsigned Penalty = 0;
712 unsigned TailOffset = 0;
713 unsigned TailLength = Current.FormatTok.TokenLength;
714 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
715 unsigned OffsetFromStart = 0;
716 while (StartColumn + TailLength > getColumnLimit()) {
717 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
718 TailOffset, TailLength);
719 StringRef::size_type SplitPoint =
720 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
721 if (SplitPoint == StringRef::npos)
722 break;
723 assert(SplitPoint != 0);
724 // +2, because 'Text' starts after the opening quotes, and does not
725 // include the closing quote we need to insert.
726 unsigned WhitespaceStartColumn =
727 StartColumn + OffsetFromStart + SplitPoint + 2;
728 State.Stack.back().LastSpace = StartColumn;
729 if (!DryRun) {
730 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
731 Line.InPPDirective, StartColumn,
732 WhitespaceStartColumn, Style);
733 }
734 TailOffset += SplitPoint + 1;
735 TailLength -= SplitPoint + 1;
736 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000737 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000738 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
739 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000740 }
741 State.Column = StartColumn + TailLength;
742 return Penalty;
743 }
744
745 StringRef::size_type
746 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
747 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
748 return Text.rfind(' ', Offset);
Daniel Jasperf7935112012-12-03 18:12:45 +0000749 }
750
Daniel Jasper2df93312013-01-09 10:16:05 +0000751 unsigned getColumnLimit() {
752 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
753 }
754
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000755 /// \brief An edge in the solution space from \c Previous->State to \c State,
756 /// inserting a newline dependent on the \c NewLine.
757 struct StateNode {
758 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000759 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000760 LineState State;
761 bool NewLine;
762 StateNode *Previous;
763 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000764
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000765 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
766 ///
767 /// In case of equal penalties, we want to prefer states that were inserted
768 /// first. During state generation we make sure that we insert states first
769 /// that break the line as late as possible.
770 typedef std::pair<unsigned, unsigned> OrderedPenalty;
771
772 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
773 /// \c State has the given \c OrderedPenalty.
774 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
775
776 /// \brief The BFS queue type.
777 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
778 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000779
780 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000782 /// This implements a variant of Dijkstra's algorithm on the graph that spans
783 /// the solution space (\c LineStates are the nodes). The algorithm tries to
784 /// find the shortest path (the one with lowest penalty) from \p InitialState
785 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000786 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000787 std::set<LineState> Seen;
788
Daniel Jasper4b866272013-02-01 11:00:45 +0000789 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000790 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000791 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
792 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
793 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000794
795 // While not empty, take first element and follow edges.
796 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000797 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000798 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000799 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000800 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000801 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000802 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000803 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000804
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000805 if (!Seen.insert(Node->State).second)
806 // State already examined with lower penalty.
807 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000808
Manuel Klimekaf491072013-02-13 10:54:19 +0000809 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
810 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000811 }
812
813 if (Queue.empty())
814 // We were unable to find a solution, do nothing.
815 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000816 return 0;
817
Daniel Jasper4b866272013-02-01 11:00:45 +0000818 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000819 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000820 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000821
Daniel Jasper4b866272013-02-01 11:00:45 +0000822 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000823 return Queue.top().second->State.Column;
824 }
825
826 void reconstructPath(LineState &State, StateNode *Current) {
827 // FIXME: This recursive implementation limits the possible number
828 // of tokens per line if compiled into a binary with small stack space.
829 // To become more independent of stack frame limitations we would need
830 // to also change the TokenAnnotator.
831 if (Current->Previous == NULL)
832 return;
833 reconstructPath(State, Current->Previous);
834 DEBUG({
835 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000836 llvm::errs()
837 << "Penalty for splitting before "
838 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
839 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000840 }
841 });
842 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000843 }
844
Manuel Klimekaf491072013-02-13 10:54:19 +0000845 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000846 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000847 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000848 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000849 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
850 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000851 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000852 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000853 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000854 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000855 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000856 Penalty += PreviousNode->State.NextToken->SplitPenalty;
857
858 StateNode *Node = new (Allocator.Allocate())
859 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000860 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000861 if (Node->State.Column > getColumnLimit()) {
862 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000863 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000864 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000865
866 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
867 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000868 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000869
Daniel Jasper4b866272013-02-01 11:00:45 +0000870 /// \brief Returns \c true, if a line break after \p State is allowed.
871 bool canBreak(const LineState &State) {
872 if (!State.NextToken->CanBreakBefore &&
873 !(State.NextToken->is(tok::r_brace) &&
874 State.Stack.back().BreakBeforeClosingBrace))
875 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000876 // This prevents breaks like:
877 // ...
878 // SomeParameter, OtherParameter).DoSomething(
879 // ...
880 // As they hide "DoSomething" and generally bad for readability.
881 if (State.NextToken->Parent->is(tok::l_paren) &&
882 State.ParenLevel <= State.StartOfLineLevel)
883 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000884 // Trying to insert a parameter on a new line if there are already more than
885 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000886 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000887 State.Stack.back().AvoidBinPacking)
888 return false;
889 return true;
890 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000891
Daniel Jasper4b866272013-02-01 11:00:45 +0000892 /// \brief Returns \c true, if a line break after \p State is mandatory.
893 bool mustBreak(const LineState &State) {
894 if (State.NextToken->MustBreakBefore)
895 return true;
896 if (State.NextToken->is(tok::r_brace) &&
897 State.Stack.back().BreakBeforeClosingBrace)
898 return true;
899 if (State.NextToken->Parent->is(tok::semi) &&
900 State.LineContainsContinuedForLoopSection)
901 return true;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000902 if ((State.NextToken->Parent->is(tok::comma) ||
903 State.NextToken->Parent->is(tok::semi) ||
904 State.NextToken->is(tok::question) ||
905 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000906 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000907 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000908 State.NextToken->isNot(tok::r_paren) &&
909 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000910 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000911 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
912 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000913 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000914 State.NextToken->LongestObjCSelectorName == 0 &&
915 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000916 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000917 if ((State.NextToken->Type == TT_CtorInitializerColon ||
918 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000919 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000920 return true;
921 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000922 }
923
Daniel Jasperf7935112012-12-03 18:12:45 +0000924 FormatStyle Style;
925 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000926 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000927 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000928 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000929 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000930
931 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
932 QueueType Queue;
933 // Increasing count of \c StateNode items we have created. This is used
934 // to create a deterministic order independent of the container.
935 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000936};
937
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000938class LexerBasedFormatTokenSource : public FormatTokenSource {
939public:
940 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000941 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000942 IdentTable(Lex.getLangOpts()) {
943 Lex.SetKeepWhitespaceMode(true);
944 }
945
946 virtual FormatToken getNextToken() {
947 if (GreaterStashed) {
948 FormatTok.NewlinesBefore = 0;
949 FormatTok.WhiteSpaceStart =
950 FormatTok.Tok.getLocation().getLocWithOffset(1);
951 FormatTok.WhiteSpaceLength = 0;
952 GreaterStashed = false;
953 return FormatTok;
954 }
955
956 FormatTok = FormatToken();
957 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000958 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000959 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000960 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
961 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000962
963 // Consume and record whitespace until we find a significant token.
964 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000965 unsigned Newlines = Text.count('\n');
966 unsigned EscapedNewlines = Text.count("\\\n");
967 FormatTok.NewlinesBefore += Newlines;
968 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000969 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
970
971 if (FormatTok.Tok.is(tok::eof))
972 return FormatTok;
973 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000974 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000975 }
Manuel Klimekef920692013-01-07 07:56:50 +0000976
977 // Now FormatTok is the next non-whitespace token.
978 FormatTok.TokenLength = Text.size();
979
Manuel Klimek1abf7892013-01-04 23:34:14 +0000980 // In case the token starts with escaped newlines, we want to
981 // take them into account as whitespace - this pattern is quite frequent
982 // in macro definitions.
983 // FIXME: What do we want to do with other escaped spaces, and escaped
984 // spaces or newlines in the middle of tokens?
985 // FIXME: Add a more explicit test.
986 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000987 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000988 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000989 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000990 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000991 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000992 }
993
994 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000995 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000996 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000997 FormatTok.Tok.setKind(Info.getTokenID());
998 }
999
1000 if (FormatTok.Tok.is(tok::greatergreater)) {
1001 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001002 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001003 GreaterStashed = true;
1004 }
1005
1006 return FormatTok;
1007 }
1008
Nico Weber29f9dea2013-02-11 15:32:15 +00001009 IdentifierTable &getIdentTable() { return IdentTable; }
1010
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001011private:
1012 FormatToken FormatTok;
1013 bool GreaterStashed;
1014 Lexer &Lex;
1015 SourceManager &SourceMgr;
1016 IdentifierTable IdentTable;
1017
1018 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001019 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001020 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1021 Tok.getLength());
1022 }
1023};
1024
Daniel Jasperf7935112012-12-03 18:12:45 +00001025class Formatter : public UnwrappedLineConsumer {
1026public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001027 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1028 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001029 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001030 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001031 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001032
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001033 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001034
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001035 void deriveLocalStyle() {
1036 unsigned CountBoundToVariable = 0;
1037 unsigned CountBoundToType = 0;
1038 bool HasCpp03IncompatibleFormat = false;
1039 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1040 if (AnnotatedLines[i].First.Children.empty())
1041 continue;
1042 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1043 while (!Tok->Children.empty()) {
1044 if (Tok->Type == TT_PointerOrReference) {
1045 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1046 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1047 if (SpacesBefore && !SpacesAfter)
1048 ++CountBoundToVariable;
1049 else if (!SpacesBefore && SpacesAfter)
1050 ++CountBoundToType;
1051 }
1052
Daniel Jasper400adc62013-02-08 15:28:42 +00001053 if (Tok->Type == TT_TemplateCloser &&
1054 Tok->Parent->Type == TT_TemplateCloser &&
1055 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001056 HasCpp03IncompatibleFormat = true;
1057 Tok = &Tok->Children[0];
1058 }
1059 }
1060 if (Style.DerivePointerBinding) {
1061 if (CountBoundToType > CountBoundToVariable)
1062 Style.PointerBindsToType = true;
1063 else if (CountBoundToType < CountBoundToVariable)
1064 Style.PointerBindsToType = false;
1065 }
1066 if (Style.Standard == FormatStyle::LS_Auto) {
1067 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1068 : FormatStyle::LS_Cpp03;
1069 }
1070 }
1071
Daniel Jasperf7935112012-12-03 18:12:45 +00001072 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001073 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001074 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001075 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001076 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +00001077 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1078 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001079 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001080 Annotator.annotate(AnnotatedLines[i]);
1081 }
1082 deriveLocalStyle();
1083 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1084 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001085 }
Manuel Klimekb95f5452013-02-08 17:38:27 +00001086 std::vector<int> IndentForLevel;
Daniel Jasper24570102013-02-14 09:58:41 +00001087 bool PreviousLineWasTouched = false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001088 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1089 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001090 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001091 const AnnotatedLine &TheLine = *I;
Daniel Jasper24570102013-02-14 09:58:41 +00001092 int Offset = getIndentOffset(TheLine.First);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001093 while (IndentForLevel.size() <= TheLine.Level)
1094 IndentForLevel.push_back(-1);
1095 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper55d7ba62013-02-18 13:08:03 +00001096 bool WasMoved =
1097 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1098 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasper24570102013-02-14 09:58:41 +00001099 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001100 unsigned Indent = LevelIndent;
1101 if (static_cast<int>(Indent) + Offset >= 0)
1102 Indent += Offset;
1103 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1104 StructuralError) {
1105 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1106 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1107 } else {
1108 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1109 PreviousEndOfLineColumn);
1110 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001111 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001112 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001113 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001114 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001115 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimekb95f5452013-02-08 17:38:27 +00001116 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001117 PreviousLineWasTouched = true;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001118 } else {
Daniel Jasper22045622013-02-12 16:51:23 +00001119 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1120 TheLine.First.FormatTok.IsFirst) {
1121 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1122 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1123 unsigned LevelIndent = Indent;
1124 if (static_cast<int>(LevelIndent) - Offset >= 0)
1125 LevelIndent -= Offset;
1126 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001127
1128 // Remove trailing whitespace of the previous line if it was touched.
1129 if (PreviousLineWasTouched)
1130 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1131 PreviousEndOfLineColumn);
Daniel Jasper22045622013-02-12 16:51:23 +00001132 }
Daniel Jasper24570102013-02-14 09:58:41 +00001133 // If we did not reformat this unwrapped line, the column at the end of
1134 // the last token is unchanged - thus, we can calculate the end of the
1135 // last token.
1136 PreviousEndOfLineColumn =
1137 SourceMgr.getSpellingColumnNumber(
1138 TheLine.Last->FormatTok.Tok.getLocation()) +
1139 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1140 SourceMgr, Lex.getLangOpts()) - 1;
1141 PreviousLineWasTouched = false;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001142 }
1143 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001144 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001145 }
1146
1147private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001148 /// \brief Get the indent of \p Level from \p IndentForLevel.
1149 ///
1150 /// \p IndentForLevel must contain the indent for the level \c l
1151 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1152 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001153 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001154 if (IndentForLevel[Level] != -1)
1155 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001156 if (Level == 0)
1157 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001158 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001159 }
1160
1161 /// \brief Get the offset of the line relatively to the level.
1162 ///
1163 /// For example, 'public:' labels in classes are offset by 1 or 2
1164 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001165 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001166 bool IsAccessModifier = false;
1167 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1168 RootToken.is(tok::kw_private))
1169 IsAccessModifier = true;
1170 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1171 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1172 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1173 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1174 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1175 IsAccessModifier = true;
1176
1177 if (IsAccessModifier)
1178 return Style.AccessModifierOffset;
1179 return 0;
1180 }
1181
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001182 /// \brief Tries to merge lines into one.
1183 ///
1184 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1185 /// if possible; note that \c I will be incremented when lines are merged.
1186 ///
1187 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001188 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001189 std::vector<AnnotatedLine>::iterator &I,
1190 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001191 // We can never merge stuff if there are trailing line comments.
1192 if (I->Last->Type == TT_LineComment)
1193 return;
1194
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001195 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1196 // If we already exceed the column limit, we set 'Limit' to 0. The different
1197 // tryMerge..() functions can then decide whether to still do merging.
1198 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001199
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001200 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001201 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001202
Daniel Jasper25837aa2013-01-14 14:14:23 +00001203 if (I->Last->is(tok::l_brace)) {
1204 tryMergeSimpleBlock(I, E, Limit);
1205 } else if (I->First.is(tok::kw_if)) {
1206 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001207 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1208 I->First.FormatTok.IsFirst)) {
1209 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001210 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001211 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001212 }
1213
Daniel Jasper39825ea2013-01-14 15:40:57 +00001214 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1215 std::vector<AnnotatedLine>::iterator E,
1216 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001217 if (Limit == 0)
1218 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001219 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001220 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1221 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001222 if (I + 2 != E && (I + 2)->InPPDirective &&
1223 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1224 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001225 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001226 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001227 join(Line, *(++I));
1228 }
1229
Daniel Jasper25837aa2013-01-14 14:14:23 +00001230 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1231 std::vector<AnnotatedLine>::iterator E,
1232 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001233 if (Limit == 0)
1234 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001235 if (!Style.AllowShortIfStatementsOnASingleLine)
1236 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001237 if ((I + 1)->InPPDirective != I->InPPDirective ||
1238 ((I + 1)->InPPDirective &&
1239 (I + 1)->First.FormatTok.HasUnescapedNewline))
1240 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001241 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001242 if (Line.Last->isNot(tok::r_paren))
1243 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001244 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001245 return;
1246 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1247 return;
1248 // Only inline simple if's (no nested if or else).
1249 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1250 return;
1251 join(Line, *(++I));
1252 }
1253
1254 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001255 std::vector<AnnotatedLine>::iterator E,
1256 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001257 // First, check that the current line allows merging. This is the case if
1258 // we're not in a control flow statement and the last token is an opening
1259 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001260 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001261 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001262 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1263 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1264 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1265 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001266 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001267 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1268 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001269 if (!AllowedTokens)
1270 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001271
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001272 AnnotatedToken *Tok = &(I + 1)->First;
1273 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001274 !Tok->MustBreakBefore) {
1275 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001276 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001277 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001278 join(Line, *(I + 1));
1279 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001280 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001281 // Check that we still have three lines and they fit into the limit.
1282 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1283 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001284 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001285
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001286 // Second, check that the next line does not contain any braces - if it
1287 // does, readability declines when putting it into a single line.
1288 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1289 return;
1290 do {
1291 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1292 return;
1293 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1294 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001295
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001296 // Last, check that the third line contains a single closing brace.
1297 Tok = &(I + 2)->First;
1298 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1299 Tok->MustBreakBefore)
1300 return;
1301
1302 join(Line, *(I + 1));
1303 join(Line, *(I + 2));
1304 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001305 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001306 }
1307
1308 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1309 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001310 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1311 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001312 }
1313
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001314 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001315 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001316 A.Last->Children.push_back(B.First);
1317 while (!A.Last->Children.empty()) {
1318 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001319 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001320 A.Last = &A.Last->Children[0];
1321 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001322 }
1323
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001324 bool touchesRanges(const AnnotatedLine &TheLine) {
1325 const FormatToken *First = &TheLine.First.FormatTok;
1326 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001327 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001328 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001329 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001330 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1331 Ranges[i].getBegin()) &&
1332 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1333 LineRange.getBegin()))
1334 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001335 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001336 return false;
1337 }
1338
1339 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001340 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001341 }
1342
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001343 /// \brief Add a new line and the required indent before the first Token
1344 /// of the \c UnwrappedLine if there was no structural parsing error.
1345 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001346 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1347 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001348 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001349
Daniel Jasperbbc84152013-01-29 11:27:30 +00001350 unsigned Newlines =
1351 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001352 if (Newlines == 0 && !Tok.IsFirst)
1353 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001354
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001355 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001356 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001357 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001358 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1359 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001360 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001361 }
1362
Alexander Kornienko116ba682013-01-14 11:34:14 +00001363 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001364 FormatStyle Style;
1365 Lexer &Lex;
1366 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001367 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001368 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001369 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001370 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001371};
1372
Daniel Jasperbbc84152013-01-29 11:27:30 +00001373tooling::Replacements
1374reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1375 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001376 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001377 OwningPtr<DiagnosticConsumer> DiagPrinter;
1378 if (DiagClient == 0) {
1379 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1380 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1381 DiagClient = DiagPrinter.get();
1382 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001383 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001384 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001385 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001386 Diagnostics.setSourceManager(&SourceMgr);
1387 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001388 return formatter.format();
1389}
1390
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001391LangOptions getFormattingLangOpts() {
1392 LangOptions LangOpts;
1393 LangOpts.CPlusPlus = 1;
1394 LangOpts.CPlusPlus11 = 1;
1395 LangOpts.Bool = 1;
1396 LangOpts.ObjC1 = 1;
1397 LangOpts.ObjC2 = 1;
1398 return LangOpts;
1399}
1400
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001401} // namespace format
1402} // namespace clang