blob: eac822c5b7240241d150c66aa804b306fca1f5f2 [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 Jasper38396592013-02-06 15:23:09 +0000497 !isTrailingComment(Current) &&
Daniel Jasper206df732013-01-07 13:08:40 +0000498 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000499 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000500 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000501 if (Current.Type != TT_LineComment &&
502 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
503 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000504 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000505 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000506 State.Stack[ParenLevel].HasMultiParameterLine = true;
507
Daniel Jaspere9de2602012-12-06 09:56:08 +0000508 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000509 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
510 // Treat the condition inside an if as if it was a second function
511 // parameter, i.e. let nested calls have an indent of 4.
512 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000513 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000514 // Top-level spaces are exempt as that mostly leads to better results.
515 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000516 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000517 Previous.Type == TT_ConditionalExpr ||
518 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000519 getPrecedence(Previous) != prec::Assignment)
520 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000521 else if (Previous.ParameterCount > 1 &&
522 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000523 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000524 Previous.Type == TT_TemplateOpener))
525 // If this function has multiple parameters, indent nested calls from
526 // the start of the first parameter.
527 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000528 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000529
530 // If we break after an {, we should also break before the corresponding }.
531 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000532 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000533
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000534 if (State.Stack.back().AvoidBinPacking && Newline &&
535 (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000536 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000537 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000538 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
539 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000540 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
541 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000542 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000543
Daniel Jaspere941b162013-01-23 10:08:28 +0000544 // Any break on this level means that the parent level has been broken
545 // and we need to avoid bin packing there.
546 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000547 if (Line.First.isNot(tok::kw_for) || i != 1)
548 State.Stack[i].BreakAfterComma = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000549 }
550 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000551
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000552 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000553 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000554
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000555 /// \brief Mark the next token as consumed in \p State and modify its stacks
556 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000557 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000558 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000560
Daniel Jasper337816e2013-01-11 10:22:12 +0000561 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
562 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000563 if (Current.is(tok::question))
564 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000565 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000566 !Current.MatchingParen->MustBreakBefore) {
567 AnnotatedToken *End = Current.MatchingParen;
568 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
569 End = &End->Children[0];
570 }
571 unsigned Length = End->TotalLength - Current.TotalLength + 1;
572 if (Length + State.Column > getColumnLimit())
573 State.Stack.back().BreakAfterComma = true;
574 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000575
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000576 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000577 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000578 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
579 Current.is(tok::l_brace) ||
580 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000581 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000582 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000583 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000584 NewIndent = 2 + State.Stack.back().LastSpace;
585 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000586 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000587 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000588 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000589 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000590 State.Stack.push_back(
591 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
592 State.Stack.back().HasMultiParameterLine));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000593 }
594
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000595 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000596 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000597 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
598 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
599 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000600 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000601 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000602
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000603 if (State.NextToken->Children.empty())
604 State.NextToken = NULL;
605 else
606 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000607
608 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000609 }
610
Daniel Jasper2df93312013-01-09 10:16:05 +0000611 unsigned getColumnLimit() {
612 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
613 }
614
Daniel Jasper4b866272013-02-01 11:00:45 +0000615 /// \brief An edge in the solution space starting from the \c LineState and
616 /// inserting a newline dependent on the \c bool.
617 typedef std::pair<bool, const LineState *> Edge;
618
619 /// \brief An item in the prioritized BFS search queue. The \c LineState was
620 /// reached using the \c Edge.
621 typedef std::pair<LineState, Edge> QueueItem;
622
623 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000624 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000625 /// This implements a variant of Dijkstra's algorithm on the graph that spans
626 /// the solution space (\c LineStates are the nodes). The algorithm tries to
627 /// find the shortest path (the one with lowest penalty) from \p InitialState
628 /// to a state where all tokens are placed.
629 unsigned analyzeSolutionSpace(const LineState &InitialState) {
630 // Insert start element into queue.
631 std::multimap<unsigned, QueueItem> Queue;
632 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000633 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000634 std::map<LineState, Edge> Seen;
635
636 // While not empty, take first element and follow edges.
637 while (!Queue.empty()) {
638 unsigned Penalty = Queue.begin()->first;
639 QueueItem Item = Queue.begin()->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000640 if (Item.first.NextToken == NULL) {
641 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000642 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000643 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000644 Queue.erase(Queue.begin());
645
646 if (Seen.find(Item.first) != Seen.end())
647 continue; // State already examined with lower penalty.
648
649 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
650 Item.first,
651 Edge(Item.second.first, Item.second.second))).first->first;
652
653 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
654 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
655 }
656
657 if (Queue.empty())
658 // We were unable to find a solution, do nothing.
659 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 return 0;
661
Daniel Jasper4b866272013-02-01 11:00:45 +0000662 // Reconstruct the solution.
663 // FIXME: Add debugging output.
664 Edge *CurrentEdge = &Queue.begin()->second.second;
665 while (CurrentEdge->second != NULL) {
666 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000667 if (CurrentEdge->first) {
668 DEBUG(llvm::errs() << "Penalty for splitting before "
669 << CurrentState.NextToken->FormatTok.Tok.getName()
670 << ": " << CurrentState.NextToken->SplitPenalty
671 << "\n");
672 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000673 addTokenToState(CurrentEdge->first, false, CurrentState);
674 CurrentEdge = &Seen[*CurrentEdge->second];
675 }
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000676 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000677
Daniel Jasper4b866272013-02-01 11:00:45 +0000678 // Return the column after the last token of the solution.
679 return Queue.begin()->second.first.Column;
680 }
681
682 /// \brief Add the following state to the analysis queue \p Queue.
683 ///
684 /// Assume the current state is \p OldState and has been reached with a
685 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
686 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
687 bool NewLine,
688 std::multimap<unsigned, QueueItem> &Queue) {
689 if (NewLine && !canBreak(OldState))
690 return;
691 if (!NewLine && mustBreak(OldState))
692 return;
693 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000694 if (NewLine)
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000695 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000696 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000697 if (State.Column > getColumnLimit()) {
698 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000699 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000700 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000701 Queue.insert(std::pair<unsigned, QueueItem>(
702 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
703 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000704
Daniel Jasper4b866272013-02-01 11:00:45 +0000705 /// \brief Returns \c true, if a line break after \p State is allowed.
706 bool canBreak(const LineState &State) {
707 if (!State.NextToken->CanBreakBefore &&
708 !(State.NextToken->is(tok::r_brace) &&
709 State.Stack.back().BreakBeforeClosingBrace))
710 return false;
711 // Trying to insert a parameter on a new line if there are already more than
712 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000713 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000714 State.Stack.back().AvoidBinPacking)
715 return false;
716 return true;
717 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000718
Daniel Jasper4b866272013-02-01 11:00:45 +0000719 /// \brief Returns \c true, if a line break after \p State is mandatory.
720 bool mustBreak(const LineState &State) {
721 if (State.NextToken->MustBreakBefore)
722 return true;
723 if (State.NextToken->is(tok::r_brace) &&
724 State.Stack.back().BreakBeforeClosingBrace)
725 return true;
726 if (State.NextToken->Parent->is(tok::semi) &&
727 State.LineContainsContinuedForLoopSection)
728 return true;
729 if (State.NextToken->Parent->is(tok::comma) &&
730 State.Stack.back().BreakAfterComma &&
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000731 !isTrailingComment(*State.NextToken))
Daniel Jasper4b866272013-02-01 11:00:45 +0000732 return true;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000733 if (State.NextToken->Type == TT_ObjCSelectorName &&
734 State.Stack.back().ColonPos != 0)
735 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000736 if ((State.NextToken->Type == TT_CtorInitializerColon ||
737 (State.NextToken->Parent->ClosesTemplateDeclaration &&
738 State.Stack.size() == 1)))
739 return true;
740 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000741 }
742
Daniel Jasperf7935112012-12-03 18:12:45 +0000743 FormatStyle Style;
744 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000745 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000746 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000747 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000748 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000749};
750
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000751class LexerBasedFormatTokenSource : public FormatTokenSource {
752public:
753 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000754 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000755 IdentTable(Lex.getLangOpts()) {
756 Lex.SetKeepWhitespaceMode(true);
757 }
758
759 virtual FormatToken getNextToken() {
760 if (GreaterStashed) {
761 FormatTok.NewlinesBefore = 0;
762 FormatTok.WhiteSpaceStart =
763 FormatTok.Tok.getLocation().getLocWithOffset(1);
764 FormatTok.WhiteSpaceLength = 0;
765 GreaterStashed = false;
766 return FormatTok;
767 }
768
769 FormatTok = FormatToken();
770 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000771 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000772 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000773 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
774 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000775
776 // Consume and record whitespace until we find a significant token.
777 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000778 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000779 FormatTok.HasUnescapedNewline =
780 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000781 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
782
783 if (FormatTok.Tok.is(tok::eof))
784 return FormatTok;
785 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000786 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000787 }
Manuel Klimekef920692013-01-07 07:56:50 +0000788
789 // Now FormatTok is the next non-whitespace token.
790 FormatTok.TokenLength = Text.size();
791
Manuel Klimek1abf7892013-01-04 23:34:14 +0000792 // In case the token starts with escaped newlines, we want to
793 // take them into account as whitespace - this pattern is quite frequent
794 // in macro definitions.
795 // FIXME: What do we want to do with other escaped spaces, and escaped
796 // spaces or newlines in the middle of tokens?
797 // FIXME: Add a more explicit test.
798 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000799 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000800 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000801 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000802 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000803 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000804 }
805
806 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000807 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000808 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000809 FormatTok.Tok.setKind(Info.getTokenID());
810 }
811
812 if (FormatTok.Tok.is(tok::greatergreater)) {
813 FormatTok.Tok.setKind(tok::greater);
814 GreaterStashed = true;
815 }
816
817 return FormatTok;
818 }
819
820private:
821 FormatToken FormatTok;
822 bool GreaterStashed;
823 Lexer &Lex;
824 SourceManager &SourceMgr;
825 IdentifierTable IdentTable;
826
827 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000828 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000829 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
830 Tok.getLength());
831 }
832};
833
Daniel Jasperf7935112012-12-03 18:12:45 +0000834class Formatter : public UnwrappedLineConsumer {
835public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000836 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
837 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000838 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000839 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000840 Whitespaces(SourceMgr), Ranges(Ranges) {
841 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000842
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000843 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000844
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000845 void deriveLocalStyle() {
846 unsigned CountBoundToVariable = 0;
847 unsigned CountBoundToType = 0;
848 bool HasCpp03IncompatibleFormat = false;
849 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
850 if (AnnotatedLines[i].First.Children.empty())
851 continue;
852 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
853 while (!Tok->Children.empty()) {
854 if (Tok->Type == TT_PointerOrReference) {
855 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
856 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
857 if (SpacesBefore && !SpacesAfter)
858 ++CountBoundToVariable;
859 else if (!SpacesBefore && SpacesAfter)
860 ++CountBoundToType;
861 }
862
863 if (Tok->Type == TT_TemplateCloser && Tok->Parent->Type ==
864 TT_TemplateCloser && Tok->FormatTok.WhiteSpaceLength == 0)
865 HasCpp03IncompatibleFormat = true;
866 Tok = &Tok->Children[0];
867 }
868 }
869 if (Style.DerivePointerBinding) {
870 if (CountBoundToType > CountBoundToVariable)
871 Style.PointerBindsToType = true;
872 else if (CountBoundToType < CountBoundToVariable)
873 Style.PointerBindsToType = false;
874 }
875 if (Style.Standard == FormatStyle::LS_Auto) {
876 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
877 : FormatStyle::LS_Cpp03;
878 }
879 }
880
Daniel Jasperf7935112012-12-03 18:12:45 +0000881 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000882 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000883 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000884 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000885 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000886 TokenAnnotator Annotator(Style, SourceMgr, Lex);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000887 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000888 Annotator.annotate(AnnotatedLines[i]);
889 }
890 deriveLocalStyle();
891 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
892 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000893 }
894 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
895 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000896 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000897 const AnnotatedLine &TheLine = *I;
898 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000899 unsigned Indent =
900 formatFirstToken(TheLine.First, TheLine.Level,
901 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000902 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000903 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000904 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000905 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000906 PreviousEndOfLineColumn = Formatter.format();
907 } else {
908 // If we did not reformat this unwrapped line, the column at the end of
909 // the last token is unchanged - thus, we can calculate the end of the
910 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000911 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000912 SourceMgr.getSpellingColumnNumber(
913 TheLine.Last->FormatTok.Tok.getLocation()) +
914 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000915 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000916 }
917 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000918 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000919 }
920
921private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000922 /// \brief Tries to merge lines into one.
923 ///
924 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
925 /// if possible; note that \c I will be incremented when lines are merged.
926 ///
927 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000928 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000929 std::vector<AnnotatedLine>::iterator &I,
930 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000931 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
932
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000933 // We can never merge stuff if there are trailing line comments.
934 if (I->Last->Type == TT_LineComment)
935 return;
936
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000937 // Check whether the UnwrappedLine can be put onto a single line. If
938 // so, this is bound to be the optimal solution (by definition) and we
939 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000940 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000941 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000942 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000943
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000944 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000945 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000946
Daniel Jasper25837aa2013-01-14 14:14:23 +0000947 if (I->Last->is(tok::l_brace)) {
948 tryMergeSimpleBlock(I, E, Limit);
949 } else if (I->First.is(tok::kw_if)) {
950 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000951 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
952 I->First.FormatTok.IsFirst)) {
953 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000954 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000955 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000956 }
957
Daniel Jasper39825ea2013-01-14 15:40:57 +0000958 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
959 std::vector<AnnotatedLine>::iterator E,
960 unsigned Limit) {
961 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000962 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
963 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000964 if (I + 2 != E && (I + 2)->InPPDirective &&
965 !(I + 2)->First.FormatTok.HasUnescapedNewline)
966 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000967 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000968 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000969 join(Line, *(++I));
970 }
971
Daniel Jasper25837aa2013-01-14 14:14:23 +0000972 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
973 std::vector<AnnotatedLine>::iterator E,
974 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000975 if (!Style.AllowShortIfStatementsOnASingleLine)
976 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000977 if ((I + 1)->InPPDirective != I->InPPDirective ||
978 ((I + 1)->InPPDirective &&
979 (I + 1)->First.FormatTok.HasUnescapedNewline))
980 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000981 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000982 if (Line.Last->isNot(tok::r_paren))
983 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000984 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000985 return;
986 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
987 return;
988 // Only inline simple if's (no nested if or else).
989 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
990 return;
991 join(Line, *(++I));
992 }
993
994 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000995 std::vector<AnnotatedLine>::iterator E,
996 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000997 // First, check that the current line allows merging. This is the case if
998 // we're not in a control flow statement and the last token is an opening
999 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001000 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001001 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001002 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1003 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1004 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1005 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001006 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001007 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1008 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001009 if (!AllowedTokens)
1010 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001011
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001012 AnnotatedToken *Tok = &(I + 1)->First;
1013 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1014 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1015 Tok->SpaceRequiredBefore = false;
1016 join(Line, *(I + 1));
1017 I += 1;
1018 } else {
1019 // Check that we still have three lines and they fit into the limit.
1020 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1021 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001022 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001023
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001024 // Second, check that the next line does not contain any braces - if it
1025 // does, readability declines when putting it into a single line.
1026 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1027 return;
1028 do {
1029 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1030 return;
1031 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1032 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001033
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001034 // Last, check that the third line contains a single closing brace.
1035 Tok = &(I + 2)->First;
1036 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1037 Tok->MustBreakBefore)
1038 return;
1039
1040 join(Line, *(I + 1));
1041 join(Line, *(I + 2));
1042 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001043 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001044 }
1045
1046 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1047 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001048 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1049 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001050 }
1051
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001052 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1053 A.Last->Children.push_back(B.First);
1054 while (!A.Last->Children.empty()) {
1055 A.Last->Children[0].Parent = A.Last;
1056 A.Last = &A.Last->Children[0];
1057 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001058 }
1059
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001060 bool touchesRanges(const AnnotatedLine &TheLine) {
1061 const FormatToken *First = &TheLine.First.FormatTok;
1062 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001063 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001064 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001065 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001066 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1067 Ranges[i].getBegin()) &&
1068 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1069 LineRange.getBegin()))
1070 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001071 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001072 return false;
1073 }
1074
1075 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001076 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001077 }
1078
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001079 /// \brief Add a new line and the required indent before the first Token
1080 /// of the \c UnwrappedLine if there was no structural parsing error.
1081 /// Returns the indent level of the \c UnwrappedLine.
1082 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1083 bool InPPDirective,
1084 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001085 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001086 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1087 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1088
Daniel Jasperbbc84152013-01-29 11:27:30 +00001089 unsigned Newlines =
1090 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001091 if (Newlines == 0 && !Tok.IsFirst)
1092 Newlines = 1;
1093 unsigned Indent = Level * 2;
1094
1095 bool IsAccessModifier = false;
1096 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1097 RootToken.is(tok::kw_private))
1098 IsAccessModifier = true;
1099 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1100 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1101 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1102 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1103 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1104 IsAccessModifier = true;
1105
1106 if (IsAccessModifier &&
1107 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1108 Indent += Style.AccessModifierOffset;
1109 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001110 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001111 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001112 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1113 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001114 }
1115 return Indent;
1116 }
1117
Alexander Kornienko116ba682013-01-14 11:34:14 +00001118 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001119 FormatStyle Style;
1120 Lexer &Lex;
1121 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001122 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001123 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001124 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001125 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001126};
1127
Daniel Jasperbbc84152013-01-29 11:27:30 +00001128tooling::Replacements
1129reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1130 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001131 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001132 OwningPtr<DiagnosticConsumer> DiagPrinter;
1133 if (DiagClient == 0) {
1134 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1135 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1136 DiagClient = DiagPrinter.get();
1137 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001138 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001139 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001140 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001141 Diagnostics.setSourceManager(&SourceMgr);
1142 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001143 return formatter.format();
1144}
1145
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001146LangOptions getFormattingLangOpts() {
1147 LangOptions LangOpts;
1148 LangOpts.CPlusPlus = 1;
1149 LangOpts.CPlusPlus11 = 1;
1150 LangOpts.Bool = 1;
1151 LangOpts.ObjC1 = 1;
1152 LangOpts.ObjC2 = 1;
1153 return LangOpts;
1154}
1155
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001156} // namespace format
1157} // namespace clang