blob: 99251f5c85bd9e7bf75b95ddb5a6fd8c171eb4c4 [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;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000039 LLVMStyle.PointerBindsToType = false;
40 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000041 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000042 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000043 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000044 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000045 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000046 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000047 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000048 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000049 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000050 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000051 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +000052 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000059 GoogleStyle.PointerBindsToType = true;
60 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000061 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000062 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000063 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000064 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000065 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000066 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000067 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000068 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000069 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000070 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000071 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
Daniel Jasper1b750ed2013-01-14 16:24:39 +000075FormatStyle getChromiumStyle() {
76 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000077 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = 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 Jasperaa701fa2013-01-18 08:44:07 +000083/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +000084///
Daniel Jasperaa701fa2013-01-18 08:44:07 +000085/// This includes special handling for certain constructs, e.g. the alignment of
86/// trailing line comments.
87class WhitespaceManager {
88public:
89 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
90
91 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
92 /// each \c AnnotatedToken.
93 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
94 unsigned Spaces, unsigned WhitespaceStartColumn,
95 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +000096 // 2+ newlines mean an empty line separating logic scopes.
97 if (NewLines >= 2)
98 alignComments();
99
100 // Align line comments if they are trailing or if they continue other
101 // trailing comments.
102 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000103 (Tok.Parent != NULL || !Comments.empty())) {
104 if (Style.ColumnLimit >=
105 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
106 Comments.push_back(StoredComment());
107 Comments.back().Tok = Tok.FormatTok;
108 Comments.back().Spaces = Spaces;
109 Comments.back().NewLines = NewLines;
110 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000111 Comments.back().MaxColumn =
112 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000113 return;
114 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000115 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000116
117 // If this line does not have a trailing comment, align the stored comments.
118 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
119 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000120 storeReplacement(Tok.FormatTok,
121 std::string(NewLines, '\n') + std::string(Spaces, ' '));
122 }
123
124 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
125 /// backslashes to escape newlines inside a preprocessor directive.
126 ///
127 /// This function and \c replaceWhitespace have the same behavior if
128 /// \c Newlines == 0.
129 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
130 unsigned Spaces, unsigned WhitespaceStartColumn,
131 const FormatStyle &Style) {
132 std::string NewLineText;
133 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000134 unsigned Offset =
135 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000136 for (unsigned i = 0; i < NewLines; ++i) {
137 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
138 NewLineText += "\\\n";
139 Offset = 0;
140 }
141 }
142 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
143 }
144
145 /// \brief Returns all the \c Replacements created during formatting.
146 const tooling::Replacements &generateReplacements() {
147 alignComments();
148 return Replaces;
149 }
150
151private:
152 /// \brief Structure to store a comment for later layout and alignment.
153 struct StoredComment {
154 FormatToken Tok;
155 unsigned MinColumn;
156 unsigned MaxColumn;
157 unsigned NewLines;
158 unsigned Spaces;
159 };
160 SmallVector<StoredComment, 16> Comments;
161 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
162
163 /// \brief Try to align all stashed comments.
164 void alignComments() {
165 unsigned MinColumn = 0;
166 unsigned MaxColumn = UINT_MAX;
167 comment_iterator Start = Comments.begin();
168 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
169 ++I) {
170 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
171 alignComments(Start, I, MinColumn);
172 MinColumn = I->MinColumn;
173 MaxColumn = I->MaxColumn;
174 Start = I;
175 } else {
176 MinColumn = std::max(MinColumn, I->MinColumn);
177 MaxColumn = std::min(MaxColumn, I->MaxColumn);
178 }
179 }
180 alignComments(Start, Comments.end(), MinColumn);
181 Comments.clear();
182 }
183
184 /// \brief Put all the comments between \p I and \p E into \p Column.
185 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
186 while (I != E) {
187 unsigned Spaces = I->Spaces + Column - I->MinColumn;
188 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
189 std::string(Spaces, ' '));
190 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000191 }
192 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000193
194 /// \brief Stores \p Text as the replacement for the whitespace in front of
195 /// \p Tok.
196 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000197 // Don't create a replacement, if it does not change anything.
198 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
199 Tok.WhiteSpaceLength) == Text)
200 return;
201
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000202 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
203 Tok.WhiteSpaceLength, Text));
204 }
205
206 SourceManager &SourceMgr;
207 tooling::Replacements Replaces;
208};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000209
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000210static bool isTrailingComment(const AnnotatedToken &Tok) {
211 return Tok.is(tok::comment) &&
212 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
213}
214
Daniel Jasperf7935112012-12-03 18:12:45 +0000215class UnwrappedLineFormatter {
216public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000217 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000218 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000219 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000220 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000221 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000222 FirstIndent(FirstIndent), RootToken(RootToken),
223 Whitespaces(Whitespaces) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000224 }
225
Manuel Klimek1abf7892013-01-04 23:34:14 +0000226 /// \brief Formats an \c UnwrappedLine.
227 ///
228 /// \returns The column after the last token in the last line of the
229 /// \c UnwrappedLine.
230 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000231 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000232 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000233 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000234 State.NextToken = &RootToken;
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000235 State.Stack.push_back(
236 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
237 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000238 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000239 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000240
Manuel Klimek24998102013-01-16 14:55:28 +0000241 DEBUG({
242 DebugTokenState(*State.NextToken);
243 });
244
Daniel Jaspere9de2602012-12-06 09:56:08 +0000245 // The first token has already been indented and thus consumed.
246 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000247
Daniel Jasper4b866272013-02-01 11:00:45 +0000248 // If everything fits on a single line, just put it there.
249 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
250 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000251 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000252 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000253 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000254 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000255
256 // Find best solution in solution space.
257 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000258 }
259
260private:
Manuel Klimek24998102013-01-16 14:55:28 +0000261 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
262 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000263 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
264 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000265 llvm::errs();
266 }
267
Daniel Jasper337816e2013-01-11 10:22:12 +0000268 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000269 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
270 bool HasMultiParameterLine)
Daniel Jaspera836b902013-01-23 16:58:21 +0000271 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000272 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000273 AvoidBinPacking(AvoidBinPacking), BreakAfterComma(false),
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000274 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000275 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000276
Daniel Jasperf7935112012-12-03 18:12:45 +0000277 /// \brief The position to which a specific parenthesis level needs to be
278 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000279 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000280
Daniel Jaspere9de2602012-12-06 09:56:08 +0000281 /// \brief The position of the last space on each level.
282 ///
283 /// Used e.g. to break like:
284 /// functionCall(Parameter, otherCall(
285 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000286 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000287
Daniel Jaspera836b902013-01-23 16:58:21 +0000288 /// \brief This is the column of the first token after an assignment.
289 unsigned AssignmentColumn;
290
Daniel Jaspere9de2602012-12-06 09:56:08 +0000291 /// \brief The position the first "<<" operator encountered on each level.
292 ///
293 /// Used to align "<<" operators. 0 if no such operator has been encountered
294 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000295 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000296
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000297 /// \brief Whether a newline needs to be inserted before the block's closing
298 /// brace.
299 ///
300 /// We only want to insert a newline before the closing brace if there also
301 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000302 bool BreakBeforeClosingBrace;
303
Daniel Jasperca6623b2013-01-28 12:45:14 +0000304 /// \brief The column of a \c ? in a conditional expression;
305 unsigned QuestionColumn;
306
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000307 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
308 /// lines, in this context.
309 bool AvoidBinPacking;
310
311 /// \brief Break after the next comma (or all the commas in this context if
312 /// \c AvoidBinPacking is \c true).
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000313 bool BreakAfterComma;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000314
315 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000316 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000317
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000318 /// \brief The position of the colon in an ObjC method declaration/call.
319 unsigned ColonPos;
320
Daniel Jasper337816e2013-01-11 10:22:12 +0000321 bool operator<(const ParenState &Other) const {
322 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000323 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000324 if (LastSpace != Other.LastSpace)
325 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000326 if (AssignmentColumn != Other.AssignmentColumn)
327 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000328 if (FirstLessLess != Other.FirstLessLess)
329 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000330 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
331 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000332 if (QuestionColumn != Other.QuestionColumn)
333 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000334 if (AvoidBinPacking != Other.AvoidBinPacking)
335 return AvoidBinPacking;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000336 if (BreakAfterComma != Other.BreakAfterComma)
337 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000338 if (HasMultiParameterLine != Other.HasMultiParameterLine)
339 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000340 if (ColonPos != Other.ColonPos)
341 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000342 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000343 }
344 };
345
346 /// \brief The current state when indenting a unwrapped line.
347 ///
348 /// As the indenting tries different combinations this is copied by value.
349 struct LineState {
350 /// \brief The number of used columns in the current line.
351 unsigned Column;
352
353 /// \brief The token that needs to be next formatted.
354 const AnnotatedToken *NextToken;
355
Daniel Jasperbbc84152013-01-29 11:27:30 +0000356 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000357 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000358 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000359 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000360
361 /// \brief \c true if this line contains a continued for-loop section.
362 bool LineContainsContinuedForLoopSection;
363
Daniel Jasper337816e2013-01-11 10:22:12 +0000364 /// \brief A stack keeping track of properties applying to parenthesis
365 /// levels.
366 std::vector<ParenState> Stack;
367
368 /// \brief Comparison operator to be able to used \c LineState in \c map.
369 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000370 if (Other.NextToken != NextToken)
371 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000372 if (Other.Column != Column)
373 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000374 if (Other.VariablePos != VariablePos)
375 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000376 if (Other.LineContainsContinuedForLoopSection !=
377 LineContainsContinuedForLoopSection)
378 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000379 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000380 }
381 };
382
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000383 /// \brief Appends the next token to \p State and updates information
384 /// necessary for indentation.
385 ///
386 /// Puts the token on the current line if \p Newline is \c true and adds a
387 /// line break and necessary indentation otherwise.
388 ///
389 /// If \p DryRun is \c false, also creates and stores the required
390 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000391 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000392 const AnnotatedToken &Current = *State.NextToken;
393 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000394 assert(State.Stack.size());
395 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000396
Daniel Jasper4b866272013-02-01 11:00:45 +0000397 if (Current.Type == TT_ImplicitStringLiteral) {
398 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
399 State.NextToken->FormatTok.TokenLength;
400 if (State.NextToken->Children.empty())
401 State.NextToken = NULL;
402 else
403 State.NextToken = &State.NextToken->Children[0];
404 return;
405 }
406
Daniel Jasperf7935112012-12-03 18:12:45 +0000407 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000408 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000409 if (Current.is(tok::r_brace)) {
410 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000411 } else if (Current.is(tok::string_literal) &&
412 Previous.is(tok::string_literal)) {
413 State.Column = State.Column - Previous.FormatTok.TokenLength;
414 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000415 State.Stack[ParenLevel].FirstLessLess != 0) {
416 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000417 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000418 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000419 Current.is(tok::period) || Current.is(tok::arrow) ||
420 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000421 // Indent and extra 4 spaces after if we know the current expression is
422 // continued. Don't do that on the top level, as we already indent 4
423 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000424 State.Column = std::max(State.Stack.back().LastSpace,
425 State.Stack.back().Indent) + 4;
426 } else if (Current.Type == TT_ConditionalExpr) {
427 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000428 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
429 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
430 ParenLevel == 0)) {
431 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000432 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
433 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000434 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000435 } else if (Previous.Type == TT_BinaryOperator &&
436 State.Stack.back().AssignmentColumn != 0) {
437 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000438 } else if (Current.Type == TT_ObjCSelectorName) {
439 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
440 State.Column =
441 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
442 } else {
443 State.Column = State.Stack.back().Indent;
444 State.Stack.back().ColonPos =
445 State.Column + Current.FormatTok.TokenLength;
446 }
447 } else if (Previous.Type == TT_ObjCMethodExpr) {
448 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000449 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000450 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000451 }
452
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000453 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
454 State.Stack.back().BreakAfterComma = false;
455
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000456 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000457 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000458
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000459 if (!DryRun) {
460 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000461 Whitespaces.replaceWhitespace(Current, 1, State.Column,
462 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000463 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000464 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
465 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000466 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000467
Daniel Jasper337816e2013-01-11 10:22:12 +0000468 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000469 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000470 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000471 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000472 if (Current.is(tok::equal) &&
473 (RootToken.is(tok::kw_for) || ParenLevel == 0))
474 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000475
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000476 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
477 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000478 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000479
Daniel Jasperf7935112012-12-03 18:12:45 +0000480 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000481 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000482
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000483 if (Current.Type == TT_ObjCSelectorName &&
484 State.Stack.back().ColonPos == 0) {
485 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
486 State.Column + Spaces + Current.FormatTok.TokenLength)
487 State.Stack.back().ColonPos =
488 State.Stack.back().Indent + Current.LongestObjCSelectorName;
489 else
490 State.Stack.back().ColonPos =
491 State.Column + Spaces + Current.LongestObjCSelectorName;
492 }
493
Daniel Jasperbcab4302013-01-09 10:40:23 +0000494 // FIXME: Do we need to do this for assignments nested in other
495 // expressions?
496 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000497 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000498 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000499 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000500 if (Current.Type != TT_LineComment &&
501 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
502 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000503 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000504 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000505 State.Stack[ParenLevel].HasMultiParameterLine = true;
506
Daniel Jaspere9de2602012-12-06 09:56:08 +0000507 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000508 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
509 // Treat the condition inside an if as if it was a second function
510 // parameter, i.e. let nested calls have an indent of 4.
511 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000512 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000513 // Top-level spaces are exempt as that mostly leads to better results.
514 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000515 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000516 Previous.Type == TT_ConditionalExpr ||
517 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000518 getPrecedence(Previous) != prec::Assignment)
519 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000520 else if (Previous.ParameterCount > 1 &&
521 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000522 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000523 Previous.Type == TT_TemplateOpener))
524 // If this function has multiple parameters, indent nested calls from
525 // the start of the first parameter.
526 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000528
529 // If we break after an {, we should also break before the corresponding }.
530 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000531 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000532
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000533 if (State.Stack.back().AvoidBinPacking && Newline &&
534 (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000535 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000536 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000537 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
538 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000539 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
540 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000541 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000542
Daniel Jaspere941b162013-01-23 10:08:28 +0000543 // Any break on this level means that the parent level has been broken
544 // and we need to avoid bin packing there.
545 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000546 if (Line.First.isNot(tok::kw_for) || i != 1)
547 State.Stack[i].BreakAfterComma = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000548 }
549 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000550
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000551 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000552 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000553
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000554 /// \brief Mark the next token as consumed in \p State and modify its stacks
555 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000556 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000557 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000558 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000559
Daniel Jasper337816e2013-01-11 10:22:12 +0000560 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
561 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000562 if (Current.is(tok::question))
563 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000564 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000565 !Current.MatchingParen->MustBreakBefore) {
566 AnnotatedToken *End = Current.MatchingParen;
567 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
568 End = &End->Children[0];
569 }
570 unsigned Length = End->TotalLength - Current.TotalLength + 1;
571 if (Length + State.Column > getColumnLimit())
572 State.Stack.back().BreakAfterComma = true;
573 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000574
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000575 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000576 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000577 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
578 Current.is(tok::l_brace) ||
579 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000580 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000581 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000582 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000583 NewIndent = 2 + State.Stack.back().LastSpace;
584 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000585 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000586 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000587 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000588 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000589 State.Stack.push_back(
590 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
591 State.Stack.back().HasMultiParameterLine));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000592 }
593
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000594 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000595 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000596 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
597 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
598 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000599 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000600 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000601
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000602 if (State.NextToken->Children.empty())
603 State.NextToken = NULL;
604 else
605 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000606
607 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000608 }
609
Daniel Jasper2df93312013-01-09 10:16:05 +0000610 unsigned getColumnLimit() {
611 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
612 }
613
Daniel Jasper4b866272013-02-01 11:00:45 +0000614 /// \brief An edge in the solution space starting from the \c LineState and
615 /// inserting a newline dependent on the \c bool.
616 typedef std::pair<bool, const LineState *> Edge;
617
618 /// \brief An item in the prioritized BFS search queue. The \c LineState was
619 /// reached using the \c Edge.
620 typedef std::pair<LineState, Edge> QueueItem;
621
622 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000623 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000624 /// This implements a variant of Dijkstra's algorithm on the graph that spans
625 /// the solution space (\c LineStates are the nodes). The algorithm tries to
626 /// find the shortest path (the one with lowest penalty) from \p InitialState
627 /// to a state where all tokens are placed.
628 unsigned analyzeSolutionSpace(const LineState &InitialState) {
629 // Insert start element into queue.
630 std::multimap<unsigned, QueueItem> Queue;
631 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000632 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000633 std::map<LineState, Edge> Seen;
634
635 // While not empty, take first element and follow edges.
636 while (!Queue.empty()) {
637 unsigned Penalty = Queue.begin()->first;
638 QueueItem Item = Queue.begin()->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000639 if (Item.first.NextToken == NULL) {
640 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000641 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000642 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000643 Queue.erase(Queue.begin());
644
645 if (Seen.find(Item.first) != Seen.end())
646 continue; // State already examined with lower penalty.
647
648 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
649 Item.first,
650 Edge(Item.second.first, Item.second.second))).first->first;
651
652 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
653 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
654 }
655
656 if (Queue.empty())
657 // We were unable to find a solution, do nothing.
658 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000659 return 0;
660
Daniel Jasper4b866272013-02-01 11:00:45 +0000661 // Reconstruct the solution.
662 // FIXME: Add debugging output.
663 Edge *CurrentEdge = &Queue.begin()->second.second;
664 while (CurrentEdge->second != NULL) {
665 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000666 if (CurrentEdge->first) {
667 DEBUG(llvm::errs() << "Penalty for splitting before "
668 << CurrentState.NextToken->FormatTok.Tok.getName()
669 << ": " << CurrentState.NextToken->SplitPenalty
670 << "\n");
671 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000672 addTokenToState(CurrentEdge->first, false, CurrentState);
673 CurrentEdge = &Seen[*CurrentEdge->second];
674 }
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000675 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000676
Daniel Jasper4b866272013-02-01 11:00:45 +0000677 // Return the column after the last token of the solution.
678 return Queue.begin()->second.first.Column;
679 }
680
681 /// \brief Add the following state to the analysis queue \p Queue.
682 ///
683 /// Assume the current state is \p OldState and has been reached with a
684 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
685 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
686 bool NewLine,
687 std::multimap<unsigned, QueueItem> &Queue) {
688 if (NewLine && !canBreak(OldState))
689 return;
690 if (!NewLine && mustBreak(OldState))
691 return;
692 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000693 if (NewLine)
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000694 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000695 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000696 if (State.Column > getColumnLimit()) {
697 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000698 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000699 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000700 Queue.insert(std::pair<unsigned, QueueItem>(
701 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
702 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000703
Daniel Jasper4b866272013-02-01 11:00:45 +0000704 /// \brief Returns \c true, if a line break after \p State is allowed.
705 bool canBreak(const LineState &State) {
706 if (!State.NextToken->CanBreakBefore &&
707 !(State.NextToken->is(tok::r_brace) &&
708 State.Stack.back().BreakBeforeClosingBrace))
709 return false;
710 // Trying to insert a parameter on a new line if there are already more than
711 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000712 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000713 State.Stack.back().AvoidBinPacking)
714 return false;
715 return true;
716 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000717
Daniel Jasper4b866272013-02-01 11:00:45 +0000718 /// \brief Returns \c true, if a line break after \p State is mandatory.
719 bool mustBreak(const LineState &State) {
720 if (State.NextToken->MustBreakBefore)
721 return true;
722 if (State.NextToken->is(tok::r_brace) &&
723 State.Stack.back().BreakBeforeClosingBrace)
724 return true;
725 if (State.NextToken->Parent->is(tok::semi) &&
726 State.LineContainsContinuedForLoopSection)
727 return true;
728 if (State.NextToken->Parent->is(tok::comma) &&
729 State.Stack.back().BreakAfterComma &&
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000730 !isTrailingComment(*State.NextToken))
Daniel Jasper4b866272013-02-01 11:00:45 +0000731 return true;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000732 if (State.NextToken->Type == TT_ObjCSelectorName &&
733 State.Stack.back().ColonPos != 0)
734 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000735 if ((State.NextToken->Type == TT_CtorInitializerColon ||
736 (State.NextToken->Parent->ClosesTemplateDeclaration &&
737 State.Stack.size() == 1)))
738 return true;
739 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000740 }
741
Daniel Jasperf7935112012-12-03 18:12:45 +0000742 FormatStyle Style;
743 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000744 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000745 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000746 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000747 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000748};
749
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000750class LexerBasedFormatTokenSource : public FormatTokenSource {
751public:
752 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000753 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000754 IdentTable(Lex.getLangOpts()) {
755 Lex.SetKeepWhitespaceMode(true);
756 }
757
758 virtual FormatToken getNextToken() {
759 if (GreaterStashed) {
760 FormatTok.NewlinesBefore = 0;
761 FormatTok.WhiteSpaceStart =
762 FormatTok.Tok.getLocation().getLocWithOffset(1);
763 FormatTok.WhiteSpaceLength = 0;
764 GreaterStashed = false;
765 return FormatTok;
766 }
767
768 FormatTok = FormatToken();
769 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000770 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000771 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000772 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
773 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000774
775 // Consume and record whitespace until we find a significant token.
776 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000777 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000778 FormatTok.HasUnescapedNewline =
779 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000780 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
781
782 if (FormatTok.Tok.is(tok::eof))
783 return FormatTok;
784 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000785 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000786 }
Manuel Klimekef920692013-01-07 07:56:50 +0000787
788 // Now FormatTok is the next non-whitespace token.
789 FormatTok.TokenLength = Text.size();
790
Manuel Klimek1abf7892013-01-04 23:34:14 +0000791 // In case the token starts with escaped newlines, we want to
792 // take them into account as whitespace - this pattern is quite frequent
793 // in macro definitions.
794 // FIXME: What do we want to do with other escaped spaces, and escaped
795 // spaces or newlines in the middle of tokens?
796 // FIXME: Add a more explicit test.
797 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000798 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000799 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000800 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000801 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000802 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000803 }
804
805 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000806 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000807 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000808 FormatTok.Tok.setKind(Info.getTokenID());
809 }
810
811 if (FormatTok.Tok.is(tok::greatergreater)) {
812 FormatTok.Tok.setKind(tok::greater);
813 GreaterStashed = true;
814 }
815
816 return FormatTok;
817 }
818
819private:
820 FormatToken FormatTok;
821 bool GreaterStashed;
822 Lexer &Lex;
823 SourceManager &SourceMgr;
824 IdentifierTable IdentTable;
825
826 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000827 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000828 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
829 Tok.getLength());
830 }
831};
832
Daniel Jasperf7935112012-12-03 18:12:45 +0000833class Formatter : public UnwrappedLineConsumer {
834public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000835 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
836 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000837 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000838 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000839 Whitespaces(SourceMgr), Ranges(Ranges) {
840 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000841
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000842 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000843
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000844 void deriveLocalStyle() {
845 unsigned CountBoundToVariable = 0;
846 unsigned CountBoundToType = 0;
847 bool HasCpp03IncompatibleFormat = false;
848 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
849 if (AnnotatedLines[i].First.Children.empty())
850 continue;
851 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
852 while (!Tok->Children.empty()) {
853 if (Tok->Type == TT_PointerOrReference) {
854 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
855 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
856 if (SpacesBefore && !SpacesAfter)
857 ++CountBoundToVariable;
858 else if (!SpacesBefore && SpacesAfter)
859 ++CountBoundToType;
860 }
861
862 if (Tok->Type == TT_TemplateCloser && Tok->Parent->Type ==
863 TT_TemplateCloser && Tok->FormatTok.WhiteSpaceLength == 0)
864 HasCpp03IncompatibleFormat = true;
865 Tok = &Tok->Children[0];
866 }
867 }
868 if (Style.DerivePointerBinding) {
869 if (CountBoundToType > CountBoundToVariable)
870 Style.PointerBindsToType = true;
871 else if (CountBoundToType < CountBoundToVariable)
872 Style.PointerBindsToType = false;
873 }
874 if (Style.Standard == FormatStyle::LS_Auto) {
875 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
876 : FormatStyle::LS_Cpp03;
877 }
878 }
879
Daniel Jasperf7935112012-12-03 18:12:45 +0000880 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000881 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000882 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000883 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000884 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000885 TokenAnnotator Annotator(Style, SourceMgr, Lex);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000886 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000887 Annotator.annotate(AnnotatedLines[i]);
888 }
889 deriveLocalStyle();
890 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
891 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000892 }
893 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
894 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000895 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000896 const AnnotatedLine &TheLine = *I;
897 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000898 unsigned Indent =
899 formatFirstToken(TheLine.First, TheLine.Level,
900 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000901 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000902 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000903 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000904 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000905 PreviousEndOfLineColumn = Formatter.format();
906 } else {
907 // If we did not reformat this unwrapped line, the column at the end of
908 // the last token is unchanged - thus, we can calculate the end of the
909 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000910 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000911 SourceMgr.getSpellingColumnNumber(
912 TheLine.Last->FormatTok.Tok.getLocation()) +
913 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000914 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000915 }
916 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000917 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000918 }
919
920private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000921 /// \brief Tries to merge lines into one.
922 ///
923 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
924 /// if possible; note that \c I will be incremented when lines are merged.
925 ///
926 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000927 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000928 std::vector<AnnotatedLine>::iterator &I,
929 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000930 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
931
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000932 // We can never merge stuff if there are trailing line comments.
933 if (I->Last->Type == TT_LineComment)
934 return;
935
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000936 // Check whether the UnwrappedLine can be put onto a single line. If
937 // so, this is bound to be the optimal solution (by definition) and we
938 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000939 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000940 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000941 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000942
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000943 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000944 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000945
Daniel Jasper25837aa2013-01-14 14:14:23 +0000946 if (I->Last->is(tok::l_brace)) {
947 tryMergeSimpleBlock(I, E, Limit);
948 } else if (I->First.is(tok::kw_if)) {
949 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000950 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
951 I->First.FormatTok.IsFirst)) {
952 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000953 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000954 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000955 }
956
Daniel Jasper39825ea2013-01-14 15:40:57 +0000957 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
958 std::vector<AnnotatedLine>::iterator E,
959 unsigned Limit) {
960 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000961 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
962 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000963 if (I + 2 != E && (I + 2)->InPPDirective &&
964 !(I + 2)->First.FormatTok.HasUnescapedNewline)
965 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000966 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000967 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000968 join(Line, *(++I));
969 }
970
Daniel Jasper25837aa2013-01-14 14:14:23 +0000971 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
972 std::vector<AnnotatedLine>::iterator E,
973 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000974 if (!Style.AllowShortIfStatementsOnASingleLine)
975 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000976 if ((I + 1)->InPPDirective != I->InPPDirective ||
977 ((I + 1)->InPPDirective &&
978 (I + 1)->First.FormatTok.HasUnescapedNewline))
979 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000980 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000981 if (Line.Last->isNot(tok::r_paren))
982 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000983 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000984 return;
985 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
986 return;
987 // Only inline simple if's (no nested if or else).
988 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
989 return;
990 join(Line, *(++I));
991 }
992
993 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000994 std::vector<AnnotatedLine>::iterator E,
995 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000996 // First, check that the current line allows merging. This is the case if
997 // we're not in a control flow statement and the last token is an opening
998 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +0000999 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001000 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001001 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1002 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1003 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1004 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001005 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001006 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1007 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001008 if (!AllowedTokens)
1009 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001010
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001011 AnnotatedToken *Tok = &(I + 1)->First;
1012 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1013 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1014 Tok->SpaceRequiredBefore = false;
1015 join(Line, *(I + 1));
1016 I += 1;
1017 } else {
1018 // Check that we still have three lines and they fit into the limit.
1019 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1020 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001021 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001022
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001023 // Second, check that the next line does not contain any braces - if it
1024 // does, readability declines when putting it into a single line.
1025 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1026 return;
1027 do {
1028 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1029 return;
1030 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1031 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001032
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001033 // Last, check that the third line contains a single closing brace.
1034 Tok = &(I + 2)->First;
1035 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1036 Tok->MustBreakBefore)
1037 return;
1038
1039 join(Line, *(I + 1));
1040 join(Line, *(I + 2));
1041 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001042 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001043 }
1044
1045 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1046 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001047 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1048 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001049 }
1050
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001051 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1052 A.Last->Children.push_back(B.First);
1053 while (!A.Last->Children.empty()) {
1054 A.Last->Children[0].Parent = A.Last;
1055 A.Last = &A.Last->Children[0];
1056 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001057 }
1058
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001059 bool touchesRanges(const AnnotatedLine &TheLine) {
1060 const FormatToken *First = &TheLine.First.FormatTok;
1061 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001062 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001063 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001064 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001065 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1066 Ranges[i].getBegin()) &&
1067 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1068 LineRange.getBegin()))
1069 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001070 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001071 return false;
1072 }
1073
1074 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001075 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001076 }
1077
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001078 /// \brief Add a new line and the required indent before the first Token
1079 /// of the \c UnwrappedLine if there was no structural parsing error.
1080 /// Returns the indent level of the \c UnwrappedLine.
1081 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1082 bool InPPDirective,
1083 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001084 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001085 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1086 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1087
Daniel Jasperbbc84152013-01-29 11:27:30 +00001088 unsigned Newlines =
1089 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001090 if (Newlines == 0 && !Tok.IsFirst)
1091 Newlines = 1;
1092 unsigned Indent = Level * 2;
1093
1094 bool IsAccessModifier = false;
1095 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1096 RootToken.is(tok::kw_private))
1097 IsAccessModifier = true;
1098 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1099 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1100 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1101 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1102 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1103 IsAccessModifier = true;
1104
1105 if (IsAccessModifier &&
1106 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1107 Indent += Style.AccessModifierOffset;
1108 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001109 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001110 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001111 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1112 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001113 }
1114 return Indent;
1115 }
1116
Alexander Kornienko116ba682013-01-14 11:34:14 +00001117 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001118 FormatStyle Style;
1119 Lexer &Lex;
1120 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001121 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001122 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001123 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001124 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001125};
1126
Daniel Jasperbbc84152013-01-29 11:27:30 +00001127tooling::Replacements
1128reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1129 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001130 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001131 OwningPtr<DiagnosticConsumer> DiagPrinter;
1132 if (DiagClient == 0) {
1133 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1134 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1135 DiagClient = DiagPrinter.get();
1136 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001137 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001138 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001139 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001140 Diagnostics.setSourceManager(&SourceMgr);
1141 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001142 return formatter.format();
1143}
1144
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001145LangOptions getFormattingLangOpts() {
1146 LangOptions LangOpts;
1147 LangOpts.CPlusPlus = 1;
1148 LangOpts.CPlusPlus11 = 1;
1149 LangOpts.Bool = 1;
1150 LangOpts.ObjC1 = 1;
1151 LangOpts.ObjC2 = 1;
1152 return LangOpts;
1153}
1154
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001155} // namespace format
1156} // namespace clang