blob: dbed75c3f19fd3032396ae9f48c3904631af69aa [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
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
19#include "clang/Format/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperf7935112012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasperda16db32013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000037 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000042 TT_ObjCMethodExpr,
Nico Weber9efe2912013-01-10 23:11:41 +000043 TT_ObjCSelectorStart,
Nico Webera2a84952013-01-10 21:30:42 +000044 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000045 TT_OverloadedOperator,
46 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000047 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000048 TT_TemplateCloser,
49 TT_TemplateOpener,
50 TT_TrailingUnaryOperator,
51 TT_UnaryOperator,
52 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000053};
54
55enum LineType {
56 LT_Invalid,
57 LT_Other,
58 LT_PreprocessorDirective,
59 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000060 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000061 LT_ObjCMethodDecl,
62 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000063};
64
Daniel Jasper7c85fde2013-01-08 14:56:18 +000065class AnnotatedToken {
66public:
67 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000068 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
69 CanBreakBefore(false), MustBreakBefore(false),
70 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071
Daniel Jasper25837aa2013-01-14 14:14:23 +000072 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
73 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
74
Daniel Jasper7c85fde2013-01-08 14:56:18 +000075 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
76 return FormatTok.Tok.isObjCAtKeyword(Kind);
77 }
78
79 FormatToken FormatTok;
80
Daniel Jasperf7935112012-12-03 18:12:45 +000081 TokenType Type;
82
Daniel Jasperf7935112012-12-03 18:12:45 +000083 bool SpaceRequiredBefore;
84 bool CanBreakBefore;
85 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000086
87 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000088
89 std::vector<AnnotatedToken> Children;
90 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000091};
92
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +000093class AnnotatedLine {
94public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +000095 AnnotatedLine(const UnwrappedLine &Line)
96 : First(Line.Tokens.front()), Level(Line.Level),
97 InPPDirective(Line.InPPDirective) {
98 assert(!Line.Tokens.empty());
99 AnnotatedToken *Current = &First;
100 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
101 E = Line.Tokens.end();
102 I != E; ++I) {
103 Current->Children.push_back(*I);
104 Current->Children[0].Parent = Current;
105 Current = &Current->Children[0];
106 }
107 Last = Current;
108 }
109 AnnotatedLine(const AnnotatedLine &Other)
110 : First(Other.First), Type(Other.Type), Level(Other.Level),
111 InPPDirective(Other.InPPDirective) {
112 Last = &First;
113 while (!Last->Children.empty()) {
114 Last->Children[0].Parent = Last;
115 Last = &Last->Children[0];
116 }
117 }
118
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000119 AnnotatedToken First;
120 AnnotatedToken *Last;
121
122 LineType Type;
123 unsigned Level;
124 bool InPPDirective;
125};
126
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000127static prec::Level getPrecedence(const AnnotatedToken &Tok) {
128 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000129}
130
Daniel Jasperf7935112012-12-03 18:12:45 +0000131FormatStyle getLLVMStyle() {
132 FormatStyle LLVMStyle;
133 LLVMStyle.ColumnLimit = 80;
134 LLVMStyle.MaxEmptyLinesToKeep = 1;
135 LLVMStyle.PointerAndReferenceBindToType = false;
136 LLVMStyle.AccessModifierOffset = -2;
137 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000138 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000139 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000140 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000141 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000142 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000143 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000144 return LLVMStyle;
145}
146
147FormatStyle getGoogleStyle() {
148 FormatStyle GoogleStyle;
149 GoogleStyle.ColumnLimit = 80;
150 GoogleStyle.MaxEmptyLinesToKeep = 1;
151 GoogleStyle.PointerAndReferenceBindToType = true;
152 GoogleStyle.AccessModifierOffset = -1;
153 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000154 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000155 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000156 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000157 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Webera6087752013-01-10 20:12:55 +0000158 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000159 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000160 return GoogleStyle;
161}
162
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000163FormatStyle getChromiumStyle() {
164 FormatStyle ChromiumStyle = getGoogleStyle();
165 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
166 return ChromiumStyle;
167}
168
Daniel Jasperf7935112012-12-03 18:12:45 +0000169struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000170 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000171 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000172 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000173};
174
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000175/// \brief Replaces the whitespace in front of \p Tok. Only call once for
176/// each \c FormatToken.
177static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
178 unsigned Spaces, const FormatStyle &Style,
179 SourceManager &SourceMgr,
180 tooling::Replacements &Replaces) {
181 Replaces.insert(tooling::Replacement(
182 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
183 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
184}
185
186/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
187/// backslashes to escape newlines inside a preprocessor directive.
188///
189/// This function and \c replaceWhitespace have the same behavior if
190/// \c Newlines == 0.
191static void replacePPWhitespace(
192 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
193 unsigned WhitespaceStartColumn, const FormatStyle &Style,
194 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
195 std::string NewLineText;
196 if (NewLines > 0) {
197 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
198 WhitespaceStartColumn);
199 for (unsigned i = 0; i < NewLines; ++i) {
200 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
201 NewLineText += "\\\n";
202 Offset = 0;
203 }
204 }
205 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
206 Tok.FormatTok.WhiteSpaceLength,
207 NewLineText + std::string(Spaces, ' ')));
208}
209
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000210/// \brief Calculates whether the (remaining) \c AnnotatedLine starting with
211/// \p RootToken fits into \p Limit columns on a single line.
212///
213/// If true, sets \p Length to the required length.
Daniel Jasper25837aa2013-01-14 14:14:23 +0000214static bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit,
215 unsigned *Length = 0) {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000216 unsigned Columns = RootToken.FormatTok.TokenLength;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000217 if (Columns > Limit) return false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000218 const AnnotatedToken *Tok = &RootToken;
219 while (!Tok->Children.empty()) {
220 Tok = &Tok->Children[0];
221 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) + Tok->FormatTok.TokenLength;
222 // A special case for the colon of a constructor initializer as this only
223 // needs to be put on a new line if the line needs to be split.
224 if (Columns > Limit ||
225 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000226 // FIXME: Remove this hack.
227 return false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000228 }
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000229 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000230 if (Length != 0)
231 *Length = Columns;
232 return true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000233}
234
Nico Weberc9d73612013-01-12 22:48:47 +0000235/// \brief Returns if a token is an Objective-C selector name.
236///
Nico Weber92c05392013-01-12 22:51:13 +0000237/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000238static bool isObjCSelectorName(const AnnotatedToken &Tok) {
239 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
240 Tok.Children[0].is(tok::colon) &&
241 Tok.Children[0].Type == TT_ObjCMethodExpr;
242}
243
Daniel Jasperf7935112012-12-03 18:12:45 +0000244class UnwrappedLineFormatter {
245public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000246 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000247 const AnnotatedLine &Line, unsigned FirstIndent,
Rafael Espindola8f1187a2013-01-12 14:22:42 +0000248 bool FitsOnALine, const AnnotatedToken &RootToken,
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000249 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000250 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000251 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Rafael Espindola8f1187a2013-01-12 14:22:42 +0000252 RootToken(RootToken), Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000253 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000254 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000255 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000256 }
257
Manuel Klimek1abf7892013-01-04 23:34:14 +0000258 /// \brief Formats an \c UnwrappedLine.
259 ///
260 /// \returns The column after the last token in the last line of the
261 /// \c UnwrappedLine.
262 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000263 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000264 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000265 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000266 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000267 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000268 State.ForLoopVariablePos = 0;
269 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000270 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000271
272 // The first token has already been indented and thus consumed.
273 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000274
275 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000276 while (State.NextToken != NULL) {
Manuel Klimeka31e58b2013-01-15 16:41:02 +0000277 if (State.NextToken->Type == TT_ImplicitStringLiteral)
278 // We will not touch the rest of the white space in this
279 // \c UnwrappedLine. The returned value can also not matter, as we
280 // cannot continue an top-level implicit string literal on the next
281 // line.
282 return 0;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000283 if (FitsOnALine) {
284 addTokenToState(false, false, State);
285 } else {
286 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
287 unsigned Break = calcPenalty(State, true, NoBreak);
288 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000289 if (State.NextToken != NULL &&
290 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
291 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
292 !fitsIntoLimit(*State.NextToken,
293 getColumnLimit() - State.Column - 1))
294 State.Stack.back().BreakAfterComma = true;
295 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000296 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000297 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000298 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000299 }
300
301private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000302 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000303 ParenState(unsigned Indent, unsigned LastSpace)
304 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
305 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000306
Daniel Jasperf7935112012-12-03 18:12:45 +0000307 /// \brief The position to which a specific parenthesis level needs to be
308 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000309 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000310
Daniel Jaspere9de2602012-12-06 09:56:08 +0000311 /// \brief The position of the last space on each level.
312 ///
313 /// Used e.g. to break like:
314 /// functionCall(Parameter, otherCall(
315 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000316 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000317
Daniel Jaspere9de2602012-12-06 09:56:08 +0000318 /// \brief The position the first "<<" operator encountered on each level.
319 ///
320 /// Used to align "<<" operators. 0 if no such operator has been encountered
321 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000322 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000323
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000324 /// \brief Whether a newline needs to be inserted before the block's closing
325 /// brace.
326 ///
327 /// We only want to insert a newline before the closing brace if there also
328 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000329 bool BreakBeforeClosingBrace;
330
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000331 bool BreakAfterComma;
332
Daniel Jasper337816e2013-01-11 10:22:12 +0000333 bool operator<(const ParenState &Other) const {
334 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000335 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000336 if (LastSpace != Other.LastSpace)
337 return LastSpace < Other.LastSpace;
338 if (FirstLessLess != Other.FirstLessLess)
339 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000340 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
341 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000342 if (BreakAfterComma != Other.BreakAfterComma)
343 return BreakAfterComma;
344 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000345 }
346 };
347
348 /// \brief The current state when indenting a unwrapped line.
349 ///
350 /// As the indenting tries different combinations this is copied by value.
351 struct LineState {
352 /// \brief The number of used columns in the current line.
353 unsigned Column;
354
355 /// \brief The token that needs to be next formatted.
356 const AnnotatedToken *NextToken;
357
358 /// \brief The parenthesis level of the first token on the current line.
359 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000360
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000361 /// \brief The column of the first variable in a for-loop declaration.
362 ///
363 /// Used to align the second variable if necessary.
364 unsigned ForLoopVariablePos;
365
366 /// \brief \c true if this line contains a continued for-loop section.
367 bool LineContainsContinuedForLoopSection;
368
Daniel Jasper337816e2013-01-11 10:22:12 +0000369 /// \brief A stack keeping track of properties applying to parenthesis
370 /// levels.
371 std::vector<ParenState> Stack;
372
373 /// \brief Comparison operator to be able to used \c LineState in \c map.
374 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000375 if (Other.NextToken != NextToken)
376 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000377 if (Other.Column != Column)
378 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000379 if (Other.StartOfLineLevel != StartOfLineLevel)
380 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000381 if (Other.ForLoopVariablePos != ForLoopVariablePos)
382 return Other.ForLoopVariablePos < ForLoopVariablePos;
383 if (Other.LineContainsContinuedForLoopSection !=
384 LineContainsContinuedForLoopSection)
385 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000386 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000387 }
388 };
389
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000390 /// \brief Appends the next token to \p State and updates information
391 /// necessary for indentation.
392 ///
393 /// Puts the token on the current line if \p Newline is \c true and adds a
394 /// line break and necessary indentation otherwise.
395 ///
396 /// If \p DryRun is \c false, also creates and stores the required
397 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000398 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000399 const AnnotatedToken &Current = *State.NextToken;
400 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000401 assert(State.Stack.size());
402 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000403
404 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000405 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000406 if (Current.is(tok::r_brace)) {
407 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000408 } else if (Current.is(tok::string_literal) &&
409 Previous.is(tok::string_literal)) {
410 State.Column = State.Column - Previous.FormatTok.TokenLength;
411 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000412 State.Stack[ParenLevel].FirstLessLess != 0) {
413 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000414 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000415 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
416 Current.is(tok::period) || Previous.is(tok::question) ||
417 Previous.Type == TT_ConditionalExpr)) {
418 // Indent and extra 4 spaces after if we know the current expression is
419 // continued. Don't do that on the top level, as we already indent 4
420 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000421 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000422 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000423 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000424 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000425 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000426 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000427 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000428 }
429
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000430 // A line starting with a closing brace is assumed to be correct for the
431 // same level as before the opening brace.
432 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000433
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000434 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000435 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000436
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000437 if (!DryRun) {
438 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000439 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
440 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000441 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000442 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000443 WhitespaceStartColumn, Style, SourceMgr,
444 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000445 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000446
Daniel Jasper337816e2013-01-11 10:22:12 +0000447 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000448 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000450 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000451 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
452 State.ForLoopVariablePos = State.Column -
453 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000454
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000455 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
456 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000457 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000458
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000460 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000461
Daniel Jasperbcab4302013-01-09 10:40:23 +0000462 // FIXME: Do we need to do this for assignments nested in other
463 // expressions?
464 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000465 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000466 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000468 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000469 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000470 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000471
Daniel Jasper206df732013-01-07 13:08:40 +0000472 // Top-level spaces that are not part of assignments are exempt as that
473 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000474 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000475 if (Spaces > 0 &&
476 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000477 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000478 }
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000479 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000480 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000481 }
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000482 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000483 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000484
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000485 /// \brief Mark the next token as consumed in \p State and modify its stacks
486 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000487 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000488 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000489 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000490
Daniel Jasper337816e2013-01-11 10:22:12 +0000491 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
492 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000493
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000494 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000495 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000496 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
497 Current.is(tok::l_brace) ||
498 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000499 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000500 if (Current.is(tok::l_brace)) {
501 // FIXME: This does not work with nested static initializers.
502 // Implement a better handling for static initializers and similar
503 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000504 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000505 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000506 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000507 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000508 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000509 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000510 }
511
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000512 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000513 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000514 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
515 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
516 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000517 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000518 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000519
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000520 if (State.NextToken->Children.empty())
521 State.NextToken = NULL;
522 else
523 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000524
525 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000526 }
527
Nico Weber49cbc2c2013-01-07 15:15:29 +0000528 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000529 unsigned splitPenalty(const AnnotatedToken &Tok) {
530 const AnnotatedToken &Left = Tok;
531 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000532
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000533 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
534 return 50;
535 if (Left.is(tok::equal) && Right.is(tok::l_brace))
536 return 150;
537
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000538 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000539 if (RootToken.is(tok::kw_for) &&
540 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000541 return 20;
542
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000543 if (Left.is(tok::semi) || Left.is(tok::comma) ||
544 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000545 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000546
547 // In Objective-C method expressions, prefer breaking before "param:" over
548 // breaking after it.
549 if (isObjCSelectorName(Right))
550 return 0;
551 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
552 return 20;
553
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000554 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000555 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000556
Daniel Jasper399d24b2013-01-09 07:06:56 +0000557 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
558 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000559 prec::Level Level = getPrecedence(Left);
560
561 // Breaking after an assignment leads to a bad result as the two sides of
562 // the assignment are visually very close together.
563 if (Level == prec::Assignment)
564 return 50;
565
Daniel Jasperde5c2072012-12-24 00:13:23 +0000566 if (Level != prec::Unknown)
567 return Level;
568
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000569 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000570 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000571
Daniel Jasperf7935112012-12-03 18:12:45 +0000572 return 3;
573 }
574
Daniel Jasper2df93312013-01-09 10:16:05 +0000575 unsigned getColumnLimit() {
576 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
577 }
578
Daniel Jasperf7935112012-12-03 18:12:45 +0000579 /// \brief Calculate the number of lines needed to format the remaining part
580 /// of the unwrapped line.
581 ///
582 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000583 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000584 /// added after the previous token.
585 ///
586 /// \param StopAt is used for optimization. If we can determine that we'll
587 /// definitely need at least \p StopAt additional lines, we already know of a
588 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000589 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000590 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000591 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 return 0;
593
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000594 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000595 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000596 if (NewLine && !State.NextToken->CanBreakBefore &&
597 !(State.NextToken->is(tok::r_brace) &&
598 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000599 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000600 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000601 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000602 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000603 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000604 State.LineContainsContinuedForLoopSection)
605 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000606 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
607 State.NextToken->Type != TT_LineComment &&
608 State.Stack.back().BreakAfterComma)
609 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000610
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000611 unsigned CurrentPenalty = 0;
612 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000613 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000614 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000615 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000616 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000617 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000618 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000619 }
620
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000621 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000622
Daniel Jasper2df93312013-01-09 10:16:05 +0000623 // Exceeding column limit is bad, assign penalty.
624 if (State.Column > getColumnLimit()) {
625 unsigned ExcessCharacters = State.Column - getColumnLimit();
626 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
627 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000628
Daniel Jasperf7935112012-12-03 18:12:45 +0000629 if (StopAt <= CurrentPenalty)
630 return UINT_MAX;
631 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000632 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000633 if (I != Memory.end()) {
634 // If this state has already been examined, we can safely return the
635 // previous result if we
636 // - have not hit the optimatization (and thus returned UINT_MAX) OR
637 // - are now computing for a smaller or equal StopAt.
638 unsigned SavedResult = I->second.first;
639 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000640 if (SavedResult != UINT_MAX)
641 return SavedResult + CurrentPenalty;
642 else if (StopAt <= SavedStopAt)
643 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000644 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000645
646 unsigned NoBreak = calcPenalty(State, false, StopAt);
647 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
648 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000649
650 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
651 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000652 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000653
654 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000655 }
656
Daniel Jasperf7935112012-12-03 18:12:45 +0000657 FormatStyle Style;
658 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000659 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000660 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000661 const bool FitsOnALine;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000662 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000663 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000664
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000665 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000666 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000667 StateMap Memory;
668
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 OptimizationParameters Parameters;
670};
671
672/// \brief Determines extra information about the tokens comprising an
673/// \c UnwrappedLine.
674class TokenAnnotator {
675public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000676 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
677 AnnotatedLine &Line)
678 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000679
680 /// \brief A parser that gathers additional information about tokens.
681 ///
682 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
683 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
684 /// into template parameter lists.
685 class AnnotatingParser {
686 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000687 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000688 : CurrentToken(&RootToken), KeywordVirtualFound(false),
689 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000690
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000691 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000692 while (CurrentToken != NULL) {
693 if (CurrentToken->is(tok::greater)) {
694 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000695 next();
696 return true;
697 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000698 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
699 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000701 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
702 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000703 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000704 if (!consumeToken())
705 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000706 }
707 return false;
708 }
709
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000710 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000711 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
712 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000713 while (CurrentToken != NULL) {
714 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000715 next();
716 return true;
717 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000718 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000719 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000720 if (!consumeToken())
721 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000722 }
723 return false;
724 }
725
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000726 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000727 if (!CurrentToken)
728 return false;
729
730 // A '[' could be an index subscript (after an indentifier or after
731 // ')' or ']'), or it could be the start of an Objective-C method
732 // expression.
733 AnnotatedToken *LSquare = CurrentToken->Parent;
734 bool StartsObjCMethodExpr =
735 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
736 LSquare->Parent->is(tok::l_square) ||
737 LSquare->Parent->is(tok::l_paren) ||
738 LSquare->Parent->is(tok::kw_return) ||
739 LSquare->Parent->is(tok::kw_throw) ||
740 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
741 true, true) > prec::Unknown;
742
743 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
744 if (StartsObjCMethodExpr) {
745 ColonIsObjCMethodExpr = true;
746 LSquare->Type = TT_ObjCMethodExpr;
747 }
748
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000749 while (CurrentToken != NULL) {
750 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000751 if (StartsObjCMethodExpr) {
752 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
753 CurrentToken->Type = TT_ObjCMethodExpr;
754 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000755 next();
756 return true;
757 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000758 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000760 if (!consumeToken())
761 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000762 }
763 return false;
764 }
765
Daniel Jasper83a54d22013-01-10 09:26:47 +0000766 bool parseBrace() {
767 while (CurrentToken != NULL) {
768 if (CurrentToken->is(tok::r_brace)) {
769 next();
770 return true;
771 }
772 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
773 return false;
774 if (!consumeToken())
775 return false;
776 }
777 // Lines can currently end with '{'.
778 return true;
779 }
780
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000781 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000782 while (CurrentToken != NULL) {
783 if (CurrentToken->is(tok::colon)) {
784 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 next();
786 return true;
787 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000788 if (!consumeToken())
789 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000790 }
791 return false;
792 }
793
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000794 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000795 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
796 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000797 next();
798 if (!parseAngle())
799 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000800 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000801 parseLine();
802 return true;
803 }
804 return false;
805 }
806
Daniel Jasperc0880a92013-01-04 18:52:56 +0000807 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000808 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000809 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000810 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000811 case tok::plus:
812 case tok::minus:
813 // At the start of the line, +/- specific ObjectiveC method
814 // declarations.
815 if (Tok->Parent == NULL)
816 Tok->Type = TT_ObjCMethodSpecifier;
817 break;
Nico Webera7252d82013-01-12 06:18:40 +0000818 case tok::colon:
819 // Colons from ?: are handled in parseConditional().
820 if (ColonIsObjCMethodExpr)
821 Tok->Type = TT_ObjCMethodExpr;
822 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000823 case tok::l_paren: {
Daniel Jasper25837aa2013-01-14 14:14:23 +0000824 bool ParensWereObjCReturnType = Tok->Parent && Tok->Parent->Type ==
825 TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000826 if (!parseParens())
827 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000828 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
829 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000830 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000831 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
832 CurrentToken->Type = TT_ObjCSelectorStart;
833 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000834 }
Nico Weber9efe2912013-01-10 23:11:41 +0000835 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000836 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000837 if (!parseSquare())
838 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000840 case tok::l_brace:
841 if (!parseBrace())
842 return false;
843 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000844 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000845 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000846 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000847 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000848 Tok->Type = TT_BinaryOperator;
849 CurrentToken = Tok;
850 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000851 }
852 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000853 case tok::r_paren:
854 case tok::r_square:
855 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000856 case tok::r_brace:
857 // Lines can start with '}'.
858 if (Tok->Parent != NULL)
859 return false;
860 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000861 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000862 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000863 break;
864 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000865 if (CurrentToken->is(tok::l_paren)) {
866 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000867 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000868 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
869 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000870 next();
871 }
872 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000873 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
874 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000875 next();
876 }
877 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000878 break;
879 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000880 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000881 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000882 case tok::kw_template:
883 parseTemplateDeclaration();
884 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000885 default:
886 break;
887 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000888 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000889 }
890
Daniel Jasper050948a52012-12-21 17:58:39 +0000891 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000892 next();
893 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
894 next();
895 while (CurrentToken != NULL) {
896 CurrentToken->Type = TT_ImplicitStringLiteral;
897 next();
898 }
899 } else {
900 while (CurrentToken != NULL) {
901 next();
902 }
903 }
904 }
905
906 void parseWarningOrError() {
907 next();
908 // We still want to format the whitespace left of the first token of the
909 // warning or error.
910 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000911 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000912 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +0000913 next();
914 }
915 }
916
917 void parsePreprocessorDirective() {
918 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000919 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000920 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000921 // Hashes in the middle of a line can lead to any strange token
922 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000923 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000924 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000925 switch (
926 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000927 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000928 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000929 parseIncludeDirective();
930 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000931 case tok::pp_error:
932 case tok::pp_warning:
933 parseWarningOrError();
934 break;
Daniel Jasper050948a52012-12-21 17:58:39 +0000935 default:
936 break;
937 }
938 }
939
Daniel Jasperda16db32013-01-07 10:48:50 +0000940 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000941 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000942 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000943 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000944 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000945 while (CurrentToken != NULL) {
946 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000947 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000948 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000949 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000950 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000951 if (KeywordVirtualFound)
952 return LT_VirtualFunctionDecl;
953 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000954 }
955
956 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000957 if (CurrentToken != NULL && !CurrentToken->Children.empty())
958 CurrentToken = &CurrentToken->Children[0];
959 else
960 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000961 }
962
963 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000964 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000965 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +0000966 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000967 };
968
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000969 void calculateExtraInformation(AnnotatedToken &Current) {
970 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
971
Manuel Klimek52b15152013-01-09 15:25:02 +0000972 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000973 Current.MustBreakBefore = true;
974 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +0000975 if (Current.Type == TT_LineComment) {
976 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
977 } else if (Current.Type == TT_CtorInitializerColon ||
978 Current.Parent->Type == TT_LineComment ||
979 (Current.is(tok::string_literal) &&
980 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +0000981 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000982 } else {
983 Current.MustBreakBefore = false;
984 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000985 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000986 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000987 if (!Current.Children.empty())
988 calculateExtraInformation(Current.Children[0]);
989 }
990
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000991 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000992 AnnotatingParser Parser(Line.First);
993 Line.Type = Parser.parseLine();
994 if (Line.Type == LT_Invalid)
995 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000996
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000997 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000998
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000999 if (Line.First.Type == TT_ObjCMethodSpecifier)
1000 Line.Type = LT_ObjCMethodDecl;
1001 else if (Line.First.Type == TT_ObjCDecl)
1002 Line.Type = LT_ObjCDecl;
1003 else if (Line.First.Type == TT_ObjCProperty)
1004 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001005
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001006 Line.First.SpaceRequiredBefore = true;
1007 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1008 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001009
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001010 if (!Line.First.Children.empty())
1011 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001012 }
1013
1014private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001015 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1016 if (getPrecedence(Current) == prec::Assignment ||
1017 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1018 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001019
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001020 if (Current.Type == TT_Unknown) {
1021 if (Current.is(tok::star) || Current.is(tok::amp)) {
1022 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001023 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1024 Current.is(tok::caret)) {
1025 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001026 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1027 Current.Type = determineIncrementUsage(Current);
1028 } else if (Current.is(tok::exclaim)) {
1029 Current.Type = TT_UnaryOperator;
1030 } else if (isBinaryOperator(Current)) {
1031 Current.Type = TT_BinaryOperator;
1032 } else if (Current.is(tok::comment)) {
1033 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1034 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001035 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001036 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001037 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001038 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001039 } else if (Current.is(tok::r_paren) &&
1040 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001041 Current.Parent->Type == TT_TemplateCloser) &&
1042 (Current.Children.empty() ||
1043 (Current.Children[0].isNot(tok::equal) &&
1044 Current.Children[0].isNot(tok::semi) &&
1045 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001046 // FIXME: We need to get smarter and understand more cases of casts.
1047 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001048 } else if (Current.is(tok::at) && Current.Children.size()) {
1049 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1050 case tok::objc_interface:
1051 case tok::objc_implementation:
1052 case tok::objc_protocol:
1053 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001054 break;
1055 case tok::objc_property:
1056 Current.Type = TT_ObjCProperty;
1057 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001058 default:
1059 break;
1060 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001061 }
1062 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001063
1064 if (!Current.Children.empty())
1065 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 }
1067
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001068 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001069 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001070 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001071 }
1072
Daniel Jasper71945272013-01-15 14:27:39 +00001073 /// \brief Returns the previous token ignoring comments.
1074 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1075 const AnnotatedToken *PrevToken = Tok.Parent;
1076 while (PrevToken != NULL && PrevToken->is(tok::comment))
1077 PrevToken = PrevToken->Parent;
1078 return PrevToken;
1079 }
1080
1081 /// \brief Returns the next token ignoring comments.
1082 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1083 if (Tok.Children.empty())
1084 return NULL;
1085 const AnnotatedToken *NextToken = &Tok.Children[0];
1086 while (NextToken->is(tok::comment)) {
1087 if (NextToken->Children.empty())
1088 return NULL;
1089 NextToken = &NextToken->Children[0];
1090 }
1091 return NextToken;
1092 }
1093
1094 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001095 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001096 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1097 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001098 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001099
1100 const AnnotatedToken *NextToken = getNextToken(Tok);
1101 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001102 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001103
Daniel Jasper71945272013-01-15 14:27:39 +00001104 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1105 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1106 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1107 PrevToken->Type == TT_BinaryOperator ||
1108 PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001109 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001110
Daniel Jasper71945272013-01-15 14:27:39 +00001111 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1112 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1113 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1114 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1115 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1116 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1117 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001118 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001119
Daniel Jasper71945272013-01-15 14:27:39 +00001120 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1121 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001122 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001123
Daniel Jasper426702d2012-12-05 07:51:39 +00001124 // It is very unlikely that we are going to find a pointer or reference type
1125 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001126 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001127 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001128
Daniel Jasperda16db32013-01-07 10:48:50 +00001129 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001130 }
1131
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001132 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001133 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1134 if (PrevToken == NULL)
1135 return TT_UnaryOperator;
1136
Daniel Jasper8dd40472012-12-21 09:41:31 +00001137 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001138 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1139 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1140 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1141 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1142 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001143 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001144
1145 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001146 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001147 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001148
1149 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001150 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001151 }
1152
1153 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001154 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001155 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1156 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001157 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001158 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1159 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001160 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001161
Daniel Jasperda16db32013-01-07 10:48:50 +00001162 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001163 }
1164
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001165 bool spaceRequiredBetween(const AnnotatedToken &Left,
1166 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001167 if (Right.is(tok::hashhash))
1168 return Left.is(tok::hash);
1169 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1170 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001171 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1172 return false;
Nico Webera6087752013-01-10 20:12:55 +00001173 if (Right.is(tok::less) &&
1174 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001175 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001176 return true;
1177 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1178 return false;
1179 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1180 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001181 if (Left.is(tok::at) &&
1182 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1183 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001184 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1185 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001186 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001187 if (Left.is(tok::coloncolon))
1188 return false;
1189 if (Right.is(tok::coloncolon))
1190 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001191 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1192 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001193 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001194 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001195 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1196 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001197 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001198 return Right.FormatTok.Tok.isLiteral() ||
1199 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001200 if (Right.is(tok::star) && Left.is(tok::l_paren))
1201 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001202 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1203 return false;
1204 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001205 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001206 if (Left.is(tok::period) || Right.is(tok::period))
1207 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001208 if (Left.is(tok::colon))
1209 return Left.Type != TT_ObjCMethodExpr;
1210 if (Right.is(tok::colon))
1211 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001212 if (Left.is(tok::l_paren))
1213 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001214 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001215 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001216 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001217 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001218 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1219 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001220 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001221 if (Left.is(tok::at) &&
1222 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001223 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001224 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1225 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001226 return true;
1227 }
1228
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001229 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001230 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001231 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1232 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001233 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001234 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001235 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001236 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001237 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1238 if (Tok.Type == TT_ObjCSelectorStart)
1239 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001240 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001241 // Don't space between ')' and <id>
1242 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001243 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001244 // Don't space between ':' and '('
1245 return false;
1246 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001247 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001248 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1249 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001250
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001251 if (Tok.Parent->is(tok::comma))
1252 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001253 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001254 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001255 if (Tok.Type == TT_OverloadedOperator)
1256 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001257 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001258 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001259 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001260 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001261 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001262 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001263 if (Tok.Parent->Type == TT_UnaryOperator ||
1264 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001265 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001266 if (Tok.Type == TT_UnaryOperator)
1267 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001268 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1269 (Tok.Parent->isNot(tok::colon) ||
1270 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001271 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1272 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001273 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1274 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001275 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001276 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001277 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001278 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001279 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001280 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001281 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001282 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001283 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001284 }
1285
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001286 bool canBreakBefore(const AnnotatedToken &Right) {
1287 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001288 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001289 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1290 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001291 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001292 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1293 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001294 // Don't break this identifier as ':' or identifier
1295 // before it will break.
1296 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001297 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1298 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001299 // Don't break at ':' if identifier before it can beak.
1300 return false;
1301 }
Nico Webera7252d82013-01-12 06:18:40 +00001302 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1303 return false;
1304 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1305 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001306 if (isObjCSelectorName(Right))
1307 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001308 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001309 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001310 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001311 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001312 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001313 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001314 return false;
1315
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001316 if (Right.is(tok::comment))
Daniel Jasper942ee722013-01-13 16:10:20 +00001317 // We rely on MustBreakBefore being set correctly here as we should not
1318 // change the "binding" behavior of a comment.
1319 return false;
1320
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001321 // We only break before r_brace if there was a corresponding break before
1322 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1323 if (Right.is(tok::r_brace))
1324 return false;
1325
Daniel Jasper71945272013-01-15 14:27:39 +00001326 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001327 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001328 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1329 Left.is(tok::comma) || Right.is(tok::lessless) ||
1330 Right.is(tok::arrow) || Right.is(tok::period) ||
1331 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001332 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1333 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1334 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001335 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001336 }
1337
Daniel Jasperf7935112012-12-03 18:12:45 +00001338 FormatStyle Style;
1339 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001340 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001341 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001342};
1343
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001344class LexerBasedFormatTokenSource : public FormatTokenSource {
1345public:
1346 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001347 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001348 IdentTable(Lex.getLangOpts()) {
1349 Lex.SetKeepWhitespaceMode(true);
1350 }
1351
1352 virtual FormatToken getNextToken() {
1353 if (GreaterStashed) {
1354 FormatTok.NewlinesBefore = 0;
1355 FormatTok.WhiteSpaceStart =
1356 FormatTok.Tok.getLocation().getLocWithOffset(1);
1357 FormatTok.WhiteSpaceLength = 0;
1358 GreaterStashed = false;
1359 return FormatTok;
1360 }
1361
1362 FormatTok = FormatToken();
1363 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001364 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001365 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001366 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1367 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001368
1369 // Consume and record whitespace until we find a significant token.
1370 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001371 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001372 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1373 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001374 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1375
1376 if (FormatTok.Tok.is(tok::eof))
1377 return FormatTok;
1378 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001379 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001380 }
Manuel Klimekef920692013-01-07 07:56:50 +00001381
1382 // Now FormatTok is the next non-whitespace token.
1383 FormatTok.TokenLength = Text.size();
1384
Manuel Klimek1abf7892013-01-04 23:34:14 +00001385 // In case the token starts with escaped newlines, we want to
1386 // take them into account as whitespace - this pattern is quite frequent
1387 // in macro definitions.
1388 // FIXME: What do we want to do with other escaped spaces, and escaped
1389 // spaces or newlines in the middle of tokens?
1390 // FIXME: Add a more explicit test.
1391 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001392 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001393 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001394 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001395 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001396 }
1397
1398 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001399 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001400 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001401 FormatTok.Tok.setKind(Info.getTokenID());
1402 }
1403
1404 if (FormatTok.Tok.is(tok::greatergreater)) {
1405 FormatTok.Tok.setKind(tok::greater);
1406 GreaterStashed = true;
1407 }
1408
1409 return FormatTok;
1410 }
1411
1412private:
1413 FormatToken FormatTok;
1414 bool GreaterStashed;
1415 Lexer &Lex;
1416 SourceManager &SourceMgr;
1417 IdentifierTable IdentTable;
1418
1419 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001420 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001421 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1422 Tok.getLength());
1423 }
1424};
1425
Daniel Jasperf7935112012-12-03 18:12:45 +00001426class Formatter : public UnwrappedLineConsumer {
1427public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001428 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1429 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001430 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001431 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001432 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001433
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001434 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001435
Daniel Jasperf7935112012-12-03 18:12:45 +00001436 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001437 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001438 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001439 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001440 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001441 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1442 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1443 Annotator.annotate();
1444 }
1445 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1446 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001447 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001448 const AnnotatedLine &TheLine = *I;
1449 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1450 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1451 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001452 PreviousEndOfLineColumn);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001453 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, I, E);
1454 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1455 FitsOnALine, TheLine.First, Replaces,
1456 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001457 PreviousEndOfLineColumn = Formatter.format();
1458 } else {
1459 // If we did not reformat this unwrapped line, the column at the end of
1460 // the last token is unchanged - thus, we can calculate the end of the
1461 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001462 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001463 SourceMgr.getSpellingColumnNumber(
1464 TheLine.Last->FormatTok.Tok.getLocation()) +
1465 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1466 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001467 1;
1468 }
1469 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001470 return Replaces;
1471 }
1472
1473private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001474 /// \brief Tries to merge lines into one.
1475 ///
1476 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1477 /// if possible; note that \c I will be incremented when lines are merged.
1478 ///
1479 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001480 bool tryFitMultipleLinesInOne(unsigned Indent,
1481 std::vector<AnnotatedLine>::iterator &I,
1482 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001483 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1484
1485 // Check whether the UnwrappedLine can be put onto a single line. If
1486 // so, this is bound to be the optimal solution (by definition) and we
1487 // don't need to analyze the entire solution space.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001488 unsigned Length = 0;
1489 if (!fitsIntoLimit(I->First, Limit, &Length))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001490 return false;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001491
1492 // We can never merge stuff if there are trailing line comments.
1493 if (I->Last->Type == TT_LineComment)
1494 return true;
1495
Daniel Jasper3e9218e2013-01-14 16:02:06 +00001496 if (Limit == Length)
1497 return true; // Couldn't fit a space.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001498 Limit -= Length + 1; // One space.
1499 if (I + 1 == E)
1500 return true;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001501
Daniel Jasper25837aa2013-01-14 14:14:23 +00001502 if (I->Last->is(tok::l_brace)) {
1503 tryMergeSimpleBlock(I, E, Limit);
1504 } else if (I->First.is(tok::kw_if)) {
1505 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001506 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1507 I->First.FormatTok.IsFirst)) {
1508 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001509 }
1510 return true;
1511 }
1512
Daniel Jasper39825ea2013-01-14 15:40:57 +00001513 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1514 std::vector<AnnotatedLine>::iterator E,
1515 unsigned Limit) {
1516 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001517 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1518 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001519 if (I + 2 != E && (I + 2)->InPPDirective &&
1520 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1521 return;
1522 if (!fitsIntoLimit((I + 1)->First, Limit)) return;
1523 join(Line, *(++I));
1524 }
1525
Daniel Jasper25837aa2013-01-14 14:14:23 +00001526 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1527 std::vector<AnnotatedLine>::iterator E,
1528 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001529 if (!Style.AllowShortIfStatementsOnASingleLine)
1530 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001531 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001532 if (Line.Last->isNot(tok::r_paren))
1533 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001534 if (!fitsIntoLimit((I + 1)->First, Limit))
1535 return;
1536 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1537 return;
1538 // Only inline simple if's (no nested if or else).
1539 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1540 return;
1541 join(Line, *(++I));
1542 }
1543
1544 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1545 std::vector<AnnotatedLine>::iterator E,
1546 unsigned Limit){
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001547 // Check that we still have three lines and they fit into the limit.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001548 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1549 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001550
1551 // First, check that the current line allows merging. This is the case if
1552 // we're not in a control flow statement and the last token is an opening
1553 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001554 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001555 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001556 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1557 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1558 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1559 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001560 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001561 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1562 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001563 if (!AllowedTokens)
1564 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001565
1566 // Second, check that the next line does not contain any braces - if it
1567 // does, readability declines when putting it into a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001568 const AnnotatedToken *Tok = &(I + 1)->First;
1569 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001570 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001571 do {
1572 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001573 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001574 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1575 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001576
1577 // Last, check that the third line contains a single closing brace.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001578 Tok = &(I + 2)->First;
1579 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1580 Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001581 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001582
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001583 // If the merged line fits, we use that instead and skip the next two lines.
1584 Line.Last->Children.push_back((I + 1)->First);
1585 while (!Line.Last->Children.empty()) {
1586 Line.Last->Children[0].Parent = Line.Last;
1587 Line.Last = &Line.Last->Children[0];
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001588 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001589
1590 join(Line, *(I + 1));
1591 join(Line, *(I + 2));
1592 I += 2;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001593 }
1594
1595 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1596 unsigned Limit) {
1597 unsigned LengthLine1 = 0;
1598 unsigned LengthLine2 = 0;
1599 if (!fitsIntoLimit((I + 1)->First, Limit, &LengthLine1) ||
1600 !fitsIntoLimit((I + 2)->First, Limit, &LengthLine2))
1601 return false;
1602 return LengthLine1 + LengthLine2 + 1 <= Limit; // One space.
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001603 }
1604
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001605 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1606 A.Last->Children.push_back(B.First);
1607 while (!A.Last->Children.empty()) {
1608 A.Last->Children[0].Parent = A.Last;
1609 A.Last = &A.Last->Children[0];
1610 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001611 }
1612
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001613 bool touchesRanges(const AnnotatedLine &TheLine) {
1614 const FormatToken *First = &TheLine.First.FormatTok;
1615 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001616 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001617 First->Tok.getLocation(),
1618 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001619 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001620 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1621 Ranges[i].getBegin()) &&
1622 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1623 LineRange.getBegin()))
1624 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001625 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001626 return false;
1627 }
1628
1629 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001630 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001631 }
1632
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001633 /// \brief Add a new line and the required indent before the first Token
1634 /// of the \c UnwrappedLine if there was no structural parsing error.
1635 /// Returns the indent level of the \c UnwrappedLine.
1636 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1637 bool InPPDirective,
1638 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001639 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001640 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1641 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1642
1643 unsigned Newlines = std::min(Tok.NewlinesBefore,
1644 Style.MaxEmptyLinesToKeep + 1);
1645 if (Newlines == 0 && !Tok.IsFirst)
1646 Newlines = 1;
1647 unsigned Indent = Level * 2;
1648
1649 bool IsAccessModifier = false;
1650 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1651 RootToken.is(tok::kw_private))
1652 IsAccessModifier = true;
1653 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1654 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1655 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1656 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1657 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1658 IsAccessModifier = true;
1659
1660 if (IsAccessModifier &&
1661 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1662 Indent += Style.AccessModifierOffset;
1663 if (!InPPDirective || Tok.HasUnescapedNewline) {
1664 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1665 } else {
1666 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1667 SourceMgr, Replaces);
1668 }
1669 return Indent;
1670 }
1671
Alexander Kornienko116ba682013-01-14 11:34:14 +00001672 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001673 FormatStyle Style;
1674 Lexer &Lex;
1675 SourceManager &SourceMgr;
1676 tooling::Replacements Replaces;
1677 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001678 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001679 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001680};
1681
1682tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1683 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001684 std::vector<CharSourceRange> Ranges,
1685 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001686 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001687 OwningPtr<DiagnosticConsumer> DiagPrinter;
1688 if (DiagClient == 0) {
1689 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1690 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1691 DiagClient = DiagPrinter.get();
1692 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001693 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001694 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001695 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001696 Diagnostics.setSourceManager(&SourceMgr);
1697 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001698 return formatter.format();
1699}
1700
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001701LangOptions getFormattingLangOpts() {
1702 LangOptions LangOpts;
1703 LangOpts.CPlusPlus = 1;
1704 LangOpts.CPlusPlus11 = 1;
1705 LangOpts.Bool = 1;
1706 LangOpts.ObjC1 = 1;
1707 LangOpts.ObjC2 = 1;
1708 return LangOpts;
1709}
1710
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001711} // namespace format
1712} // namespace clang