blob: 7f78ac0bcf094626d0a3c494419dfa3bc4accbb5 [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 Jasper94f0e132013-02-06 20:07:35 +000083static bool isTrailingComment(const AnnotatedToken &Tok) {
84 return Tok.is(tok::comment) &&
85 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86}
87
Daniel Jasperaa701fa2013-01-18 08:44:07 +000088/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +000089///
Daniel Jasperaa701fa2013-01-18 08:44:07 +000090/// This includes special handling for certain constructs, e.g. the alignment of
91/// trailing line comments.
92class WhitespaceManager {
93public:
94 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
95
96 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
97 /// each \c AnnotatedToken.
98 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
99 unsigned Spaces, unsigned WhitespaceStartColumn,
100 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000101 // 2+ newlines mean an empty line separating logic scopes.
102 if (NewLines >= 2)
103 alignComments();
104
105 // Align line comments if they are trailing or if they continue other
106 // trailing comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000107 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000108 if (Style.ColumnLimit >=
109 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
110 Comments.push_back(StoredComment());
111 Comments.back().Tok = Tok.FormatTok;
112 Comments.back().Spaces = Spaces;
113 Comments.back().NewLines = NewLines;
Daniel Jasperf79f9352013-02-06 22:04:05 +0000114 if (NewLines == 0)
115 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
116 else
117 Comments.back().MinColumn = Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000118 Comments.back().MaxColumn =
119 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000120 return;
121 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000122 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000123
124 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000125 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000126 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000127 storeReplacement(Tok.FormatTok,
128 std::string(NewLines, '\n') + std::string(Spaces, ' '));
129 }
130
131 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
132 /// backslashes to escape newlines inside a preprocessor directive.
133 ///
134 /// This function and \c replaceWhitespace have the same behavior if
135 /// \c Newlines == 0.
136 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
137 unsigned Spaces, unsigned WhitespaceStartColumn,
138 const FormatStyle &Style) {
139 std::string NewLineText;
140 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000141 unsigned Offset =
142 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000143 for (unsigned i = 0; i < NewLines; ++i) {
144 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
145 NewLineText += "\\\n";
146 Offset = 0;
147 }
148 }
149 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
150 }
151
152 /// \brief Returns all the \c Replacements created during formatting.
153 const tooling::Replacements &generateReplacements() {
154 alignComments();
155 return Replaces;
156 }
157
158private:
159 /// \brief Structure to store a comment for later layout and alignment.
160 struct StoredComment {
161 FormatToken Tok;
162 unsigned MinColumn;
163 unsigned MaxColumn;
164 unsigned NewLines;
165 unsigned Spaces;
166 };
167 SmallVector<StoredComment, 16> Comments;
168 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
169
170 /// \brief Try to align all stashed comments.
171 void alignComments() {
172 unsigned MinColumn = 0;
173 unsigned MaxColumn = UINT_MAX;
174 comment_iterator Start = Comments.begin();
175 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
176 ++I) {
177 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
178 alignComments(Start, I, MinColumn);
179 MinColumn = I->MinColumn;
180 MaxColumn = I->MaxColumn;
181 Start = I;
182 } else {
183 MinColumn = std::max(MinColumn, I->MinColumn);
184 MaxColumn = std::min(MaxColumn, I->MaxColumn);
185 }
186 }
187 alignComments(Start, Comments.end(), MinColumn);
188 Comments.clear();
189 }
190
191 /// \brief Put all the comments between \p I and \p E into \p Column.
192 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
193 while (I != E) {
194 unsigned Spaces = I->Spaces + Column - I->MinColumn;
195 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
196 std::string(Spaces, ' '));
197 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000198 }
199 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000200
201 /// \brief Stores \p Text as the replacement for the whitespace in front of
202 /// \p Tok.
203 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000204 // Don't create a replacement, if it does not change anything.
205 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
206 Tok.WhiteSpaceLength) == Text)
207 return;
208
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000209 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
210 Tok.WhiteSpaceLength, Text));
211 }
212
213 SourceManager &SourceMgr;
214 tooling::Replacements Replaces;
215};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000216
Daniel Jasperf7935112012-12-03 18:12:45 +0000217class UnwrappedLineFormatter {
218public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000219 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000220 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000221 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000222 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000223 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000224 FirstIndent(FirstIndent), RootToken(RootToken),
225 Whitespaces(Whitespaces) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000226 }
227
Manuel Klimek1abf7892013-01-04 23:34:14 +0000228 /// \brief Formats an \c UnwrappedLine.
229 ///
230 /// \returns The column after the last token in the last line of the
231 /// \c UnwrappedLine.
232 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000233 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000234 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000235 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000236 State.NextToken = &RootToken;
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000237 State.Stack.push_back(
238 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
239 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000240 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000241 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000242
Manuel Klimek24998102013-01-16 14:55:28 +0000243 DEBUG({
244 DebugTokenState(*State.NextToken);
245 });
246
Daniel Jaspere9de2602012-12-06 09:56:08 +0000247 // The first token has already been indented and thus consumed.
248 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000249
Daniel Jasper4b866272013-02-01 11:00:45 +0000250 // If everything fits on a single line, just put it there.
251 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
252 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000253 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000254 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000255 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000256 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000257
258 // Find best solution in solution space.
259 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000260 }
261
262private:
Manuel Klimek24998102013-01-16 14:55:28 +0000263 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
264 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000265 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
266 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000267 llvm::errs();
268 }
269
Daniel Jasper337816e2013-01-11 10:22:12 +0000270 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000271 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
272 bool HasMultiParameterLine)
Daniel Jaspera836b902013-01-23 16:58:21 +0000273 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000274 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000275 AvoidBinPacking(AvoidBinPacking), BreakAfterComma(false),
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000276 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000277 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000278
Daniel Jasperf7935112012-12-03 18:12:45 +0000279 /// \brief The position to which a specific parenthesis level needs to be
280 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000281 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000282
Daniel Jaspere9de2602012-12-06 09:56:08 +0000283 /// \brief The position of the last space on each level.
284 ///
285 /// Used e.g. to break like:
286 /// functionCall(Parameter, otherCall(
287 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000288 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000289
Daniel Jaspera836b902013-01-23 16:58:21 +0000290 /// \brief This is the column of the first token after an assignment.
291 unsigned AssignmentColumn;
292
Daniel Jaspere9de2602012-12-06 09:56:08 +0000293 /// \brief The position the first "<<" operator encountered on each level.
294 ///
295 /// Used to align "<<" operators. 0 if no such operator has been encountered
296 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000297 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000298
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000299 /// \brief Whether a newline needs to be inserted before the block's closing
300 /// brace.
301 ///
302 /// We only want to insert a newline before the closing brace if there also
303 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000304 bool BreakBeforeClosingBrace;
305
Daniel Jasperca6623b2013-01-28 12:45:14 +0000306 /// \brief The column of a \c ? in a conditional expression;
307 unsigned QuestionColumn;
308
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000309 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
310 /// lines, in this context.
311 bool AvoidBinPacking;
312
313 /// \brief Break after the next comma (or all the commas in this context if
314 /// \c AvoidBinPacking is \c true).
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000315 bool BreakAfterComma;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000316
317 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000318 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000319
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000320 /// \brief The position of the colon in an ObjC method declaration/call.
321 unsigned ColonPos;
322
Daniel Jasper337816e2013-01-11 10:22:12 +0000323 bool operator<(const ParenState &Other) const {
324 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000325 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000326 if (LastSpace != Other.LastSpace)
327 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000328 if (AssignmentColumn != Other.AssignmentColumn)
329 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000330 if (FirstLessLess != Other.FirstLessLess)
331 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000332 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
333 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000334 if (QuestionColumn != Other.QuestionColumn)
335 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000336 if (AvoidBinPacking != Other.AvoidBinPacking)
337 return AvoidBinPacking;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000338 if (BreakAfterComma != Other.BreakAfterComma)
339 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000340 if (HasMultiParameterLine != Other.HasMultiParameterLine)
341 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000342 if (ColonPos != Other.ColonPos)
343 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000344 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000345 }
346 };
347
348 /// \brief The current state when indenting a unwrapped line.
349 ///
350 /// As the indenting tries different combinations this is copied by value.
351 struct LineState {
352 /// \brief The number of used columns in the current line.
353 unsigned Column;
354
355 /// \brief The token that needs to be next formatted.
356 const AnnotatedToken *NextToken;
357
Daniel Jasperbbc84152013-01-29 11:27:30 +0000358 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000359 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000360 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000361 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000362
363 /// \brief \c true if this line contains a continued for-loop section.
364 bool LineContainsContinuedForLoopSection;
365
Daniel Jasper337816e2013-01-11 10:22:12 +0000366 /// \brief A stack keeping track of properties applying to parenthesis
367 /// levels.
368 std::vector<ParenState> Stack;
369
370 /// \brief Comparison operator to be able to used \c LineState in \c map.
371 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000372 if (Other.NextToken != NextToken)
373 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000374 if (Other.Column != Column)
375 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000376 if (Other.VariablePos != VariablePos)
377 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000378 if (Other.LineContainsContinuedForLoopSection !=
379 LineContainsContinuedForLoopSection)
380 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000381 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000382 }
383 };
384
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000385 /// \brief Appends the next token to \p State and updates information
386 /// necessary for indentation.
387 ///
388 /// Puts the token on the current line if \p Newline is \c true and adds a
389 /// line break and necessary indentation otherwise.
390 ///
391 /// If \p DryRun is \c false, also creates and stores the required
392 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000393 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000394 const AnnotatedToken &Current = *State.NextToken;
395 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000396 assert(State.Stack.size());
397 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000398
Daniel Jasper4b866272013-02-01 11:00:45 +0000399 if (Current.Type == TT_ImplicitStringLiteral) {
400 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
401 State.NextToken->FormatTok.TokenLength;
402 if (State.NextToken->Children.empty())
403 State.NextToken = NULL;
404 else
405 State.NextToken = &State.NextToken->Children[0];
406 return;
407 }
408
Daniel Jasperf7935112012-12-03 18:12:45 +0000409 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000410 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000411 if (Current.is(tok::r_brace)) {
412 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000413 } else if (Current.is(tok::string_literal) &&
414 Previous.is(tok::string_literal)) {
415 State.Column = State.Column - Previous.FormatTok.TokenLength;
416 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000417 State.Stack[ParenLevel].FirstLessLess != 0) {
418 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000419 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000420 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000421 Current.is(tok::period) || Current.is(tok::arrow) ||
422 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000423 // Indent and extra 4 spaces after if we know the current expression is
424 // continued. Don't do that on the top level, as we already indent 4
425 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000426 State.Column = std::max(State.Stack.back().LastSpace,
427 State.Stack.back().Indent) + 4;
428 } else if (Current.Type == TT_ConditionalExpr) {
429 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000430 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
431 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
432 ParenLevel == 0)) {
433 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000434 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
435 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000436 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000437 } else if (Previous.Type == TT_BinaryOperator &&
438 State.Stack.back().AssignmentColumn != 0) {
439 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000440 } else if (Current.Type == TT_ObjCSelectorName) {
441 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
442 State.Column =
443 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
444 } else {
445 State.Column = State.Stack.back().Indent;
446 State.Stack.back().ColonPos =
447 State.Column + Current.FormatTok.TokenLength;
448 }
449 } else if (Previous.Type == TT_ObjCMethodExpr) {
450 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000451 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000452 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000453 }
454
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000455 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
456 State.Stack.back().BreakAfterComma = false;
457
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000458 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000459 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000460
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000461 if (!DryRun) {
462 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000463 Whitespaces.replaceWhitespace(Current, 1, State.Column,
464 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000465 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000466 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
467 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000468 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000469
Daniel Jasper337816e2013-01-11 10:22:12 +0000470 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000471 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000472 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000473 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000474 if (Current.is(tok::equal) &&
475 (RootToken.is(tok::kw_for) || ParenLevel == 0))
476 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000477
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000478 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
479 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000480 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000481
Daniel Jasperf7935112012-12-03 18:12:45 +0000482 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000483 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000484
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000485 if (Current.Type == TT_ObjCSelectorName &&
486 State.Stack.back().ColonPos == 0) {
487 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
488 State.Column + Spaces + Current.FormatTok.TokenLength)
489 State.Stack.back().ColonPos =
490 State.Stack.back().Indent + Current.LongestObjCSelectorName;
491 else
492 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000493 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000494 }
495
Daniel Jasperbcab4302013-01-09 10:40:23 +0000496 // FIXME: Do we need to do this for assignments nested in other
497 // expressions?
498 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper38396592013-02-06 15:23:09 +0000499 !isTrailingComment(Current) &&
Daniel Jasper206df732013-01-07 13:08:40 +0000500 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000501 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000502 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000503 if (Current.Type != TT_LineComment &&
504 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
505 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000506 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000507 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000508 State.Stack[ParenLevel].HasMultiParameterLine = true;
509
Daniel Jaspere9de2602012-12-06 09:56:08 +0000510 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000511 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
512 // Treat the condition inside an if as if it was a second function
513 // parameter, i.e. let nested calls have an indent of 4.
514 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000515 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000516 // Top-level spaces are exempt as that mostly leads to better results.
517 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000518 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000519 Previous.Type == TT_ConditionalExpr ||
520 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000521 getPrecedence(Previous) != prec::Assignment)
522 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000523 else if (Previous.ParameterCount > 1 &&
524 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000525 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000526 Previous.Type == TT_TemplateOpener))
527 // If this function has multiple parameters, indent nested calls from
528 // the start of the first parameter.
529 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000530 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000531
532 // If we break after an {, we should also break before the corresponding }.
533 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000534 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000535
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000536 if (State.Stack.back().AvoidBinPacking && Newline &&
537 (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000538 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000539 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000540 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
541 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000542 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
543 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000544 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000545
Daniel Jaspere941b162013-01-23 10:08:28 +0000546 // Any break on this level means that the parent level has been broken
547 // and we need to avoid bin packing there.
548 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000549 if (Line.First.isNot(tok::kw_for) || i != 1)
550 State.Stack[i].BreakAfterComma = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000551 }
552 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000553
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000554 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000555 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000556
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557 /// \brief Mark the next token as consumed in \p State and modify its stacks
558 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000560 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000561 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000562
Daniel Jasper337816e2013-01-11 10:22:12 +0000563 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
564 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000565 if (Current.is(tok::question))
566 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000567 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000568 !Current.MatchingParen->MustBreakBefore) {
569 AnnotatedToken *End = Current.MatchingParen;
570 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
571 End = &End->Children[0];
572 }
573 unsigned Length = End->TotalLength - Current.TotalLength + 1;
574 if (Length + State.Column > getColumnLimit())
575 State.Stack.back().BreakAfterComma = true;
576 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000577
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000578 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000579 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000580 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
581 Current.is(tok::l_brace) ||
582 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000583 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000584 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000585 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000586 NewIndent = 2 + State.Stack.back().LastSpace;
587 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000588 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000589 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000590 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000591 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000592 State.Stack.push_back(
593 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
594 State.Stack.back().HasMultiParameterLine));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000595 }
596
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000597 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000598 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000599 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
600 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
601 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000602 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000603 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000604
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000605 if (State.NextToken->Children.empty())
606 State.NextToken = NULL;
607 else
608 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000609
610 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000611 }
612
Daniel Jasper2df93312013-01-09 10:16:05 +0000613 unsigned getColumnLimit() {
614 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
615 }
616
Daniel Jasper4b866272013-02-01 11:00:45 +0000617 /// \brief An edge in the solution space starting from the \c LineState and
618 /// inserting a newline dependent on the \c bool.
619 typedef std::pair<bool, const LineState *> Edge;
620
621 /// \brief An item in the prioritized BFS search queue. The \c LineState was
622 /// reached using the \c Edge.
623 typedef std::pair<LineState, Edge> QueueItem;
624
625 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000626 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000627 /// This implements a variant of Dijkstra's algorithm on the graph that spans
628 /// the solution space (\c LineStates are the nodes). The algorithm tries to
629 /// find the shortest path (the one with lowest penalty) from \p InitialState
630 /// to a state where all tokens are placed.
631 unsigned analyzeSolutionSpace(const LineState &InitialState) {
632 // Insert start element into queue.
633 std::multimap<unsigned, QueueItem> Queue;
634 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000635 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000636 std::map<LineState, Edge> Seen;
637
638 // While not empty, take first element and follow edges.
639 while (!Queue.empty()) {
640 unsigned Penalty = Queue.begin()->first;
641 QueueItem Item = Queue.begin()->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000642 if (Item.first.NextToken == NULL) {
643 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000644 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000645 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000646 Queue.erase(Queue.begin());
647
648 if (Seen.find(Item.first) != Seen.end())
649 continue; // State already examined with lower penalty.
650
651 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
652 Item.first,
653 Edge(Item.second.first, Item.second.second))).first->first;
654
655 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
656 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
657 }
658
659 if (Queue.empty())
660 // We were unable to find a solution, do nothing.
661 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000662 return 0;
663
Daniel Jasper4b866272013-02-01 11:00:45 +0000664 // Reconstruct the solution.
665 // FIXME: Add debugging output.
666 Edge *CurrentEdge = &Queue.begin()->second.second;
667 while (CurrentEdge->second != NULL) {
668 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000669 if (CurrentEdge->first) {
670 DEBUG(llvm::errs() << "Penalty for splitting before "
671 << CurrentState.NextToken->FormatTok.Tok.getName()
672 << ": " << CurrentState.NextToken->SplitPenalty
673 << "\n");
674 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000675 addTokenToState(CurrentEdge->first, false, CurrentState);
676 CurrentEdge = &Seen[*CurrentEdge->second];
677 }
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000678 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000679
Daniel Jasper4b866272013-02-01 11:00:45 +0000680 // Return the column after the last token of the solution.
681 return Queue.begin()->second.first.Column;
682 }
683
684 /// \brief Add the following state to the analysis queue \p Queue.
685 ///
686 /// Assume the current state is \p OldState and has been reached with a
687 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
688 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
689 bool NewLine,
690 std::multimap<unsigned, QueueItem> &Queue) {
691 if (NewLine && !canBreak(OldState))
692 return;
693 if (!NewLine && mustBreak(OldState))
694 return;
695 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000696 if (NewLine)
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000697 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000698 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000699 if (State.Column > getColumnLimit()) {
700 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000701 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000702 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000703 Queue.insert(std::pair<unsigned, QueueItem>(
704 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
705 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000706
Daniel Jasper4b866272013-02-01 11:00:45 +0000707 /// \brief Returns \c true, if a line break after \p State is allowed.
708 bool canBreak(const LineState &State) {
709 if (!State.NextToken->CanBreakBefore &&
710 !(State.NextToken->is(tok::r_brace) &&
711 State.Stack.back().BreakBeforeClosingBrace))
712 return false;
713 // Trying to insert a parameter on a new line if there are already more than
714 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000715 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000716 State.Stack.back().AvoidBinPacking)
717 return false;
718 return true;
719 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000720
Daniel Jasper4b866272013-02-01 11:00:45 +0000721 /// \brief Returns \c true, if a line break after \p State is mandatory.
722 bool mustBreak(const LineState &State) {
723 if (State.NextToken->MustBreakBefore)
724 return true;
725 if (State.NextToken->is(tok::r_brace) &&
726 State.Stack.back().BreakBeforeClosingBrace)
727 return true;
728 if (State.NextToken->Parent->is(tok::semi) &&
729 State.LineContainsContinuedForLoopSection)
730 return true;
731 if (State.NextToken->Parent->is(tok::comma) &&
732 State.Stack.back().BreakAfterComma &&
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000733 !isTrailingComment(*State.NextToken))
Daniel Jasper4b866272013-02-01 11:00:45 +0000734 return true;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000735 if (State.NextToken->Type == TT_ObjCSelectorName &&
736 State.Stack.back().ColonPos != 0)
737 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000738 if ((State.NextToken->Type == TT_CtorInitializerColon ||
739 (State.NextToken->Parent->ClosesTemplateDeclaration &&
740 State.Stack.size() == 1)))
741 return true;
742 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000743 }
744
Daniel Jasperf7935112012-12-03 18:12:45 +0000745 FormatStyle Style;
746 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000747 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000748 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000749 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000750 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000751};
752
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000753class LexerBasedFormatTokenSource : public FormatTokenSource {
754public:
755 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000756 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000757 IdentTable(Lex.getLangOpts()) {
758 Lex.SetKeepWhitespaceMode(true);
759 }
760
761 virtual FormatToken getNextToken() {
762 if (GreaterStashed) {
763 FormatTok.NewlinesBefore = 0;
764 FormatTok.WhiteSpaceStart =
765 FormatTok.Tok.getLocation().getLocWithOffset(1);
766 FormatTok.WhiteSpaceLength = 0;
767 GreaterStashed = false;
768 return FormatTok;
769 }
770
771 FormatTok = FormatToken();
772 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000773 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000774 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000775 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
776 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000777
778 // Consume and record whitespace until we find a significant token.
779 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000780 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000781 FormatTok.HasUnescapedNewline =
782 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000783 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
784
785 if (FormatTok.Tok.is(tok::eof))
786 return FormatTok;
787 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000788 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000789 }
Manuel Klimekef920692013-01-07 07:56:50 +0000790
791 // Now FormatTok is the next non-whitespace token.
792 FormatTok.TokenLength = Text.size();
793
Manuel Klimek1abf7892013-01-04 23:34:14 +0000794 // In case the token starts with escaped newlines, we want to
795 // take them into account as whitespace - this pattern is quite frequent
796 // in macro definitions.
797 // FIXME: What do we want to do with other escaped spaces, and escaped
798 // spaces or newlines in the middle of tokens?
799 // FIXME: Add a more explicit test.
800 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000801 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000802 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000803 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000804 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000805 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000806 }
807
808 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000809 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000810 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000811 FormatTok.Tok.setKind(Info.getTokenID());
812 }
813
814 if (FormatTok.Tok.is(tok::greatergreater)) {
815 FormatTok.Tok.setKind(tok::greater);
816 GreaterStashed = true;
817 }
818
819 return FormatTok;
820 }
821
822private:
823 FormatToken FormatTok;
824 bool GreaterStashed;
825 Lexer &Lex;
826 SourceManager &SourceMgr;
827 IdentifierTable IdentTable;
828
829 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000830 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000831 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
832 Tok.getLength());
833 }
834};
835
Daniel Jasperf7935112012-12-03 18:12:45 +0000836class Formatter : public UnwrappedLineConsumer {
837public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000838 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
839 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000840 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000841 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000842 Whitespaces(SourceMgr), Ranges(Ranges) {
843 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000844
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000845 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000846
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000847 void deriveLocalStyle() {
848 unsigned CountBoundToVariable = 0;
849 unsigned CountBoundToType = 0;
850 bool HasCpp03IncompatibleFormat = false;
851 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
852 if (AnnotatedLines[i].First.Children.empty())
853 continue;
854 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
855 while (!Tok->Children.empty()) {
856 if (Tok->Type == TT_PointerOrReference) {
857 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
858 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
859 if (SpacesBefore && !SpacesAfter)
860 ++CountBoundToVariable;
861 else if (!SpacesBefore && SpacesAfter)
862 ++CountBoundToType;
863 }
864
865 if (Tok->Type == TT_TemplateCloser && Tok->Parent->Type ==
866 TT_TemplateCloser && Tok->FormatTok.WhiteSpaceLength == 0)
867 HasCpp03IncompatibleFormat = true;
868 Tok = &Tok->Children[0];
869 }
870 }
871 if (Style.DerivePointerBinding) {
872 if (CountBoundToType > CountBoundToVariable)
873 Style.PointerBindsToType = true;
874 else if (CountBoundToType < CountBoundToVariable)
875 Style.PointerBindsToType = false;
876 }
877 if (Style.Standard == FormatStyle::LS_Auto) {
878 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
879 : FormatStyle::LS_Cpp03;
880 }
881 }
882
Daniel Jasperf7935112012-12-03 18:12:45 +0000883 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000884 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000885 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000886 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000887 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000888 TokenAnnotator Annotator(Style, SourceMgr, Lex);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000889 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000890 Annotator.annotate(AnnotatedLines[i]);
891 }
892 deriveLocalStyle();
893 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
894 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000895 }
896 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
897 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000898 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000899 const AnnotatedLine &TheLine = *I;
900 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000901 unsigned Indent =
902 formatFirstToken(TheLine.First, TheLine.Level,
903 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000904 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000905 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000906 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000907 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000908 PreviousEndOfLineColumn = Formatter.format();
909 } else {
910 // If we did not reformat this unwrapped line, the column at the end of
911 // the last token is unchanged - thus, we can calculate the end of the
912 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000913 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000914 SourceMgr.getSpellingColumnNumber(
915 TheLine.Last->FormatTok.Tok.getLocation()) +
916 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000917 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000918 }
919 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000920 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000921 }
922
923private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000924 /// \brief Tries to merge lines into one.
925 ///
926 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
927 /// if possible; note that \c I will be incremented when lines are merged.
928 ///
929 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000930 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000931 std::vector<AnnotatedLine>::iterator &I,
932 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000933 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
934
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000935 // We can never merge stuff if there are trailing line comments.
936 if (I->Last->Type == TT_LineComment)
937 return;
938
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000939 // Check whether the UnwrappedLine can be put onto a single line. If
940 // so, this is bound to be the optimal solution (by definition) and we
941 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000942 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000943 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000944 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000945
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000946 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000947 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000948
Daniel Jasper25837aa2013-01-14 14:14:23 +0000949 if (I->Last->is(tok::l_brace)) {
950 tryMergeSimpleBlock(I, E, Limit);
951 } else if (I->First.is(tok::kw_if)) {
952 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000953 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
954 I->First.FormatTok.IsFirst)) {
955 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000956 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000957 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000958 }
959
Daniel Jasper39825ea2013-01-14 15:40:57 +0000960 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
961 std::vector<AnnotatedLine>::iterator E,
962 unsigned Limit) {
963 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000964 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
965 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000966 if (I + 2 != E && (I + 2)->InPPDirective &&
967 !(I + 2)->First.FormatTok.HasUnescapedNewline)
968 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000969 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000970 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000971 join(Line, *(++I));
972 }
973
Daniel Jasper25837aa2013-01-14 14:14:23 +0000974 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
975 std::vector<AnnotatedLine>::iterator E,
976 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000977 if (!Style.AllowShortIfStatementsOnASingleLine)
978 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000979 if ((I + 1)->InPPDirective != I->InPPDirective ||
980 ((I + 1)->InPPDirective &&
981 (I + 1)->First.FormatTok.HasUnescapedNewline))
982 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000983 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000984 if (Line.Last->isNot(tok::r_paren))
985 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000986 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000987 return;
988 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
989 return;
990 // Only inline simple if's (no nested if or else).
991 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
992 return;
993 join(Line, *(++I));
994 }
995
996 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000997 std::vector<AnnotatedLine>::iterator E,
998 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000999 // First, check that the current line allows merging. This is the case if
1000 // we're not in a control flow statement and the last token is an opening
1001 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001002 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001003 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001004 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1005 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1006 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1007 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001008 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001009 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1010 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001011 if (!AllowedTokens)
1012 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001013
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001014 AnnotatedToken *Tok = &(I + 1)->First;
1015 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1016 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1017 Tok->SpaceRequiredBefore = false;
1018 join(Line, *(I + 1));
1019 I += 1;
1020 } else {
1021 // Check that we still have three lines and they fit into the limit.
1022 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1023 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001024 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001025
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001026 // Second, check that the next line does not contain any braces - if it
1027 // does, readability declines when putting it into a single line.
1028 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1029 return;
1030 do {
1031 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1032 return;
1033 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1034 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001035
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001036 // Last, check that the third line contains a single closing brace.
1037 Tok = &(I + 2)->First;
1038 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1039 Tok->MustBreakBefore)
1040 return;
1041
1042 join(Line, *(I + 1));
1043 join(Line, *(I + 2));
1044 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001045 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001046 }
1047
1048 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1049 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001050 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1051 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001052 }
1053
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001054 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1055 A.Last->Children.push_back(B.First);
1056 while (!A.Last->Children.empty()) {
1057 A.Last->Children[0].Parent = A.Last;
1058 A.Last = &A.Last->Children[0];
1059 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001060 }
1061
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001062 bool touchesRanges(const AnnotatedLine &TheLine) {
1063 const FormatToken *First = &TheLine.First.FormatTok;
1064 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001065 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001066 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001067 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001068 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1069 Ranges[i].getBegin()) &&
1070 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1071 LineRange.getBegin()))
1072 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001073 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001074 return false;
1075 }
1076
1077 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001078 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001079 }
1080
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001081 /// \brief Add a new line and the required indent before the first Token
1082 /// of the \c UnwrappedLine if there was no structural parsing error.
1083 /// Returns the indent level of the \c UnwrappedLine.
1084 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1085 bool InPPDirective,
1086 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001087 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001088 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1089 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1090
Daniel Jasperbbc84152013-01-29 11:27:30 +00001091 unsigned Newlines =
1092 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001093 if (Newlines == 0 && !Tok.IsFirst)
1094 Newlines = 1;
1095 unsigned Indent = Level * 2;
1096
1097 bool IsAccessModifier = false;
1098 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1099 RootToken.is(tok::kw_private))
1100 IsAccessModifier = true;
1101 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1102 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1103 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1104 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1105 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1106 IsAccessModifier = true;
1107
1108 if (IsAccessModifier &&
1109 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1110 Indent += Style.AccessModifierOffset;
1111 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001112 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001113 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001114 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1115 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001116 }
1117 return Indent;
1118 }
1119
Alexander Kornienko116ba682013-01-14 11:34:14 +00001120 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001121 FormatStyle Style;
1122 Lexer &Lex;
1123 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001124 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001125 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001126 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001127 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001128};
1129
Daniel Jasperbbc84152013-01-29 11:27:30 +00001130tooling::Replacements
1131reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1132 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001133 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001134 OwningPtr<DiagnosticConsumer> DiagPrinter;
1135 if (DiagClient == 0) {
1136 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1137 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1138 DiagClient = DiagPrinter.get();
1139 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001140 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001141 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001142 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001143 Diagnostics.setSourceManager(&SourceMgr);
1144 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001145 return formatter.format();
1146}
1147
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001148LangOptions getFormattingLangOpts() {
1149 LangOptions LangOpts;
1150 LangOpts.CPlusPlus = 1;
1151 LangOpts.CPlusPlus11 = 1;
1152 LangOpts.Bool = 1;
1153 LangOpts.ObjC1 = 1;
1154 LangOpts.ObjC2 = 1;
1155 return LangOpts;
1156}
1157
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001158} // namespace format
1159} // namespace clang