blob: 39d70d3e5a4efc135d2a456d7e5336c7ff129992 [file] [log] [blame]
Daniel Jasperbac016b2012-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///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimekca547db2013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimekca547db2013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperbac016b2012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasper71607512013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasper71607512013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasper71607512013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek407a31a2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasper46ef8522013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Webered91bba2013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Weberbcfdd262013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Weber70848232013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasper71607512013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasper71607512013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
63 LT_PreprocessorDirective,
64 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000065 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000066 LT_ObjCMethodDecl,
67 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000068};
69
Daniel Jasper26f7e782013-01-08 14:56:18 +000070class AnnotatedToken {
71public:
Daniel Jasperdcc2a622013-01-18 08:44:07 +000072 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000073 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
74 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper0df6acd2013-01-16 14:59:02 +000075 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper26f7e782013-01-08 14:56:18 +000076
Daniel Jasperfeb18f52013-01-14 14:14:23 +000077 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
78 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
79
Daniel Jasper26f7e782013-01-08 14:56:18 +000080 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
81 return FormatTok.Tok.isObjCAtKeyword(Kind);
82 }
83
84 FormatToken FormatTok;
85
Daniel Jasperbac016b2012-12-03 18:12:45 +000086 TokenType Type;
87
Daniel Jasperbac016b2012-12-03 18:12:45 +000088 bool SpaceRequiredBefore;
89 bool CanBreakBefore;
90 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000091
92 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000093
Daniel Jasper0df6acd2013-01-16 14:59:02 +000094 AnnotatedToken *MatchingParen;
95
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +000096 /// \brief The total length of the line up to and including this token.
97 unsigned TotalLength;
98
Daniel Jasper26f7e782013-01-08 14:56:18 +000099 std::vector<AnnotatedToken> Children;
100 AnnotatedToken *Parent;
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000101
102 const AnnotatedToken *getPreviousNoneComment() const {
103 AnnotatedToken *Tok = Parent;
104 while (Tok != NULL && Tok->is(tok::comment))
105 Tok = Tok->Parent;
106 return Tok;
107 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000108};
109
Daniel Jasper995e8202013-01-14 13:08:07 +0000110class AnnotatedLine {
111public:
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000112 AnnotatedLine(const UnwrappedLine &Line)
113 : First(Line.Tokens.front()), Level(Line.Level),
114 InPPDirective(Line.InPPDirective) {
115 assert(!Line.Tokens.empty());
116 AnnotatedToken *Current = &First;
117 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
118 E = Line.Tokens.end();
119 I != E; ++I) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000120 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000121 Current->Children[0].Parent = Current;
122 Current = &Current->Children[0];
123 }
124 Last = Current;
125 }
126 AnnotatedLine(const AnnotatedLine &Other)
127 : First(Other.First), Type(Other.Type), Level(Other.Level),
128 InPPDirective(Other.InPPDirective) {
129 Last = &First;
130 while (!Last->Children.empty()) {
131 Last->Children[0].Parent = Last;
132 Last = &Last->Children[0];
133 }
134 }
135
Daniel Jasper995e8202013-01-14 13:08:07 +0000136 AnnotatedToken First;
137 AnnotatedToken *Last;
138
139 LineType Type;
140 unsigned Level;
141 bool InPPDirective;
142};
143
Daniel Jasper26f7e782013-01-08 14:56:18 +0000144static prec::Level getPrecedence(const AnnotatedToken &Tok) {
145 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +0000146}
147
Daniel Jasperbac016b2012-12-03 18:12:45 +0000148FormatStyle getLLVMStyle() {
149 FormatStyle LLVMStyle;
150 LLVMStyle.ColumnLimit = 80;
151 LLVMStyle.MaxEmptyLinesToKeep = 1;
152 LLVMStyle.PointerAndReferenceBindToType = false;
153 LLVMStyle.AccessModifierOffset = -2;
154 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +0000155 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000156 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000157 LLVMStyle.BinPackParameters = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000158 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000159 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000160 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000161 return LLVMStyle;
162}
163
164FormatStyle getGoogleStyle() {
165 FormatStyle GoogleStyle;
166 GoogleStyle.ColumnLimit = 80;
167 GoogleStyle.MaxEmptyLinesToKeep = 1;
168 GoogleStyle.PointerAndReferenceBindToType = true;
169 GoogleStyle.AccessModifierOffset = -1;
170 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +0000171 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000172 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000173 GoogleStyle.BinPackParameters = false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000174 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +0000175 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000176 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000177 return GoogleStyle;
178}
179
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000180FormatStyle getChromiumStyle() {
181 FormatStyle ChromiumStyle = getGoogleStyle();
182 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
183 return ChromiumStyle;
184}
185
Daniel Jasperbac016b2012-12-03 18:12:45 +0000186struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000187 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000188 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000189 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000190};
191
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000192/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000193///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000194/// This includes special handling for certain constructs, e.g. the alignment of
195/// trailing line comments.
196class WhitespaceManager {
197public:
198 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
199
200 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
201 /// each \c AnnotatedToken.
202 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
203 unsigned Spaces, unsigned WhitespaceStartColumn,
204 const FormatStyle &Style) {
205 if (Tok.Type == TT_LineComment && NewLines < 2 &&
206 (Tok.Parent != NULL || !Comments.empty())) {
207 if (Style.ColumnLimit >=
208 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
209 Comments.push_back(StoredComment());
210 Comments.back().Tok = Tok.FormatTok;
211 Comments.back().Spaces = Spaces;
212 Comments.back().NewLines = NewLines;
213 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
214 Comments.back().MaxColumn = Style.ColumnLimit -
215 Spaces - Tok.FormatTok.TokenLength;
216 return;
217 }
218 } else if (NewLines == 0 && Tok.Children.empty() &&
219 Tok.Type != TT_LineComment) {
220 alignComments();
221 }
222 storeReplacement(Tok.FormatTok,
223 std::string(NewLines, '\n') + std::string(Spaces, ' '));
224 }
225
226 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
227 /// backslashes to escape newlines inside a preprocessor directive.
228 ///
229 /// This function and \c replaceWhitespace have the same behavior if
230 /// \c Newlines == 0.
231 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
232 unsigned Spaces, unsigned WhitespaceStartColumn,
233 const FormatStyle &Style) {
234 std::string NewLineText;
235 if (NewLines > 0) {
236 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
237 WhitespaceStartColumn);
238 for (unsigned i = 0; i < NewLines; ++i) {
239 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
240 NewLineText += "\\\n";
241 Offset = 0;
242 }
243 }
244 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
245 }
246
247 /// \brief Returns all the \c Replacements created during formatting.
248 const tooling::Replacements &generateReplacements() {
249 alignComments();
250 return Replaces;
251 }
252
253private:
254 /// \brief Structure to store a comment for later layout and alignment.
255 struct StoredComment {
256 FormatToken Tok;
257 unsigned MinColumn;
258 unsigned MaxColumn;
259 unsigned NewLines;
260 unsigned Spaces;
261 };
262 SmallVector<StoredComment, 16> Comments;
263 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
264
265 /// \brief Try to align all stashed comments.
266 void alignComments() {
267 unsigned MinColumn = 0;
268 unsigned MaxColumn = UINT_MAX;
269 comment_iterator Start = Comments.begin();
270 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
271 ++I) {
272 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
273 alignComments(Start, I, MinColumn);
274 MinColumn = I->MinColumn;
275 MaxColumn = I->MaxColumn;
276 Start = I;
277 } else {
278 MinColumn = std::max(MinColumn, I->MinColumn);
279 MaxColumn = std::min(MaxColumn, I->MaxColumn);
280 }
281 }
282 alignComments(Start, Comments.end(), MinColumn);
283 Comments.clear();
284 }
285
286 /// \brief Put all the comments between \p I and \p E into \p Column.
287 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
288 while (I != E) {
289 unsigned Spaces = I->Spaces + Column - I->MinColumn;
290 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
291 std::string(Spaces, ' '));
292 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000293 }
294 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000295
296 /// \brief Stores \p Text as the replacement for the whitespace in front of
297 /// \p Tok.
298 void storeReplacement(const FormatToken &Tok, const std::string Text) {
299 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
300 Tok.WhiteSpaceLength, Text));
301 }
302
303 SourceManager &SourceMgr;
304 tooling::Replacements Replaces;
305};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000306
Nico Webere8ccc812013-01-12 22:48:47 +0000307/// \brief Returns if a token is an Objective-C selector name.
308///
Nico Weberea865632013-01-12 22:51:13 +0000309/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Webere8ccc812013-01-12 22:48:47 +0000310static bool isObjCSelectorName(const AnnotatedToken &Tok) {
311 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
312 Tok.Children[0].is(tok::colon) &&
313 Tok.Children[0].Type == TT_ObjCMethodExpr;
314}
315
Daniel Jasperbac016b2012-12-03 18:12:45 +0000316class UnwrappedLineFormatter {
317public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000318 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000319 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000320 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000321 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000322 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000323 FirstIndent(FirstIndent), RootToken(RootToken),
324 Whitespaces(Whitespaces) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000325 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000326 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000327 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000328 }
329
Manuel Klimekd4397b92013-01-04 23:34:14 +0000330 /// \brief Formats an \c UnwrappedLine.
331 ///
332 /// \returns The column after the last token in the last line of the
333 /// \c UnwrappedLine.
334 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000335 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000336 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000337 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000338 State.NextToken = &RootToken;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000339 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000340 State.ForLoopVariablePos = 0;
341 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000342 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000343
Manuel Klimekca547db2013-01-16 14:55:28 +0000344 DEBUG({
345 DebugTokenState(*State.NextToken);
346 });
347
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000348 // The first token has already been indented and thus consumed.
349 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000350
351 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000352 while (State.NextToken != NULL) {
Manuel Klimek19132302013-01-15 16:41:02 +0000353 if (State.NextToken->Type == TT_ImplicitStringLiteral)
354 // We will not touch the rest of the white space in this
355 // \c UnwrappedLine. The returned value can also not matter, as we
356 // cannot continue an top-level implicit string literal on the next
357 // line.
358 return 0;
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000359 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000360 addTokenToState(false, false, State);
361 } else {
362 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
363 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimekca547db2013-01-16 14:55:28 +0000364 DEBUG({
365 if (Break < NoBreak)
366 llvm::errs() << "\n";
367 else
368 llvm::errs() << " ";
369 llvm::errs() << "<";
370 DebugPenalty(Break, Break < NoBreak);
371 llvm::errs() << "/";
372 DebugPenalty(NoBreak, !(Break < NoBreak));
373 llvm::errs() << "> ";
374 DebugTokenState(*State.NextToken);
375 });
Daniel Jasper1321eb52012-12-18 21:05:13 +0000376 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000377 if (State.NextToken != NULL &&
378 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
379 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000380 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000381 State.Stack.back().BreakAfterComma = true;
382 }
Daniel Jasper1321eb52012-12-18 21:05:13 +0000383 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000384 }
Manuel Klimekca547db2013-01-16 14:55:28 +0000385 DEBUG(llvm::errs() << "\n");
Manuel Klimekd4397b92013-01-04 23:34:14 +0000386 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000387 }
388
389private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000390 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
391 const Token &Tok = AnnotatedTok.FormatTok.Tok;
392 llvm::errs()
393 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
394 Tok.getLength());
395 llvm::errs();
396 }
397
398 void DebugPenalty(unsigned Penalty, bool Winner) {
399 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
400 if (Penalty == UINT_MAX)
401 llvm::errs() << "MAX";
402 else
403 llvm::errs() << Penalty;
404 llvm::errs().resetColor();
405 }
406
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000407 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000408 ParenState(unsigned Indent, unsigned LastSpace)
409 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000410 BreakBeforeClosingBrace(false), BreakAfterComma(false),
411 HasMultiParameterLine(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000412
Daniel Jasperbac016b2012-12-03 18:12:45 +0000413 /// \brief The position to which a specific parenthesis level needs to be
414 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000415 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000416
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000417 /// \brief The position of the last space on each level.
418 ///
419 /// Used e.g. to break like:
420 /// functionCall(Parameter, otherCall(
421 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000422 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000423
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000424 /// \brief The position the first "<<" operator encountered on each level.
425 ///
426 /// Used to align "<<" operators. 0 if no such operator has been encountered
427 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000428 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000429
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000430 /// \brief Whether a newline needs to be inserted before the block's closing
431 /// brace.
432 ///
433 /// We only want to insert a newline before the closing brace if there also
434 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000435 bool BreakBeforeClosingBrace;
436
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000437 bool BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000438 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000439
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000440 bool operator<(const ParenState &Other) const {
441 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000442 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000443 if (LastSpace != Other.LastSpace)
444 return LastSpace < Other.LastSpace;
445 if (FirstLessLess != Other.FirstLessLess)
446 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000447 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
448 return BreakBeforeClosingBrace;
Daniel Jasperb3123142013-01-12 07:36:22 +0000449 if (BreakAfterComma != Other.BreakAfterComma)
450 return BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000451 if (HasMultiParameterLine != Other.HasMultiParameterLine)
452 return HasMultiParameterLine;
Daniel Jasperb3123142013-01-12 07:36:22 +0000453 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000454 }
455 };
456
457 /// \brief The current state when indenting a unwrapped line.
458 ///
459 /// As the indenting tries different combinations this is copied by value.
460 struct LineState {
461 /// \brief The number of used columns in the current line.
462 unsigned Column;
463
464 /// \brief The token that needs to be next formatted.
465 const AnnotatedToken *NextToken;
466
467 /// \brief The parenthesis level of the first token on the current line.
468 unsigned StartOfLineLevel;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000469
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000470 /// \brief The column of the first variable in a for-loop declaration.
471 ///
472 /// Used to align the second variable if necessary.
473 unsigned ForLoopVariablePos;
474
475 /// \brief \c true if this line contains a continued for-loop section.
476 bool LineContainsContinuedForLoopSection;
477
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000478 /// \brief A stack keeping track of properties applying to parenthesis
479 /// levels.
480 std::vector<ParenState> Stack;
481
482 /// \brief Comparison operator to be able to used \c LineState in \c map.
483 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000484 if (Other.NextToken != NextToken)
485 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000486 if (Other.Column != Column)
487 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000488 if (Other.StartOfLineLevel != StartOfLineLevel)
489 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000490 if (Other.ForLoopVariablePos != ForLoopVariablePos)
491 return Other.ForLoopVariablePos < ForLoopVariablePos;
492 if (Other.LineContainsContinuedForLoopSection !=
493 LineContainsContinuedForLoopSection)
494 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000495 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000496 }
497 };
498
Daniel Jasper20409152012-12-04 14:54:30 +0000499 /// \brief Appends the next token to \p State and updates information
500 /// necessary for indentation.
501 ///
502 /// Puts the token on the current line if \p Newline is \c true and adds a
503 /// line break and necessary indentation otherwise.
504 ///
505 /// If \p DryRun is \c false, also creates and stores the required
506 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000507 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000508 const AnnotatedToken &Current = *State.NextToken;
509 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000510 assert(State.Stack.size());
511 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000512
513 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000514 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000515 if (Current.is(tok::r_brace)) {
516 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000517 } else if (Current.is(tok::string_literal) &&
518 Previous.is(tok::string_literal)) {
519 State.Column = State.Column - Previous.FormatTok.TokenLength;
520 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000521 State.Stack[ParenLevel].FirstLessLess != 0) {
522 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000523 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-01-09 07:06:56 +0000524 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
525 Current.is(tok::period) || Previous.is(tok::question) ||
526 Previous.Type == TT_ConditionalExpr)) {
527 // Indent and extra 4 spaces after if we know the current expression is
528 // continued. Don't do that on the top level, as we already indent 4
529 // there.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000530 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000531 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000532 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000533 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000534 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000535 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000536 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000537 }
538
Manuel Klimek2851c162013-01-10 14:36:46 +0000539 // A line starting with a closing brace is assumed to be correct for the
540 // same level as before the opening brace.
541 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000542
Daniel Jasper26f7e782013-01-08 14:56:18 +0000543 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000544 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000545
Manuel Klimek060143e2013-01-02 18:33:23 +0000546 if (!DryRun) {
547 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000548 Whitespaces.replaceWhitespace(Current, 1, State.Column,
549 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000550 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000551 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
552 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000553 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000554
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000555 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Weberf681fa82013-01-12 07:05:25 +0000556 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000557 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000558 } else {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000559 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
560 State.ForLoopVariablePos = State.Column -
561 Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000562
Daniel Jasper26f7e782013-01-08 14:56:18 +0000563 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
564 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000565 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000566
Daniel Jasperbac016b2012-12-03 18:12:45 +0000567 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000568 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000569
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000570 // FIXME: Do we need to do this for assignments nested in other
571 // expressions?
572 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000573 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000574 Previous.is(tok::kw_return)))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000575 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000576 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000577 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000578 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000579 if (Current.getPreviousNoneComment()->is(tok::comma) &&
580 Current.isNot(tok::comment))
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000581 State.Stack[ParenLevel].HasMultiParameterLine = true;
582
Daniel Jasper1321eb52012-12-18 21:05:13 +0000583
Daniel Jasper9cda8002013-01-07 13:08:40 +0000584 // Top-level spaces that are not part of assignments are exempt as that
585 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000586 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000587 if (Spaces > 0 &&
588 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000589 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000590 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000591
592 // If we break after an {, we should also break before the corresponding }.
593 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000594 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000595
596 // If we are breaking after '(', '{', '<' or ',', we need to break after
597 // future commas as well to avoid bin packing.
598 if (!Style.BinPackParameters && Newline &&
599 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
600 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
601 State.Stack.back().BreakAfterComma = true;
602
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000603 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000604 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000605
Daniel Jasper20409152012-12-04 14:54:30 +0000606 /// \brief Mark the next token as consumed in \p State and modify its stacks
607 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000608 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000609 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000610 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000611
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000612 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
613 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000614
Daniel Jaspercf225b62012-12-24 13:43:52 +0000615 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000616 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000617 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
618 Current.is(tok::l_brace) ||
619 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000620 unsigned NewIndent;
Manuel Klimek2851c162013-01-10 14:36:46 +0000621 if (Current.is(tok::l_brace)) {
622 // FIXME: This does not work with nested static initializers.
623 // Implement a better handling for static initializers and similar
624 // constructs.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000625 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000626 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000627 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000628 }
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000629 State.Stack.push_back(
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000630 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000631
632 // If the entire set of parameters will not fit on the current line, we
633 // will need to break after commas on this level to avoid bin-packing.
634 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
635 !Current.Children.empty()) {
636 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
637 Current.MatchingParen->TotalLength -
638 Current.Children[0].TotalLength) {
639 State.Stack.back().BreakAfterComma = true;
640 }
641 }
Daniel Jasper20409152012-12-04 14:54:30 +0000642 }
643
Daniel Jaspercf225b62012-12-24 13:43:52 +0000644 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000645 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000646 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
647 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
648 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000649 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000650 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000651
Daniel Jasper26f7e782013-01-08 14:56:18 +0000652 if (State.NextToken->Children.empty())
653 State.NextToken = NULL;
654 else
655 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000656
657 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000658 }
659
Nico Weberdecf7bc2013-01-07 15:15:29 +0000660 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000661 unsigned splitPenalty(const AnnotatedToken &Tok) {
662 const AnnotatedToken &Left = Tok;
663 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000664
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000665 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
666 return 50;
667 if (Left.is(tok::equal) && Right.is(tok::l_brace))
668 return 150;
669
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000670 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000671 if (RootToken.is(tok::kw_for) &&
672 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000673 return 20;
674
Daniel Jasper26f7e782013-01-08 14:56:18 +0000675 if (Left.is(tok::semi) || Left.is(tok::comma) ||
676 Left.ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000677 return 0;
Nico Webere8ccc812013-01-12 22:48:47 +0000678
679 // In Objective-C method expressions, prefer breaking before "param:" over
680 // breaking after it.
681 if (isObjCSelectorName(Right))
682 return 0;
683 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
684 return 20;
685
Daniel Jasper26f7e782013-01-08 14:56:18 +0000686 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000687 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000688
Daniel Jasper9c837d02013-01-09 07:06:56 +0000689 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
690 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000691 prec::Level Level = getPrecedence(Left);
692
693 // Breaking after an assignment leads to a bad result as the two sides of
694 // the assignment are visually very close together.
695 if (Level == prec::Assignment)
696 return 50;
697
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000698 if (Level != prec::Unknown)
699 return Level;
700
Daniel Jasper26f7e782013-01-08 14:56:18 +0000701 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000702 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000703
Daniel Jasperbac016b2012-12-03 18:12:45 +0000704 return 3;
705 }
706
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000707 unsigned getColumnLimit() {
708 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
709 }
710
Daniel Jasperbac016b2012-12-03 18:12:45 +0000711 /// \brief Calculate the number of lines needed to format the remaining part
712 /// of the unwrapped line.
713 ///
714 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000715 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000716 /// added after the previous token.
717 ///
718 /// \param StopAt is used for optimization. If we can determine that we'll
719 /// definitely need at least \p StopAt additional lines, we already know of a
720 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000721 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000722 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000723 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000724 return 0;
725
Daniel Jasper26f7e782013-01-08 14:56:18 +0000726 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000727 return UINT_MAX;
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000728 if (NewLine && !State.NextToken->CanBreakBefore &&
729 !(State.NextToken->is(tok::r_brace) &&
730 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000731 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000732 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000733 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000734 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000735 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000736 State.LineContainsContinuedForLoopSection)
737 return UINT_MAX;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000738 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000739 State.NextToken->isNot(tok::comment) &&
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000740 State.Stack.back().BreakAfterComma)
741 return UINT_MAX;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000742 // Trying to insert a parameter on a new line if there are already more than
743 // one parameter on the current line is bin packing.
744 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
745 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
746 return UINT_MAX;
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000747 if (!NewLine && State.NextToken->Type == TT_CtorInitializerColon)
748 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000749
Daniel Jasper33182dd2012-12-05 14:57:28 +0000750 unsigned CurrentPenalty = 0;
751 if (NewLine) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000752 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000753 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000754 } else {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000755 if (State.Stack.size() < State.StartOfLineLevel &&
756 State.NextToken->is(tok::identifier))
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000757 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000758 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000759 }
760
Daniel Jasper20409152012-12-04 14:54:30 +0000761 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000762
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000763 // Exceeding column limit is bad, assign penalty.
764 if (State.Column > getColumnLimit()) {
765 unsigned ExcessCharacters = State.Column - getColumnLimit();
766 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
767 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000768
Daniel Jasperbac016b2012-12-03 18:12:45 +0000769 if (StopAt <= CurrentPenalty)
770 return UINT_MAX;
771 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000772 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000773 if (I != Memory.end()) {
774 // If this state has already been examined, we can safely return the
775 // previous result if we
776 // - have not hit the optimatization (and thus returned UINT_MAX) OR
777 // - are now computing for a smaller or equal StopAt.
778 unsigned SavedResult = I->second.first;
779 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000780 if (SavedResult != UINT_MAX)
781 return SavedResult + CurrentPenalty;
782 else if (StopAt <= SavedStopAt)
783 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000784 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000785
786 unsigned NoBreak = calcPenalty(State, false, StopAt);
787 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
788 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000789
790 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
791 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000792 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000793
794 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000795 }
796
Daniel Jasperbac016b2012-12-03 18:12:45 +0000797 FormatStyle Style;
798 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000799 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000800 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000801 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000802 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803
Daniel Jasper33182dd2012-12-05 14:57:28 +0000804 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000805 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000806 StateMap Memory;
807
Daniel Jasperbac016b2012-12-03 18:12:45 +0000808 OptimizationParameters Parameters;
809};
810
811/// \brief Determines extra information about the tokens comprising an
812/// \c UnwrappedLine.
813class TokenAnnotator {
814public:
Daniel Jasper995e8202013-01-14 13:08:07 +0000815 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
816 AnnotatedLine &Line)
817 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000818
819 /// \brief A parser that gathers additional information about tokens.
820 ///
821 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
822 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
823 /// into template parameter lists.
824 class AnnotatingParser {
825 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000826 AnnotatingParser(AnnotatedToken &RootToken)
Nico Weberbcfdd262013-01-12 06:18:40 +0000827 : CurrentToken(&RootToken), KeywordVirtualFound(false),
828 ColonIsObjCMethodExpr(false) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000829
Nico Weber6a21a552013-01-18 02:43:57 +0000830 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
831 struct ObjCSelectorRAII {
832 AnnotatingParser &P;
833 bool ColonWasObjCMethodExpr;
834
835 ObjCSelectorRAII(AnnotatingParser &P)
836 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
837
838 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
839
840 void markStart(AnnotatedToken &Left) {
841 P.ColonIsObjCMethodExpr = true;
842 Left.Type = TT_ObjCMethodExpr;
843 }
844
845 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
846 };
847
848
Daniel Jasper20409152012-12-04 14:54:30 +0000849 bool parseAngle() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000850 if (CurrentToken == NULL)
851 return false;
852 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000853 while (CurrentToken != NULL) {
854 if (CurrentToken->is(tok::greater)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000855 Left->MatchingParen = CurrentToken;
856 CurrentToken->MatchingParen = Left;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000857 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000858 next();
859 return true;
860 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000861 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
862 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000863 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000864 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
865 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000866 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000867 if (!consumeToken())
868 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000869 }
870 return false;
871 }
872
Nico Weber5096a442013-01-17 17:17:19 +0000873 bool parseParens(bool LookForDecls = false) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000874 if (CurrentToken == NULL)
875 return false;
Nico Weber6a21a552013-01-18 02:43:57 +0000876 bool StartsObjCMethodExpr = false;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000877 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber6a21a552013-01-18 02:43:57 +0000878 if (CurrentToken->is(tok::caret)) {
879 // ^( starts a block.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000880 Left->Type = TT_ObjCBlockLParen;
Nico Weber6a21a552013-01-18 02:43:57 +0000881 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
882 // @selector( starts a selector.
883 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
884 MaybeSel->Parent->is(tok::at)) {
885 StartsObjCMethodExpr = true;
886 }
887 }
888
889 ObjCSelectorRAII objCSelector(*this);
890 if (StartsObjCMethodExpr)
891 objCSelector.markStart(*Left);
892
Daniel Jasper26f7e782013-01-08 14:56:18 +0000893 while (CurrentToken != NULL) {
Nico Weber5096a442013-01-17 17:17:19 +0000894 // LookForDecls is set when "if (" has been seen. Check for
895 // 'identifier' '*' 'identifier' followed by not '=' -- this
896 // '*' has to be a binary operator but determineStarAmpUsage() will
897 // categorize it as an unary operator, so set the right type here.
898 if (LookForDecls && !CurrentToken->Children.empty()) {
899 AnnotatedToken &Prev = *CurrentToken->Parent;
900 AnnotatedToken &Next = CurrentToken->Children[0];
901 if (Prev.Parent->is(tok::identifier) &&
902 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
903 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
904 Prev.Type = TT_BinaryOperator;
905 LookForDecls = false;
906 }
907 }
908
Daniel Jasper26f7e782013-01-08 14:56:18 +0000909 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000910 Left->MatchingParen = CurrentToken;
911 CurrentToken->MatchingParen = Left;
Nico Weber6a21a552013-01-18 02:43:57 +0000912
913 if (StartsObjCMethodExpr)
914 objCSelector.markEnd(*CurrentToken);
915
Daniel Jasperbac016b2012-12-03 18:12:45 +0000916 next();
917 return true;
918 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000919 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000920 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000921 if (!consumeToken())
922 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000923 }
924 return false;
925 }
926
Daniel Jasper20409152012-12-04 14:54:30 +0000927 bool parseSquare() {
Nico Weberbcfdd262013-01-12 06:18:40 +0000928 if (!CurrentToken)
929 return false;
930
931 // A '[' could be an index subscript (after an indentifier or after
932 // ')' or ']'), or it could be the start of an Objective-C method
933 // expression.
934 AnnotatedToken *LSquare = CurrentToken->Parent;
935 bool StartsObjCMethodExpr =
936 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
937 LSquare->Parent->is(tok::l_square) ||
938 LSquare->Parent->is(tok::l_paren) ||
939 LSquare->Parent->is(tok::kw_return) ||
940 LSquare->Parent->is(tok::kw_throw) ||
941 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
942 true, true) > prec::Unknown;
943
Nico Weber6a21a552013-01-18 02:43:57 +0000944 ObjCSelectorRAII objCSelector(*this);
945 if (StartsObjCMethodExpr)
946 objCSelector.markStart(*LSquare);
Nico Weberbcfdd262013-01-12 06:18:40 +0000947
Daniel Jasper26f7e782013-01-08 14:56:18 +0000948 while (CurrentToken != NULL) {
949 if (CurrentToken->is(tok::r_square)) {
Nico Weber6a21a552013-01-18 02:43:57 +0000950 if (StartsObjCMethodExpr)
951 objCSelector.markEnd(*CurrentToken);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000952 next();
953 return true;
954 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000955 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000957 if (!consumeToken())
958 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000959 }
960 return false;
961 }
962
Daniel Jasper700e7102013-01-10 09:26:47 +0000963 bool parseBrace() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000964 // Lines are fine to end with '{'.
965 if (CurrentToken == NULL)
966 return true;
967 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper700e7102013-01-10 09:26:47 +0000968 while (CurrentToken != NULL) {
969 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000970 Left->MatchingParen = CurrentToken;
971 CurrentToken->MatchingParen = Left;
Daniel Jasper700e7102013-01-10 09:26:47 +0000972 next();
973 return true;
974 }
975 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
976 return false;
977 if (!consumeToken())
978 return false;
979 }
Daniel Jasper700e7102013-01-10 09:26:47 +0000980 return true;
981 }
982
Daniel Jasper20409152012-12-04 14:54:30 +0000983 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000984 while (CurrentToken != NULL) {
985 if (CurrentToken->is(tok::colon)) {
986 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000987 next();
988 return true;
989 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000990 if (!consumeToken())
991 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000992 }
993 return false;
994 }
995
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000996 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000997 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
998 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000999 next();
1000 if (!parseAngle())
1001 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001002 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001003 parseLine();
1004 return true;
1005 }
1006 return false;
1007 }
1008
Daniel Jasper1f42f112013-01-04 18:52:56 +00001009 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001010 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001011 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001012 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-01-10 23:11:41 +00001013 case tok::plus:
1014 case tok::minus:
1015 // At the start of the line, +/- specific ObjectiveC method
1016 // declarations.
1017 if (Tok->Parent == NULL)
1018 Tok->Type = TT_ObjCMethodSpecifier;
1019 break;
Nico Weberbcfdd262013-01-12 06:18:40 +00001020 case tok::colon:
1021 // Colons from ?: are handled in parseConditional().
Daniel Jasper1f2b0782013-01-16 16:23:19 +00001022 if (Tok->Parent->is(tok::r_paren))
1023 Tok->Type = TT_CtorInitializerColon;
Nico Weberbcfdd262013-01-12 06:18:40 +00001024 if (ColonIsObjCMethodExpr)
1025 Tok->Type = TT_ObjCMethodExpr;
1026 break;
Nico Weber5096a442013-01-17 17:17:19 +00001027 case tok::kw_if:
1028 case tok::kw_while:
1029 if (CurrentToken->is(tok::l_paren)) {
1030 next();
1031 if (!parseParens(/*LookForDecls=*/true))
1032 return false;
1033 }
1034 break;
Nico Weber94fb7292013-01-18 05:50:57 +00001035 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001036 if (!parseParens())
1037 return false;
Nico Weber94fb7292013-01-18 05:50:57 +00001038 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001039 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001040 if (!parseSquare())
1041 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001042 break;
Daniel Jasper700e7102013-01-10 09:26:47 +00001043 case tok::l_brace:
1044 if (!parseBrace())
1045 return false;
1046 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001047 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +00001048 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +00001049 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001050 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001051 Tok->Type = TT_BinaryOperator;
1052 CurrentToken = Tok;
1053 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001054 }
1055 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001056 case tok::r_paren:
1057 case tok::r_square:
1058 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +00001059 case tok::r_brace:
1060 // Lines can start with '}'.
1061 if (Tok->Parent != NULL)
1062 return false;
1063 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001064 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001065 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001066 break;
1067 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001068 if (CurrentToken->is(tok::l_paren)) {
1069 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001070 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001071 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1072 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001073 next();
1074 }
1075 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001076 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1077 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001078 next();
1079 }
1080 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001081 break;
1082 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +00001083 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001084 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001085 case tok::kw_template:
1086 parseTemplateDeclaration();
1087 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001088 default:
1089 break;
1090 }
Daniel Jasper1f42f112013-01-04 18:52:56 +00001091 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001092 }
1093
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001094 void parseIncludeDirective() {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001095 next();
1096 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1097 next();
1098 while (CurrentToken != NULL) {
1099 CurrentToken->Type = TT_ImplicitStringLiteral;
1100 next();
1101 }
1102 } else {
1103 while (CurrentToken != NULL) {
1104 next();
1105 }
1106 }
1107 }
1108
1109 void parseWarningOrError() {
1110 next();
1111 // We still want to format the whitespace left of the first token of the
1112 // warning or error.
1113 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001114 while (CurrentToken != NULL) {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001115 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001116 next();
1117 }
1118 }
1119
1120 void parsePreprocessorDirective() {
1121 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001122 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001123 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001124 // Hashes in the middle of a line can lead to any strange token
1125 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001126 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001127 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001128 switch (
1129 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001130 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +00001131 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001132 parseIncludeDirective();
1133 break;
Manuel Klimek407a31a2013-01-15 15:50:27 +00001134 case tok::pp_error:
1135 case tok::pp_warning:
1136 parseWarningOrError();
1137 break;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001138 default:
1139 break;
1140 }
1141 }
1142
Daniel Jasper71607512013-01-07 10:48:50 +00001143 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001144 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001145 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +00001146 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001147 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001148 while (CurrentToken != NULL) {
1149 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +00001150 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001151 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +00001152 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001153 }
Daniel Jasper71607512013-01-07 10:48:50 +00001154 if (KeywordVirtualFound)
1155 return LT_VirtualFunctionDecl;
1156 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001157 }
1158
1159 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001160 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1161 CurrentToken = &CurrentToken->Children[0];
1162 else
1163 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001164 }
1165
1166 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001167 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +00001168 bool KeywordVirtualFound;
Nico Weberbcfdd262013-01-12 06:18:40 +00001169 bool ColonIsObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001170 };
1171
Daniel Jasper26f7e782013-01-08 14:56:18 +00001172 void calculateExtraInformation(AnnotatedToken &Current) {
1173 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1174
Manuel Klimek526ed112013-01-09 15:25:02 +00001175 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001176 Current.MustBreakBefore = true;
1177 } else {
Daniel Jasper487f64b2013-01-13 16:10:20 +00001178 if (Current.Type == TT_LineComment) {
1179 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001180 } else if ((Current.Parent->is(tok::comment) &&
1181 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper487f64b2013-01-13 16:10:20 +00001182 (Current.is(tok::string_literal) &&
1183 Current.Parent->is(tok::string_literal))) {
Manuel Klimek526ed112013-01-09 15:25:02 +00001184 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +00001185 } else {
1186 Current.MustBreakBefore = false;
1187 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001188 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001189 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001190 if (Current.MustBreakBefore)
1191 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1192 else
1193 Current.TotalLength = Current.Parent->TotalLength +
1194 Current.FormatTok.TokenLength +
1195 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001196 if (!Current.Children.empty())
1197 calculateExtraInformation(Current.Children[0]);
1198 }
1199
Daniel Jasper995e8202013-01-14 13:08:07 +00001200 void annotate() {
Daniel Jasper995e8202013-01-14 13:08:07 +00001201 AnnotatingParser Parser(Line.First);
1202 Line.Type = Parser.parseLine();
1203 if (Line.Type == LT_Invalid)
1204 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001205
Daniel Jasper995e8202013-01-14 13:08:07 +00001206 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +00001207
Daniel Jasper995e8202013-01-14 13:08:07 +00001208 if (Line.First.Type == TT_ObjCMethodSpecifier)
1209 Line.Type = LT_ObjCMethodDecl;
1210 else if (Line.First.Type == TT_ObjCDecl)
1211 Line.Type = LT_ObjCDecl;
1212 else if (Line.First.Type == TT_ObjCProperty)
1213 Line.Type = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +00001214
Daniel Jasper995e8202013-01-14 13:08:07 +00001215 Line.First.SpaceRequiredBefore = true;
1216 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1217 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001218
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001219 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasper995e8202013-01-14 13:08:07 +00001220 if (!Line.First.Children.empty())
1221 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001222 }
1223
1224private:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001225 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1226 if (getPrecedence(Current) == prec::Assignment ||
1227 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1228 IsRHS = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001229
Daniel Jasper26f7e782013-01-08 14:56:18 +00001230 if (Current.Type == TT_Unknown) {
1231 if (Current.is(tok::star) || Current.is(tok::amp)) {
1232 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasper886568d2013-01-09 08:36:49 +00001233 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1234 Current.is(tok::caret)) {
1235 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001236 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1237 Current.Type = determineIncrementUsage(Current);
1238 } else if (Current.is(tok::exclaim)) {
1239 Current.Type = TT_UnaryOperator;
1240 } else if (isBinaryOperator(Current)) {
1241 Current.Type = TT_BinaryOperator;
1242 } else if (Current.is(tok::comment)) {
1243 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1244 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +00001245 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001246 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001247 else
Daniel Jasper26f7e782013-01-08 14:56:18 +00001248 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001249 } else if (Current.is(tok::r_paren) &&
1250 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasper4981bd02013-01-13 08:01:36 +00001251 Current.Parent->Type == TT_TemplateCloser) &&
1252 (Current.Children.empty() ||
1253 (Current.Children[0].isNot(tok::equal) &&
1254 Current.Children[0].isNot(tok::semi) &&
1255 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001256 // FIXME: We need to get smarter and understand more cases of casts.
1257 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +00001258 } else if (Current.is(tok::at) && Current.Children.size()) {
1259 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1260 case tok::objc_interface:
1261 case tok::objc_implementation:
1262 case tok::objc_protocol:
1263 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +00001264 break;
1265 case tok::objc_property:
1266 Current.Type = TT_ObjCProperty;
1267 break;
Nico Webered91bba2013-01-10 19:19:14 +00001268 default:
1269 break;
1270 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001271 }
1272 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001273
1274 if (!Current.Children.empty())
1275 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001276 }
1277
Daniel Jasper26f7e782013-01-08 14:56:18 +00001278 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001279 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +00001280 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001281 }
1282
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001283 /// \brief Returns the previous token ignoring comments.
1284 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1285 const AnnotatedToken *PrevToken = Tok.Parent;
1286 while (PrevToken != NULL && PrevToken->is(tok::comment))
1287 PrevToken = PrevToken->Parent;
1288 return PrevToken;
1289 }
1290
1291 /// \brief Returns the next token ignoring comments.
1292 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1293 if (Tok.Children.empty())
1294 return NULL;
1295 const AnnotatedToken *NextToken = &Tok.Children[0];
1296 while (NextToken->is(tok::comment)) {
1297 if (NextToken->Children.empty())
1298 return NULL;
1299 NextToken = &NextToken->Children[0];
1300 }
1301 return NextToken;
1302 }
1303
1304 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001305 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001306 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1307 if (PrevToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001308 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001309
1310 const AnnotatedToken *NextToken = getNextToken(Tok);
1311 if (NextToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001312 return TT_Unknown;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001313
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001314 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1315 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1316 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1317 PrevToken->Type == TT_BinaryOperator ||
Daniel Jasper48bd7b72013-01-16 16:04:06 +00001318 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +00001319 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001320
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001321 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1322 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1323 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1324 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1325 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1326 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1327 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +00001328 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001329
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001330 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1331 NextToken->is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +00001332 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +00001333
Daniel Jasper112fb272012-12-05 07:51:39 +00001334 // It is very unlikely that we are going to find a pointer or reference type
1335 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +00001336 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +00001337 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +00001338
Daniel Jasper71607512013-01-07 10:48:50 +00001339 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001340 }
1341
Daniel Jasper886568d2013-01-09 08:36:49 +00001342 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001343 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1344 if (PrevToken == NULL)
1345 return TT_UnaryOperator;
1346
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001347 // Use heuristics to recognize unary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001348 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1349 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1350 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1351 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1352 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasper71607512013-01-07 10:48:50 +00001353 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001354
1355 // There can't be to consecutive binary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001356 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +00001357 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001358
1359 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +00001360 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001361 }
1362
1363 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001364 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001365 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1366 if (PrevToken == NULL)
Daniel Jasper4abbb532013-01-14 12:18:19 +00001367 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001368 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1369 PrevToken->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +00001370 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001371
Daniel Jasper71607512013-01-07 10:48:50 +00001372 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001373 }
1374
Daniel Jasper26f7e782013-01-08 14:56:18 +00001375 bool spaceRequiredBetween(const AnnotatedToken &Left,
1376 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +00001377 if (Right.is(tok::hashhash))
1378 return Left.is(tok::hash);
1379 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1380 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +00001381 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1382 return false;
Nico Weber5f500df2013-01-10 20:12:55 +00001383 if (Right.is(tok::less) &&
1384 (Left.is(tok::kw_template) ||
Daniel Jasper995e8202013-01-14 13:08:07 +00001385 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001386 return true;
1387 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1388 return false;
1389 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1390 return false;
Nico Webercb4d6902013-01-08 19:40:21 +00001391 if (Left.is(tok::at) &&
1392 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1393 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001394 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1395 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001396 return false;
Daniel Jasper6b825c22013-01-16 07:19:28 +00001397 if (Left.is(tok::coloncolon))
1398 return false;
1399 if (Right.is(tok::coloncolon))
1400 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001401 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1402 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001403 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001404 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001405 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1406 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001407 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001408 return Right.FormatTok.Tok.isLiteral() ||
1409 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001410 if (Right.is(tok::star) && Left.is(tok::l_paren))
1411 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001412 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1413 return false;
1414 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +00001415 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001416 if (Left.is(tok::period) || Right.is(tok::period))
1417 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001418 if (Left.is(tok::colon))
1419 return Left.Type != TT_ObjCMethodExpr;
1420 if (Right.is(tok::colon))
1421 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001422 if (Left.is(tok::l_paren))
1423 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001424 if (Right.is(tok::l_paren)) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001425 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Webered91bba2013-01-10 19:19:14 +00001426 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001427 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasper088dab52013-01-11 16:09:04 +00001428 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1429 Left.is(tok::kw_delete);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001430 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001431 if (Left.is(tok::at) &&
1432 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001433 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001434 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1435 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001436 return true;
1437 }
1438
Daniel Jasper26f7e782013-01-08 14:56:18 +00001439 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001440 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001441 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1442 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001443 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001444 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001445 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001446 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weberaab60052013-01-17 06:14:50 +00001447 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001448 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001449 // Don't space between ')' and <id>
1450 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001451 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001452 // Don't space between ':' and '('
1453 return false;
1454 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001455 if (Line.Type == LT_ObjCProperty &&
Nico Weber70848232013-01-10 21:30:42 +00001456 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1457 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001458
Daniel Jasper4e9008a2013-01-13 08:19:51 +00001459 if (Tok.Parent->is(tok::comma))
1460 return true;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001461 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001462 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001463 if (Tok.Type == TT_OverloadedOperator)
1464 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001465 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001466 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001467 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001468 if (Tok.is(tok::colon))
Daniel Jasper995e8202013-01-14 13:08:07 +00001469 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Weberbcfdd262013-01-12 06:18:40 +00001470 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001471 if (Tok.Parent->Type == TT_UnaryOperator ||
1472 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001473 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001474 if (Tok.Type == TT_UnaryOperator)
1475 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webercd458332013-01-12 23:48:49 +00001476 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1477 (Tok.Parent->isNot(tok::colon) ||
1478 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001479 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1480 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001481 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1482 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001483 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001484 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001485 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001486 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001487 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001488 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001489 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001490 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001491 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001492 }
1493
Daniel Jasper26f7e782013-01-08 14:56:18 +00001494 bool canBreakBefore(const AnnotatedToken &Right) {
1495 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasper995e8202013-01-14 13:08:07 +00001496 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001497 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1498 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001499 return true;
Nico Weber774b9732013-01-12 07:00:16 +00001500 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1501 Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001502 // Don't break this identifier as ':' or identifier
1503 // before it will break.
1504 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001505 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1506 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001507 // Don't break at ':' if identifier before it can beak.
1508 return false;
1509 }
Nico Weberbcfdd262013-01-12 06:18:40 +00001510 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1511 return false;
1512 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1513 return true;
Nico Webere8ccc812013-01-12 22:48:47 +00001514 if (isObjCSelectorName(Right))
1515 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001516 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001517 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001518 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001519 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001520 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001521 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001522 return false;
1523
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001524 if (Right.Type == TT_LineComment)
Daniel Jasper487f64b2013-01-13 16:10:20 +00001525 // We rely on MustBreakBefore being set correctly here as we should not
1526 // change the "binding" behavior of a comment.
1527 return false;
1528
Daniel Jasper60ca75d2013-01-17 13:31:52 +00001529 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1530 // unless it is follow by ';', '{' or '='.
1531 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1532 Left.Parent->is(tok::r_paren))
1533 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1534 Right.isNot(tok::equal);
1535
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001536 // We only break before r_brace if there was a corresponding break before
1537 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1538 if (Right.is(tok::r_brace))
1539 return false;
1540
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001541 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001542 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001543 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1544 Left.is(tok::comma) || Right.is(tok::lessless) ||
1545 Right.is(tok::arrow) || Right.is(tok::period) ||
1546 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001547 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1548 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1549 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001550 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001551 }
1552
Daniel Jasperbac016b2012-12-03 18:12:45 +00001553 FormatStyle Style;
1554 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001555 Lexer &Lex;
Daniel Jasper995e8202013-01-14 13:08:07 +00001556 AnnotatedLine &Line;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001557};
1558
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001559class LexerBasedFormatTokenSource : public FormatTokenSource {
1560public:
1561 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001562 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001563 IdentTable(Lex.getLangOpts()) {
1564 Lex.SetKeepWhitespaceMode(true);
1565 }
1566
1567 virtual FormatToken getNextToken() {
1568 if (GreaterStashed) {
1569 FormatTok.NewlinesBefore = 0;
1570 FormatTok.WhiteSpaceStart =
1571 FormatTok.Tok.getLocation().getLocWithOffset(1);
1572 FormatTok.WhiteSpaceLength = 0;
1573 GreaterStashed = false;
1574 return FormatTok;
1575 }
1576
1577 FormatTok = FormatToken();
1578 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001579 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001580 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001581 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1582 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001583
1584 // Consume and record whitespace until we find a significant token.
1585 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001586 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001587 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1588 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001589 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1590
1591 if (FormatTok.Tok.is(tok::eof))
1592 return FormatTok;
1593 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001594 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001595 }
Manuel Klimek95419382013-01-07 07:56:50 +00001596
1597 // Now FormatTok is the next non-whitespace token.
1598 FormatTok.TokenLength = Text.size();
1599
Manuel Klimekd4397b92013-01-04 23:34:14 +00001600 // In case the token starts with escaped newlines, we want to
1601 // take them into account as whitespace - this pattern is quite frequent
1602 // in macro definitions.
1603 // FIXME: What do we want to do with other escaped spaces, and escaped
1604 // spaces or newlines in the middle of tokens?
1605 // FIXME: Add a more explicit test.
1606 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001607 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001608 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001609 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001610 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001611 }
1612
1613 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001614 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001615 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001616 FormatTok.Tok.setKind(Info.getTokenID());
1617 }
1618
1619 if (FormatTok.Tok.is(tok::greatergreater)) {
1620 FormatTok.Tok.setKind(tok::greater);
1621 GreaterStashed = true;
1622 }
1623
1624 return FormatTok;
1625 }
1626
1627private:
1628 FormatToken FormatTok;
1629 bool GreaterStashed;
1630 Lexer &Lex;
1631 SourceManager &SourceMgr;
1632 IdentifierTable IdentTable;
1633
1634 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001635 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001636 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1637 Tok.getLength());
1638 }
1639};
1640
Daniel Jasperbac016b2012-12-03 18:12:45 +00001641class Formatter : public UnwrappedLineConsumer {
1642public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001643 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1644 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001645 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001646 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001647 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001648
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001649 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001650
Daniel Jasperbac016b2012-12-03 18:12:45 +00001651 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001652 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001653 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001654 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001655 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +00001656 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1657 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1658 Annotator.annotate();
1659 }
1660 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1661 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001662 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001663 const AnnotatedLine &TheLine = *I;
1664 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1665 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1666 TheLine.InPPDirective,
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001667 PreviousEndOfLineColumn);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001668 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001669 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001670 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001671 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001672 PreviousEndOfLineColumn = Formatter.format();
1673 } else {
1674 // If we did not reformat this unwrapped line, the column at the end of
1675 // the last token is unchanged - thus, we can calculate the end of the
1676 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001677 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +00001678 SourceMgr.getSpellingColumnNumber(
1679 TheLine.Last->FormatTok.Tok.getLocation()) +
1680 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1681 SourceMgr, Lex.getLangOpts()) -
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001682 1;
1683 }
1684 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001685 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001686 }
1687
1688private:
Manuel Klimek517e8942013-01-11 17:54:10 +00001689 /// \brief Tries to merge lines into one.
1690 ///
1691 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1692 /// if possible; note that \c I will be incremented when lines are merged.
1693 ///
1694 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001695 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001696 std::vector<AnnotatedLine>::iterator &I,
1697 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001698 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1699
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001700 // We can never merge stuff if there are trailing line comments.
1701 if (I->Last->Type == TT_LineComment)
1702 return;
1703
Manuel Klimek517e8942013-01-11 17:54:10 +00001704 // Check whether the UnwrappedLine can be put onto a single line. If
1705 // so, this is bound to be the optimal solution (by definition) and we
1706 // don't need to analyze the entire solution space.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001707 if (I->Last->TotalLength >= Limit)
1708 return;
1709 Limit -= I->Last->TotalLength + 1; // One space.
Daniel Jasper55b08e72013-01-16 07:02:34 +00001710
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001711 if (I + 1 == E)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001712 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001713
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001714 if (I->Last->is(tok::l_brace)) {
1715 tryMergeSimpleBlock(I, E, Limit);
1716 } else if (I->First.is(tok::kw_if)) {
1717 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001718 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1719 I->First.FormatTok.IsFirst)) {
1720 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001721 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001722 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001723 }
1724
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001725 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1726 std::vector<AnnotatedLine>::iterator E,
1727 unsigned Limit) {
1728 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001729 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1730 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001731 if (I + 2 != E && (I + 2)->InPPDirective &&
1732 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1733 return;
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001734 if ((I + 1)->Last->TotalLength > Limit)
1735 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001736 join(Line, *(++I));
1737 }
1738
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001739 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1740 std::vector<AnnotatedLine>::iterator E,
1741 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001742 if (!Style.AllowShortIfStatementsOnASingleLine)
1743 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001744 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001745 if (Line.Last->isNot(tok::r_paren))
1746 return;
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001747 if ((I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001748 return;
1749 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1750 return;
1751 // Only inline simple if's (no nested if or else).
1752 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1753 return;
1754 join(Line, *(++I));
1755 }
1756
1757 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1758 std::vector<AnnotatedLine>::iterator E,
1759 unsigned Limit){
Daniel Jasper995e8202013-01-14 13:08:07 +00001760 // Check that we still have three lines and they fit into the limit.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001761 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1762 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001763
1764 // First, check that the current line allows merging. This is the case if
1765 // we're not in a control flow statement and the last token is an opening
1766 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001767 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001768 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001769 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1770 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1771 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1772 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001773 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001774 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1775 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001776 if (!AllowedTokens)
1777 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001778
1779 // Second, check that the next line does not contain any braces - if it
1780 // does, readability declines when putting it into a single line.
Daniel Jasper995e8202013-01-14 13:08:07 +00001781 const AnnotatedToken *Tok = &(I + 1)->First;
1782 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001783 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001784 do {
1785 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001786 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001787 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1788 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001789
1790 // Last, check that the third line contains a single closing brace.
Daniel Jasper995e8202013-01-14 13:08:07 +00001791 Tok = &(I + 2)->First;
1792 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1793 Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001794 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001795
Daniel Jasper995e8202013-01-14 13:08:07 +00001796 // If the merged line fits, we use that instead and skip the next two lines.
1797 Line.Last->Children.push_back((I + 1)->First);
1798 while (!Line.Last->Children.empty()) {
1799 Line.Last->Children[0].Parent = Line.Last;
1800 Line.Last = &Line.Last->Children[0];
Manuel Klimek517e8942013-01-11 17:54:10 +00001801 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001802
1803 join(Line, *(I + 1));
1804 join(Line, *(I + 2));
1805 I += 2;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001806 }
1807
1808 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1809 unsigned Limit) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001810 return (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001811 }
1812
Daniel Jasper995e8202013-01-14 13:08:07 +00001813 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1814 A.Last->Children.push_back(B.First);
1815 while (!A.Last->Children.empty()) {
1816 A.Last->Children[0].Parent = A.Last;
1817 A.Last = &A.Last->Children[0];
1818 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001819 }
1820
Daniel Jasper995e8202013-01-14 13:08:07 +00001821 bool touchesRanges(const AnnotatedLine &TheLine) {
1822 const FormatToken *First = &TheLine.First.FormatTok;
1823 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001824 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001825 First->Tok.getLocation(),
1826 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001827 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001828 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1829 Ranges[i].getBegin()) &&
1830 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1831 LineRange.getBegin()))
1832 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001833 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001834 return false;
1835 }
1836
1837 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001838 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001839 }
1840
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001841 /// \brief Add a new line and the required indent before the first Token
1842 /// of the \c UnwrappedLine if there was no structural parsing error.
1843 /// Returns the indent level of the \c UnwrappedLine.
1844 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1845 bool InPPDirective,
1846 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001847 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001848 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1849 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1850
1851 unsigned Newlines = std::min(Tok.NewlinesBefore,
1852 Style.MaxEmptyLinesToKeep + 1);
1853 if (Newlines == 0 && !Tok.IsFirst)
1854 Newlines = 1;
1855 unsigned Indent = Level * 2;
1856
1857 bool IsAccessModifier = false;
1858 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1859 RootToken.is(tok::kw_private))
1860 IsAccessModifier = true;
1861 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1862 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1863 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1864 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1865 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1866 IsAccessModifier = true;
1867
1868 if (IsAccessModifier &&
1869 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1870 Indent += Style.AccessModifierOffset;
1871 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001872 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001873 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001874 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1875 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001876 }
1877 return Indent;
1878 }
1879
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001880 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001881 FormatStyle Style;
1882 Lexer &Lex;
1883 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001884 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001885 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001886 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001887 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001888};
1889
1890tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1891 SourceManager &SourceMgr,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001892 std::vector<CharSourceRange> Ranges,
1893 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001894 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001895 OwningPtr<DiagnosticConsumer> DiagPrinter;
1896 if (DiagClient == 0) {
1897 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1898 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1899 DiagClient = DiagPrinter.get();
1900 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001901 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001902 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001903 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001904 Diagnostics.setSourceManager(&SourceMgr);
1905 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001906 return formatter.format();
1907}
1908
Daniel Jasper46ef8522013-01-10 13:08:12 +00001909LangOptions getFormattingLangOpts() {
1910 LangOptions LangOpts;
1911 LangOpts.CPlusPlus = 1;
1912 LangOpts.CPlusPlus11 = 1;
1913 LangOpts.Bool = 1;
1914 LangOpts.ObjC1 = 1;
1915 LangOpts.ObjC2 = 1;
1916 return LangOpts;
1917}
1918
Daniel Jaspercd162382013-01-07 13:26:07 +00001919} // namespace format
1920} // namespace clang