blob: bbebec3652f94417a0a7d1acd5cd41bf902e7b04 [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 Klimek24998102013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000027#include <string>
28
Manuel Klimek24998102013-01-16 14:55:28 +000029// Uncomment to get debug output from tests:
30// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
31
Daniel Jasperf7935112012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperf7935112012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
39 LLVMStyle.PointerAndReferenceBindToType = false;
40 LLVMStyle.AccessModifierOffset = -2;
41 LLVMStyle.SplitTemplateClosingGreater = true;
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 Jasperd36ef5e2013-01-28 15:40:20 +000046 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
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;
58 GoogleStyle.PointerAndReferenceBindToType = true;
59 GoogleStyle.AccessModifierOffset = -1;
60 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000061 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000062 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000063 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000064 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000065 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
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 Jasperf7935112012-12-03 18:12:45 +000070 return GoogleStyle;
71}
72
Daniel Jasper1b750ed2013-01-14 16:24:39 +000073FormatStyle getChromiumStyle() {
74 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000075 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper17fdaa42013-01-29 15:19:38 +000076 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000077 return ChromiumStyle;
78}
79
Daniel Jasperaa701fa2013-01-18 08:44:07 +000080/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +000081///
Daniel Jasperaa701fa2013-01-18 08:44:07 +000082/// This includes special handling for certain constructs, e.g. the alignment of
83/// trailing line comments.
84class WhitespaceManager {
85public:
86 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
87
88 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
89 /// each \c AnnotatedToken.
90 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
91 unsigned Spaces, unsigned WhitespaceStartColumn,
92 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +000093 // 2+ newlines mean an empty line separating logic scopes.
94 if (NewLines >= 2)
95 alignComments();
96
97 // Align line comments if they are trailing or if they continue other
98 // trailing comments.
99 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000100 (Tok.Parent != NULL || !Comments.empty())) {
101 if (Style.ColumnLimit >=
102 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
103 Comments.push_back(StoredComment());
104 Comments.back().Tok = Tok.FormatTok;
105 Comments.back().Spaces = Spaces;
106 Comments.back().NewLines = NewLines;
107 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000108 Comments.back().MaxColumn =
109 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000110 return;
111 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000112 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000113
114 // If this line does not have a trailing comment, align the stored comments.
115 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
116 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000117 storeReplacement(Tok.FormatTok,
118 std::string(NewLines, '\n') + std::string(Spaces, ' '));
119 }
120
121 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
122 /// backslashes to escape newlines inside a preprocessor directive.
123 ///
124 /// This function and \c replaceWhitespace have the same behavior if
125 /// \c Newlines == 0.
126 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
127 unsigned Spaces, unsigned WhitespaceStartColumn,
128 const FormatStyle &Style) {
129 std::string NewLineText;
130 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000131 unsigned Offset =
132 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000133 for (unsigned i = 0; i < NewLines; ++i) {
134 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
135 NewLineText += "\\\n";
136 Offset = 0;
137 }
138 }
139 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
140 }
141
142 /// \brief Returns all the \c Replacements created during formatting.
143 const tooling::Replacements &generateReplacements() {
144 alignComments();
145 return Replaces;
146 }
147
148private:
149 /// \brief Structure to store a comment for later layout and alignment.
150 struct StoredComment {
151 FormatToken Tok;
152 unsigned MinColumn;
153 unsigned MaxColumn;
154 unsigned NewLines;
155 unsigned Spaces;
156 };
157 SmallVector<StoredComment, 16> Comments;
158 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
159
160 /// \brief Try to align all stashed comments.
161 void alignComments() {
162 unsigned MinColumn = 0;
163 unsigned MaxColumn = UINT_MAX;
164 comment_iterator Start = Comments.begin();
165 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
166 ++I) {
167 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
168 alignComments(Start, I, MinColumn);
169 MinColumn = I->MinColumn;
170 MaxColumn = I->MaxColumn;
171 Start = I;
172 } else {
173 MinColumn = std::max(MinColumn, I->MinColumn);
174 MaxColumn = std::min(MaxColumn, I->MaxColumn);
175 }
176 }
177 alignComments(Start, Comments.end(), MinColumn);
178 Comments.clear();
179 }
180
181 /// \brief Put all the comments between \p I and \p E into \p Column.
182 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
183 while (I != E) {
184 unsigned Spaces = I->Spaces + Column - I->MinColumn;
185 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
186 std::string(Spaces, ' '));
187 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000188 }
189 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000190
191 /// \brief Stores \p Text as the replacement for the whitespace in front of
192 /// \p Tok.
193 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000194 // Don't create a replacement, if it does not change anything.
195 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
196 Tok.WhiteSpaceLength) == Text)
197 return;
198
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000199 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
200 Tok.WhiteSpaceLength, Text));
201 }
202
203 SourceManager &SourceMgr;
204 tooling::Replacements Replaces;
205};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000206
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000207static bool isTrailingComment(const AnnotatedToken &Tok) {
208 return Tok.is(tok::comment) &&
209 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
210}
211
Daniel Jasperf7935112012-12-03 18:12:45 +0000212class UnwrappedLineFormatter {
213public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000214 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000215 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000216 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000217 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000218 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000219 FirstIndent(FirstIndent), RootToken(RootToken),
220 Whitespaces(Whitespaces) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000221 }
222
Manuel Klimek1abf7892013-01-04 23:34:14 +0000223 /// \brief Formats an \c UnwrappedLine.
224 ///
225 /// \returns The column after the last token in the last line of the
226 /// \c UnwrappedLine.
227 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000228 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000229 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000230 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000231 State.NextToken = &RootToken;
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000232 State.Stack.push_back(
233 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
234 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000235 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000236 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000237
Manuel Klimek24998102013-01-16 14:55:28 +0000238 DEBUG({
239 DebugTokenState(*State.NextToken);
240 });
241
Daniel Jaspere9de2602012-12-06 09:56:08 +0000242 // The first token has already been indented and thus consumed.
243 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000244
Daniel Jasper4b866272013-02-01 11:00:45 +0000245 // If everything fits on a single line, just put it there.
246 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
247 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000248 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000249 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000250 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000251 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000252
253 // Find best solution in solution space.
254 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000255 }
256
257private:
Manuel Klimek24998102013-01-16 14:55:28 +0000258 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
259 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000260 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
261 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000262 llvm::errs();
263 }
264
Daniel Jasper337816e2013-01-11 10:22:12 +0000265 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000266 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
267 bool HasMultiParameterLine)
Daniel Jaspera836b902013-01-23 16:58:21 +0000268 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000269 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000270 AvoidBinPacking(AvoidBinPacking), BreakAfterComma(false),
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000271 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000272 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000273
Daniel Jasperf7935112012-12-03 18:12:45 +0000274 /// \brief The position to which a specific parenthesis level needs to be
275 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000276 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000277
Daniel Jaspere9de2602012-12-06 09:56:08 +0000278 /// \brief The position of the last space on each level.
279 ///
280 /// Used e.g. to break like:
281 /// functionCall(Parameter, otherCall(
282 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000283 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000284
Daniel Jaspera836b902013-01-23 16:58:21 +0000285 /// \brief This is the column of the first token after an assignment.
286 unsigned AssignmentColumn;
287
Daniel Jaspere9de2602012-12-06 09:56:08 +0000288 /// \brief The position the first "<<" operator encountered on each level.
289 ///
290 /// Used to align "<<" operators. 0 if no such operator has been encountered
291 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000292 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000293
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000294 /// \brief Whether a newline needs to be inserted before the block's closing
295 /// brace.
296 ///
297 /// We only want to insert a newline before the closing brace if there also
298 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000299 bool BreakBeforeClosingBrace;
300
Daniel Jasperca6623b2013-01-28 12:45:14 +0000301 /// \brief The column of a \c ? in a conditional expression;
302 unsigned QuestionColumn;
303
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000304 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
305 /// lines, in this context.
306 bool AvoidBinPacking;
307
308 /// \brief Break after the next comma (or all the commas in this context if
309 /// \c AvoidBinPacking is \c true).
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000310 bool BreakAfterComma;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000311
312 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000313 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000314
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000315 /// \brief The position of the colon in an ObjC method declaration/call.
316 unsigned ColonPos;
317
Daniel Jasper337816e2013-01-11 10:22:12 +0000318 bool operator<(const ParenState &Other) const {
319 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000320 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000321 if (LastSpace != Other.LastSpace)
322 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000323 if (AssignmentColumn != Other.AssignmentColumn)
324 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000325 if (FirstLessLess != Other.FirstLessLess)
326 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000327 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
328 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000329 if (QuestionColumn != Other.QuestionColumn)
330 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000331 if (AvoidBinPacking != Other.AvoidBinPacking)
332 return AvoidBinPacking;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000333 if (BreakAfterComma != Other.BreakAfterComma)
334 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000335 if (HasMultiParameterLine != Other.HasMultiParameterLine)
336 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000337 if (ColonPos != Other.ColonPos)
338 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000339 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000340 }
341 };
342
343 /// \brief The current state when indenting a unwrapped line.
344 ///
345 /// As the indenting tries different combinations this is copied by value.
346 struct LineState {
347 /// \brief The number of used columns in the current line.
348 unsigned Column;
349
350 /// \brief The token that needs to be next formatted.
351 const AnnotatedToken *NextToken;
352
Daniel Jasperbbc84152013-01-29 11:27:30 +0000353 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000354 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000355 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000356 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000357
358 /// \brief \c true if this line contains a continued for-loop section.
359 bool LineContainsContinuedForLoopSection;
360
Daniel Jasper337816e2013-01-11 10:22:12 +0000361 /// \brief A stack keeping track of properties applying to parenthesis
362 /// levels.
363 std::vector<ParenState> Stack;
364
365 /// \brief Comparison operator to be able to used \c LineState in \c map.
366 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000367 if (Other.NextToken != NextToken)
368 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000369 if (Other.Column != Column)
370 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000371 if (Other.VariablePos != VariablePos)
372 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000373 if (Other.LineContainsContinuedForLoopSection !=
374 LineContainsContinuedForLoopSection)
375 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000376 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000377 }
378 };
379
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000380 /// \brief Appends the next token to \p State and updates information
381 /// necessary for indentation.
382 ///
383 /// Puts the token on the current line if \p Newline is \c true and adds a
384 /// line break and necessary indentation otherwise.
385 ///
386 /// If \p DryRun is \c false, also creates and stores the required
387 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000388 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000389 const AnnotatedToken &Current = *State.NextToken;
390 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000391 assert(State.Stack.size());
392 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000393
Daniel Jasper4b866272013-02-01 11:00:45 +0000394 if (Current.Type == TT_ImplicitStringLiteral) {
395 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
396 State.NextToken->FormatTok.TokenLength;
397 if (State.NextToken->Children.empty())
398 State.NextToken = NULL;
399 else
400 State.NextToken = &State.NextToken->Children[0];
401 return;
402 }
403
Daniel Jasperf7935112012-12-03 18:12:45 +0000404 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000405 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000406 if (Current.is(tok::r_brace)) {
407 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000408 } else if (Current.is(tok::string_literal) &&
409 Previous.is(tok::string_literal)) {
410 State.Column = State.Column - Previous.FormatTok.TokenLength;
411 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000412 State.Stack[ParenLevel].FirstLessLess != 0) {
413 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000414 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000415 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000416 Current.is(tok::period) || Current.is(tok::arrow) ||
417 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000418 // Indent and extra 4 spaces after if we know the current expression is
419 // continued. Don't do that on the top level, as we already indent 4
420 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000421 State.Column = std::max(State.Stack.back().LastSpace,
422 State.Stack.back().Indent) + 4;
423 } else if (Current.Type == TT_ConditionalExpr) {
424 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000425 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
426 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
427 ParenLevel == 0)) {
428 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000429 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
430 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000432 } else if (Previous.Type == TT_BinaryOperator &&
433 State.Stack.back().AssignmentColumn != 0) {
434 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000435 } else if (Current.Type == TT_ObjCSelectorName) {
436 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
437 State.Column =
438 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
439 } else {
440 State.Column = State.Stack.back().Indent;
441 State.Stack.back().ColonPos =
442 State.Column + Current.FormatTok.TokenLength;
443 }
444 } else if (Previous.Type == TT_ObjCMethodExpr) {
445 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000446 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000447 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000448 }
449
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000450 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
451 State.Stack.back().BreakAfterComma = false;
452
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000453 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000454 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000455
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000456 if (!DryRun) {
457 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000458 Whitespaces.replaceWhitespace(Current, 1, State.Column,
459 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000460 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000461 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
462 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000463 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000464
Daniel Jasper337816e2013-01-11 10:22:12 +0000465 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000466 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000468 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000469 if (Current.is(tok::equal) &&
470 (RootToken.is(tok::kw_for) || ParenLevel == 0))
471 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000472
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000473 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
474 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000475 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000476
Daniel Jasperf7935112012-12-03 18:12:45 +0000477 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000478 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000479
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000480 if (Current.Type == TT_ObjCSelectorName &&
481 State.Stack.back().ColonPos == 0) {
482 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
483 State.Column + Spaces + Current.FormatTok.TokenLength)
484 State.Stack.back().ColonPos =
485 State.Stack.back().Indent + Current.LongestObjCSelectorName;
486 else
487 State.Stack.back().ColonPos =
488 State.Column + Spaces + Current.LongestObjCSelectorName;
489 }
490
Daniel Jasperbcab4302013-01-09 10:40:23 +0000491 // FIXME: Do we need to do this for assignments nested in other
492 // expressions?
493 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000494 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000495 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000496 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000497 if (Current.Type != TT_LineComment &&
498 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
499 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000500 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000501 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000502 State.Stack[ParenLevel].HasMultiParameterLine = true;
503
Daniel Jaspere9de2602012-12-06 09:56:08 +0000504 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000505 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
506 // Treat the condition inside an if as if it was a second function
507 // parameter, i.e. let nested calls have an indent of 4.
508 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000509 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000510 // Top-level spaces are exempt as that mostly leads to better results.
511 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000512 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000513 Previous.Type == TT_ConditionalExpr ||
514 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000515 getPrecedence(Previous) != prec::Assignment)
516 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000517 else if (Previous.ParameterCount > 1 &&
518 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000519 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000520 Previous.Type == TT_TemplateOpener))
521 // If this function has multiple parameters, indent nested calls from
522 // the start of the first parameter.
523 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000524 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000525
526 // If we break after an {, we should also break before the corresponding }.
527 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000528 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000529
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000530 if (State.Stack.back().AvoidBinPacking && Newline &&
531 (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000532 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000533 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000534 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
535 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000536 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
537 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000538 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000539
Daniel Jaspere941b162013-01-23 10:08:28 +0000540 // 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) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000543 if (Line.First.isNot(tok::kw_for) || i != 1)
544 State.Stack[i].BreakAfterComma = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000545 }
546 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000547
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000548 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000549 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000550
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000551 /// \brief Mark the next token as consumed in \p State and modify its stacks
552 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000553 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000554 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000555 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000556
Daniel Jasper337816e2013-01-11 10:22:12 +0000557 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
558 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000559 if (Current.is(tok::question))
560 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000561 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000562 !Current.MatchingParen->MustBreakBefore) {
563 AnnotatedToken *End = Current.MatchingParen;
564 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
565 End = &End->Children[0];
566 }
567 unsigned Length = End->TotalLength - Current.TotalLength + 1;
568 if (Length + State.Column > getColumnLimit())
569 State.Stack.back().BreakAfterComma = true;
570 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000571
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000572 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000573 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000574 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
575 Current.is(tok::l_brace) ||
576 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000577 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000578 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000579 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000580 NewIndent = 2 + State.Stack.back().LastSpace;
581 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000582 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000583 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000584 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000585 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000586 State.Stack.push_back(
587 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
588 State.Stack.back().HasMultiParameterLine));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000589 }
590
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000591 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000592 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000593 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
594 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
595 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000596 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000598
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000599 if (State.NextToken->Children.empty())
600 State.NextToken = NULL;
601 else
602 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000603
604 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000605 }
606
Daniel Jasper2df93312013-01-09 10:16:05 +0000607 unsigned getColumnLimit() {
608 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
609 }
610
Daniel Jasper4b866272013-02-01 11:00:45 +0000611 /// \brief An edge in the solution space starting from the \c LineState and
612 /// inserting a newline dependent on the \c bool.
613 typedef std::pair<bool, const LineState *> Edge;
614
615 /// \brief An item in the prioritized BFS search queue. The \c LineState was
616 /// reached using the \c Edge.
617 typedef std::pair<LineState, Edge> QueueItem;
618
619 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000620 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000621 /// This implements a variant of Dijkstra's algorithm on the graph that spans
622 /// the solution space (\c LineStates are the nodes). The algorithm tries to
623 /// find the shortest path (the one with lowest penalty) from \p InitialState
624 /// to a state where all tokens are placed.
625 unsigned analyzeSolutionSpace(const LineState &InitialState) {
626 // Insert start element into queue.
627 std::multimap<unsigned, QueueItem> Queue;
628 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000629 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000630 std::map<LineState, Edge> Seen;
631
632 // While not empty, take first element and follow edges.
633 while (!Queue.empty()) {
634 unsigned Penalty = Queue.begin()->first;
635 QueueItem Item = Queue.begin()->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000636 if (Item.first.NextToken == NULL) {
637 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000638 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000639 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000640 Queue.erase(Queue.begin());
641
642 if (Seen.find(Item.first) != Seen.end())
643 continue; // State already examined with lower penalty.
644
645 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
646 Item.first,
647 Edge(Item.second.first, Item.second.second))).first->first;
648
649 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
650 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
651 }
652
653 if (Queue.empty())
654 // We were unable to find a solution, do nothing.
655 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000656 return 0;
657
Daniel Jasper4b866272013-02-01 11:00:45 +0000658 // Reconstruct the solution.
659 // FIXME: Add debugging output.
660 Edge *CurrentEdge = &Queue.begin()->second.second;
661 while (CurrentEdge->second != NULL) {
662 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000663 if (CurrentEdge->first) {
664 DEBUG(llvm::errs() << "Penalty for splitting before "
665 << CurrentState.NextToken->FormatTok.Tok.getName()
666 << ": " << CurrentState.NextToken->SplitPenalty
667 << "\n");
668 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000669 addTokenToState(CurrentEdge->first, false, CurrentState);
670 CurrentEdge = &Seen[*CurrentEdge->second];
671 }
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000672 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000673
Daniel Jasper4b866272013-02-01 11:00:45 +0000674 // Return the column after the last token of the solution.
675 return Queue.begin()->second.first.Column;
676 }
677
678 /// \brief Add the following state to the analysis queue \p Queue.
679 ///
680 /// Assume the current state is \p OldState and has been reached with a
681 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
682 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
683 bool NewLine,
684 std::multimap<unsigned, QueueItem> &Queue) {
685 if (NewLine && !canBreak(OldState))
686 return;
687 if (!NewLine && mustBreak(OldState))
688 return;
689 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000690 if (NewLine)
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000691 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000692 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000693 if (State.Column > getColumnLimit()) {
694 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000695 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000696 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000697 Queue.insert(std::pair<unsigned, QueueItem>(
698 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
699 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000700
Daniel Jasper4b866272013-02-01 11:00:45 +0000701 /// \brief Returns \c true, if a line break after \p State is allowed.
702 bool canBreak(const LineState &State) {
703 if (!State.NextToken->CanBreakBefore &&
704 !(State.NextToken->is(tok::r_brace) &&
705 State.Stack.back().BreakBeforeClosingBrace))
706 return false;
707 // Trying to insert a parameter on a new line if there are already more than
708 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000709 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000710 State.Stack.back().AvoidBinPacking)
711 return false;
712 return true;
713 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000714
Daniel Jasper4b866272013-02-01 11:00:45 +0000715 /// \brief Returns \c true, if a line break after \p State is mandatory.
716 bool mustBreak(const LineState &State) {
717 if (State.NextToken->MustBreakBefore)
718 return true;
719 if (State.NextToken->is(tok::r_brace) &&
720 State.Stack.back().BreakBeforeClosingBrace)
721 return true;
722 if (State.NextToken->Parent->is(tok::semi) &&
723 State.LineContainsContinuedForLoopSection)
724 return true;
725 if (State.NextToken->Parent->is(tok::comma) &&
726 State.Stack.back().BreakAfterComma &&
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000727 !isTrailingComment(*State.NextToken))
Daniel Jasper4b866272013-02-01 11:00:45 +0000728 return true;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000729 if (State.NextToken->Type == TT_ObjCSelectorName &&
730 State.Stack.back().ColonPos != 0)
731 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000732 if ((State.NextToken->Type == TT_CtorInitializerColon ||
733 (State.NextToken->Parent->ClosesTemplateDeclaration &&
734 State.Stack.size() == 1)))
735 return true;
736 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 }
738
Daniel Jasperf7935112012-12-03 18:12:45 +0000739 FormatStyle Style;
740 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000741 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000742 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000743 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000744 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000745};
746
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000747class LexerBasedFormatTokenSource : public FormatTokenSource {
748public:
749 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000750 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000751 IdentTable(Lex.getLangOpts()) {
752 Lex.SetKeepWhitespaceMode(true);
753 }
754
755 virtual FormatToken getNextToken() {
756 if (GreaterStashed) {
757 FormatTok.NewlinesBefore = 0;
758 FormatTok.WhiteSpaceStart =
759 FormatTok.Tok.getLocation().getLocWithOffset(1);
760 FormatTok.WhiteSpaceLength = 0;
761 GreaterStashed = false;
762 return FormatTok;
763 }
764
765 FormatTok = FormatToken();
766 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000767 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000768 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000769 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
770 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000771
772 // Consume and record whitespace until we find a significant token.
773 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000774 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000775 FormatTok.HasUnescapedNewline =
776 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000777 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
778
779 if (FormatTok.Tok.is(tok::eof))
780 return FormatTok;
781 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000782 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000783 }
Manuel Klimekef920692013-01-07 07:56:50 +0000784
785 // Now FormatTok is the next non-whitespace token.
786 FormatTok.TokenLength = Text.size();
787
Manuel Klimek1abf7892013-01-04 23:34:14 +0000788 // In case the token starts with escaped newlines, we want to
789 // take them into account as whitespace - this pattern is quite frequent
790 // in macro definitions.
791 // FIXME: What do we want to do with other escaped spaces, and escaped
792 // spaces or newlines in the middle of tokens?
793 // FIXME: Add a more explicit test.
794 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000795 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000796 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000797 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000798 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000799 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000800 }
801
802 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000803 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000804 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000805 FormatTok.Tok.setKind(Info.getTokenID());
806 }
807
808 if (FormatTok.Tok.is(tok::greatergreater)) {
809 FormatTok.Tok.setKind(tok::greater);
810 GreaterStashed = true;
811 }
812
813 return FormatTok;
814 }
815
816private:
817 FormatToken FormatTok;
818 bool GreaterStashed;
819 Lexer &Lex;
820 SourceManager &SourceMgr;
821 IdentifierTable IdentTable;
822
823 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000824 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000825 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
826 Tok.getLength());
827 }
828};
829
Daniel Jasperf7935112012-12-03 18:12:45 +0000830class Formatter : public UnwrappedLineConsumer {
831public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000832 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
833 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000834 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000835 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000836 Whitespaces(SourceMgr), Ranges(Ranges) {
837 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000838
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000839 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000840
Daniel Jasperf7935112012-12-03 18:12:45 +0000841 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000842 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000843 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000844 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000845 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000846 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
847 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
848 Annotator.annotate();
849 }
850 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
851 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000852 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000853 const AnnotatedLine &TheLine = *I;
854 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000855 unsigned Indent =
856 formatFirstToken(TheLine.First, TheLine.Level,
857 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000858 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000859 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000860 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000861 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000862 PreviousEndOfLineColumn = Formatter.format();
863 } else {
864 // If we did not reformat this unwrapped line, the column at the end of
865 // the last token is unchanged - thus, we can calculate the end of the
866 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000867 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000868 SourceMgr.getSpellingColumnNumber(
869 TheLine.Last->FormatTok.Tok.getLocation()) +
870 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000871 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000872 }
873 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000874 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000875 }
876
877private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000878 /// \brief Tries to merge lines into one.
879 ///
880 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
881 /// if possible; note that \c I will be incremented when lines are merged.
882 ///
883 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000884 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000885 std::vector<AnnotatedLine>::iterator &I,
886 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000887 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
888
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000889 // We can never merge stuff if there are trailing line comments.
890 if (I->Last->Type == TT_LineComment)
891 return;
892
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000893 // Check whether the UnwrappedLine can be put onto a single line. If
894 // so, this is bound to be the optimal solution (by definition) and we
895 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000896 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000897 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000898 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000899
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000900 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000901 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000902
Daniel Jasper25837aa2013-01-14 14:14:23 +0000903 if (I->Last->is(tok::l_brace)) {
904 tryMergeSimpleBlock(I, E, Limit);
905 } else if (I->First.is(tok::kw_if)) {
906 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000907 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
908 I->First.FormatTok.IsFirst)) {
909 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000910 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000911 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000912 }
913
Daniel Jasper39825ea2013-01-14 15:40:57 +0000914 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
915 std::vector<AnnotatedLine>::iterator E,
916 unsigned Limit) {
917 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000918 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
919 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000920 if (I + 2 != E && (I + 2)->InPPDirective &&
921 !(I + 2)->First.FormatTok.HasUnescapedNewline)
922 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000923 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000924 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000925 join(Line, *(++I));
926 }
927
Daniel Jasper25837aa2013-01-14 14:14:23 +0000928 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
929 std::vector<AnnotatedLine>::iterator E,
930 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000931 if (!Style.AllowShortIfStatementsOnASingleLine)
932 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000933 if ((I + 1)->InPPDirective != I->InPPDirective ||
934 ((I + 1)->InPPDirective &&
935 (I + 1)->First.FormatTok.HasUnescapedNewline))
936 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000937 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000938 if (Line.Last->isNot(tok::r_paren))
939 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000940 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000941 return;
942 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
943 return;
944 // Only inline simple if's (no nested if or else).
945 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
946 return;
947 join(Line, *(++I));
948 }
949
950 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000951 std::vector<AnnotatedLine>::iterator E,
952 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000953 // First, check that the current line allows merging. This is the case if
954 // we're not in a control flow statement and the last token is an opening
955 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +0000956 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000957 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000958 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
959 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
960 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
961 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +0000962 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000963 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
964 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000965 if (!AllowedTokens)
966 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000967
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000968 AnnotatedToken *Tok = &(I + 1)->First;
969 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
970 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
971 Tok->SpaceRequiredBefore = false;
972 join(Line, *(I + 1));
973 I += 1;
974 } else {
975 // Check that we still have three lines and they fit into the limit.
976 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
977 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +0000978 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000979
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000980 // Second, check that the next line does not contain any braces - if it
981 // does, readability declines when putting it into a single line.
982 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
983 return;
984 do {
985 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
986 return;
987 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
988 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000989
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000990 // Last, check that the third line contains a single closing brace.
991 Tok = &(I + 2)->First;
992 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
993 Tok->MustBreakBefore)
994 return;
995
996 join(Line, *(I + 1));
997 join(Line, *(I + 2));
998 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000999 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001000 }
1001
1002 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1003 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001004 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1005 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001006 }
1007
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001008 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1009 A.Last->Children.push_back(B.First);
1010 while (!A.Last->Children.empty()) {
1011 A.Last->Children[0].Parent = A.Last;
1012 A.Last = &A.Last->Children[0];
1013 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001014 }
1015
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001016 bool touchesRanges(const AnnotatedLine &TheLine) {
1017 const FormatToken *First = &TheLine.First.FormatTok;
1018 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001019 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001020 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001021 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001022 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1023 Ranges[i].getBegin()) &&
1024 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1025 LineRange.getBegin()))
1026 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001027 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001028 return false;
1029 }
1030
1031 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001032 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001033 }
1034
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001035 /// \brief Add a new line and the required indent before the first Token
1036 /// of the \c UnwrappedLine if there was no structural parsing error.
1037 /// Returns the indent level of the \c UnwrappedLine.
1038 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1039 bool InPPDirective,
1040 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001041 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001042 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1043 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1044
Daniel Jasperbbc84152013-01-29 11:27:30 +00001045 unsigned Newlines =
1046 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001047 if (Newlines == 0 && !Tok.IsFirst)
1048 Newlines = 1;
1049 unsigned Indent = Level * 2;
1050
1051 bool IsAccessModifier = false;
1052 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1053 RootToken.is(tok::kw_private))
1054 IsAccessModifier = true;
1055 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1056 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1057 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1058 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1059 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1060 IsAccessModifier = true;
1061
1062 if (IsAccessModifier &&
1063 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1064 Indent += Style.AccessModifierOffset;
1065 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001066 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001067 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001068 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1069 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001070 }
1071 return Indent;
1072 }
1073
Alexander Kornienko116ba682013-01-14 11:34:14 +00001074 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001075 FormatStyle Style;
1076 Lexer &Lex;
1077 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001078 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001079 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001080 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001081 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001082};
1083
Daniel Jasperbbc84152013-01-29 11:27:30 +00001084tooling::Replacements
1085reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1086 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001087 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001088 OwningPtr<DiagnosticConsumer> DiagPrinter;
1089 if (DiagClient == 0) {
1090 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1091 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1092 DiagClient = DiagPrinter.get();
1093 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001094 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001095 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001096 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001097 Diagnostics.setSourceManager(&SourceMgr);
1098 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001099 return formatter.format();
1100}
1101
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001102LangOptions getFormattingLangOpts() {
1103 LangOptions LangOpts;
1104 LangOpts.CPlusPlus = 1;
1105 LangOpts.CPlusPlus11 = 1;
1106 LangOpts.Bool = 1;
1107 LangOpts.ObjC1 = 1;
1108 LangOpts.ObjC2 = 1;
1109 return LangOpts;
1110}
1111
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001112} // namespace format
1113} // namespace clang