blob: 4b5c2b8f662b22faac9d8c758d5fe6be37654212 [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
Daniel Jaspera67a8f02013-01-16 10:41:46 +000089 /// \brief The total length of the line up to and including this token.
90 unsigned TotalLength;
91
Daniel Jasper7c85fde2013-01-08 14:56:18 +000092 std::vector<AnnotatedToken> Children;
93 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000094};
95
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +000096class AnnotatedLine {
97public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +000098 AnnotatedLine(const UnwrappedLine &Line)
99 : First(Line.Tokens.front()), Level(Line.Level),
100 InPPDirective(Line.InPPDirective) {
101 assert(!Line.Tokens.empty());
102 AnnotatedToken *Current = &First;
103 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
104 E = Line.Tokens.end();
105 I != E; ++I) {
106 Current->Children.push_back(*I);
107 Current->Children[0].Parent = Current;
108 Current = &Current->Children[0];
109 }
110 Last = Current;
111 }
112 AnnotatedLine(const AnnotatedLine &Other)
113 : First(Other.First), Type(Other.Type), Level(Other.Level),
114 InPPDirective(Other.InPPDirective) {
115 Last = &First;
116 while (!Last->Children.empty()) {
117 Last->Children[0].Parent = Last;
118 Last = &Last->Children[0];
119 }
120 }
121
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000122 AnnotatedToken First;
123 AnnotatedToken *Last;
124
125 LineType Type;
126 unsigned Level;
127 bool InPPDirective;
128};
129
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000130static prec::Level getPrecedence(const AnnotatedToken &Tok) {
131 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000132}
133
Daniel Jasperf7935112012-12-03 18:12:45 +0000134FormatStyle getLLVMStyle() {
135 FormatStyle LLVMStyle;
136 LLVMStyle.ColumnLimit = 80;
137 LLVMStyle.MaxEmptyLinesToKeep = 1;
138 LLVMStyle.PointerAndReferenceBindToType = false;
139 LLVMStyle.AccessModifierOffset = -2;
140 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000141 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000142 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000143 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000144 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000145 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000146 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000147 return LLVMStyle;
148}
149
150FormatStyle getGoogleStyle() {
151 FormatStyle GoogleStyle;
152 GoogleStyle.ColumnLimit = 80;
153 GoogleStyle.MaxEmptyLinesToKeep = 1;
154 GoogleStyle.PointerAndReferenceBindToType = true;
155 GoogleStyle.AccessModifierOffset = -1;
156 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000157 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000158 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000159 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000160 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Webera6087752013-01-10 20:12:55 +0000161 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000162 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000163 return GoogleStyle;
164}
165
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000166FormatStyle getChromiumStyle() {
167 FormatStyle ChromiumStyle = getGoogleStyle();
168 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
169 return ChromiumStyle;
170}
171
Daniel Jasperf7935112012-12-03 18:12:45 +0000172struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000173 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000174 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000175 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000176};
177
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000178/// \brief Replaces the whitespace in front of \p Tok. Only call once for
179/// each \c FormatToken.
180static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
181 unsigned Spaces, const FormatStyle &Style,
182 SourceManager &SourceMgr,
183 tooling::Replacements &Replaces) {
184 Replaces.insert(tooling::Replacement(
185 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
186 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
187}
188
189/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
190/// backslashes to escape newlines inside a preprocessor directive.
191///
192/// This function and \c replaceWhitespace have the same behavior if
193/// \c Newlines == 0.
194static void replacePPWhitespace(
195 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
196 unsigned WhitespaceStartColumn, const FormatStyle &Style,
197 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
198 std::string NewLineText;
199 if (NewLines > 0) {
200 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
201 WhitespaceStartColumn);
202 for (unsigned i = 0; i < NewLines; ++i) {
203 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
204 NewLineText += "\\\n";
205 Offset = 0;
206 }
207 }
208 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
209 Tok.FormatTok.WhiteSpaceLength,
210 NewLineText + std::string(Spaces, ' ')));
211}
212
Nico Weberc9d73612013-01-12 22:48:47 +0000213/// \brief Returns if a token is an Objective-C selector name.
214///
Nico Weber92c05392013-01-12 22:51:13 +0000215/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000216static bool isObjCSelectorName(const AnnotatedToken &Tok) {
217 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
218 Tok.Children[0].is(tok::colon) &&
219 Tok.Children[0].Type == TT_ObjCMethodExpr;
220}
221
Daniel Jasperf7935112012-12-03 18:12:45 +0000222class UnwrappedLineFormatter {
223public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000224 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000225 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000226 const AnnotatedToken &RootToken,
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000227 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000228 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000229 FirstIndent(FirstIndent), RootToken(RootToken), Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000230 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000231 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000232 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000233 }
234
Manuel Klimek1abf7892013-01-04 23:34:14 +0000235 /// \brief Formats an \c UnwrappedLine.
236 ///
237 /// \returns The column after the last token in the last line of the
238 /// \c UnwrappedLine.
239 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000240 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000241 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000242 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000243 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000244 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000245 State.ForLoopVariablePos = 0;
246 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000247 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000248
249 // The first token has already been indented and thus consumed.
250 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000251
252 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000253 while (State.NextToken != NULL) {
Manuel Klimeka31e58b2013-01-15 16:41:02 +0000254 if (State.NextToken->Type == TT_ImplicitStringLiteral)
255 // We will not touch the rest of the white space in this
256 // \c UnwrappedLine. The returned value can also not matter, as we
257 // cannot continue an top-level implicit string literal on the next
258 // line.
259 return 0;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000260 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000261 addTokenToState(false, false, State);
262 } else {
263 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
264 unsigned Break = calcPenalty(State, true, NoBreak);
265 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000266 if (State.NextToken != NULL &&
267 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
268 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000269 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000270 State.Stack.back().BreakAfterComma = true;
271 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000272 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000273 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000274 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000275 }
276
277private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000278 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000279 ParenState(unsigned Indent, unsigned LastSpace)
280 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
281 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000282
Daniel Jasperf7935112012-12-03 18:12:45 +0000283 /// \brief The position to which a specific parenthesis level needs to be
284 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000285 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000286
Daniel Jaspere9de2602012-12-06 09:56:08 +0000287 /// \brief The position of the last space on each level.
288 ///
289 /// Used e.g. to break like:
290 /// functionCall(Parameter, otherCall(
291 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000292 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000293
Daniel Jaspere9de2602012-12-06 09:56:08 +0000294 /// \brief The position the first "<<" operator encountered on each level.
295 ///
296 /// Used to align "<<" operators. 0 if no such operator has been encountered
297 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000298 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000299
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000300 /// \brief Whether a newline needs to be inserted before the block's closing
301 /// brace.
302 ///
303 /// We only want to insert a newline before the closing brace if there also
304 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000305 bool BreakBeforeClosingBrace;
306
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000307 bool BreakAfterComma;
308
Daniel Jasper337816e2013-01-11 10:22:12 +0000309 bool operator<(const ParenState &Other) const {
310 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000311 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000312 if (LastSpace != Other.LastSpace)
313 return LastSpace < Other.LastSpace;
314 if (FirstLessLess != Other.FirstLessLess)
315 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000316 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
317 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000318 if (BreakAfterComma != Other.BreakAfterComma)
319 return BreakAfterComma;
320 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000321 }
322 };
323
324 /// \brief The current state when indenting a unwrapped line.
325 ///
326 /// As the indenting tries different combinations this is copied by value.
327 struct LineState {
328 /// \brief The number of used columns in the current line.
329 unsigned Column;
330
331 /// \brief The token that needs to be next formatted.
332 const AnnotatedToken *NextToken;
333
334 /// \brief The parenthesis level of the first token on the current line.
335 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000336
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000337 /// \brief The column of the first variable in a for-loop declaration.
338 ///
339 /// Used to align the second variable if necessary.
340 unsigned ForLoopVariablePos;
341
342 /// \brief \c true if this line contains a continued for-loop section.
343 bool LineContainsContinuedForLoopSection;
344
Daniel Jasper337816e2013-01-11 10:22:12 +0000345 /// \brief A stack keeping track of properties applying to parenthesis
346 /// levels.
347 std::vector<ParenState> Stack;
348
349 /// \brief Comparison operator to be able to used \c LineState in \c map.
350 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000351 if (Other.NextToken != NextToken)
352 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000353 if (Other.Column != Column)
354 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000355 if (Other.StartOfLineLevel != StartOfLineLevel)
356 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000357 if (Other.ForLoopVariablePos != ForLoopVariablePos)
358 return Other.ForLoopVariablePos < ForLoopVariablePos;
359 if (Other.LineContainsContinuedForLoopSection !=
360 LineContainsContinuedForLoopSection)
361 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000363 }
364 };
365
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000366 /// \brief Appends the next token to \p State and updates information
367 /// necessary for indentation.
368 ///
369 /// Puts the token on the current line if \p Newline is \c true and adds a
370 /// line break and necessary indentation otherwise.
371 ///
372 /// If \p DryRun is \c false, also creates and stores the required
373 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000374 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000375 const AnnotatedToken &Current = *State.NextToken;
376 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000377 assert(State.Stack.size());
378 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000379
380 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000381 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000382 if (Current.is(tok::r_brace)) {
383 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000384 } else if (Current.is(tok::string_literal) &&
385 Previous.is(tok::string_literal)) {
386 State.Column = State.Column - Previous.FormatTok.TokenLength;
387 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000388 State.Stack[ParenLevel].FirstLessLess != 0) {
389 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000390 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000391 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
392 Current.is(tok::period) || Previous.is(tok::question) ||
393 Previous.Type == TT_ConditionalExpr)) {
394 // Indent and extra 4 spaces after if we know the current expression is
395 // continued. Don't do that on the top level, as we already indent 4
396 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000397 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000398 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000399 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000400 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000401 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000402 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000403 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000404 }
405
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000406 // A line starting with a closing brace is assumed to be correct for the
407 // same level as before the opening brace.
408 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000409
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000410 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000411 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000412
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000413 if (!DryRun) {
414 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000415 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
416 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000417 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000418 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000419 WhitespaceStartColumn, Style, SourceMgr,
420 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000421 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000422
Daniel Jasper337816e2013-01-11 10:22:12 +0000423 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000424 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000425 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000427 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
428 State.ForLoopVariablePos = State.Column -
429 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000430
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000431 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
432 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000433 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000434
Daniel Jasperf7935112012-12-03 18:12:45 +0000435 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000436 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000437
Daniel Jasperbcab4302013-01-09 10:40:23 +0000438 // FIXME: Do we need to do this for assignments nested in other
439 // expressions?
440 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000441 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000442 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000443 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000444 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000445 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000446 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000447
Daniel Jasper206df732013-01-07 13:08:40 +0000448 // Top-level spaces that are not part of assignments are exempt as that
449 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000450 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000451 if (Spaces > 0 &&
452 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000453 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000454 }
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000455 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000456 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000457 }
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000458 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000459 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000460
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000461 /// \brief Mark the next token as consumed in \p State and modify its stacks
462 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000463 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000464 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000465 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000466
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
468 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000469
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000470 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000471 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000472 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
473 Current.is(tok::l_brace) ||
474 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000475 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000476 if (Current.is(tok::l_brace)) {
477 // FIXME: This does not work with nested static initializers.
478 // Implement a better handling for static initializers and similar
479 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000480 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000481 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000482 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000483 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000484 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000485 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000486 }
487
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000488 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000489 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000490 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
491 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
492 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000493 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000494 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000495
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000496 if (State.NextToken->Children.empty())
497 State.NextToken = NULL;
498 else
499 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000500
501 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000502 }
503
Nico Weber49cbc2c2013-01-07 15:15:29 +0000504 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000505 unsigned splitPenalty(const AnnotatedToken &Tok) {
506 const AnnotatedToken &Left = Tok;
507 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000508
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000509 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
510 return 50;
511 if (Left.is(tok::equal) && Right.is(tok::l_brace))
512 return 150;
513
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000514 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000515 if (RootToken.is(tok::kw_for) &&
516 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000517 return 20;
518
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000519 if (Left.is(tok::semi) || Left.is(tok::comma) ||
520 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000521 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000522
523 // In Objective-C method expressions, prefer breaking before "param:" over
524 // breaking after it.
525 if (isObjCSelectorName(Right))
526 return 0;
527 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
528 return 20;
529
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000530 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000531 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000532
Daniel Jasper399d24b2013-01-09 07:06:56 +0000533 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
534 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000535 prec::Level Level = getPrecedence(Left);
536
537 // Breaking after an assignment leads to a bad result as the two sides of
538 // the assignment are visually very close together.
539 if (Level == prec::Assignment)
540 return 50;
541
Daniel Jasperde5c2072012-12-24 00:13:23 +0000542 if (Level != prec::Unknown)
543 return Level;
544
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000545 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000546 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000547
Daniel Jasperf7935112012-12-03 18:12:45 +0000548 return 3;
549 }
550
Daniel Jasper2df93312013-01-09 10:16:05 +0000551 unsigned getColumnLimit() {
552 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
553 }
554
Daniel Jasperf7935112012-12-03 18:12:45 +0000555 /// \brief Calculate the number of lines needed to format the remaining part
556 /// of the unwrapped line.
557 ///
558 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000560 /// added after the previous token.
561 ///
562 /// \param StopAt is used for optimization. If we can determine that we'll
563 /// definitely need at least \p StopAt additional lines, we already know of a
564 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000565 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000566 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000567 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000568 return 0;
569
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000570 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000571 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000572 if (NewLine && !State.NextToken->CanBreakBefore &&
573 !(State.NextToken->is(tok::r_brace) &&
574 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000575 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000576 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000577 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000578 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000579 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000580 State.LineContainsContinuedForLoopSection)
581 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000582 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
583 State.NextToken->Type != TT_LineComment &&
584 State.Stack.back().BreakAfterComma)
585 return UINT_MAX;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000586 if (!NewLine && State.NextToken->Type == TT_CtorInitializerColon)
587 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000588
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000589 unsigned CurrentPenalty = 0;
590 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000591 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000592 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000593 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000594 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000595 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000596 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000597 }
598
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000599 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000600
Daniel Jasper2df93312013-01-09 10:16:05 +0000601 // Exceeding column limit is bad, assign penalty.
602 if (State.Column > getColumnLimit()) {
603 unsigned ExcessCharacters = State.Column - getColumnLimit();
604 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
605 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000606
Daniel Jasperf7935112012-12-03 18:12:45 +0000607 if (StopAt <= CurrentPenalty)
608 return UINT_MAX;
609 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000610 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000611 if (I != Memory.end()) {
612 // If this state has already been examined, we can safely return the
613 // previous result if we
614 // - have not hit the optimatization (and thus returned UINT_MAX) OR
615 // - are now computing for a smaller or equal StopAt.
616 unsigned SavedResult = I->second.first;
617 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000618 if (SavedResult != UINT_MAX)
619 return SavedResult + CurrentPenalty;
620 else if (StopAt <= SavedStopAt)
621 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000622 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000623
624 unsigned NoBreak = calcPenalty(State, false, StopAt);
625 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
626 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000627
628 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
629 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000630 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000631
632 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000633 }
634
Daniel Jasperf7935112012-12-03 18:12:45 +0000635 FormatStyle Style;
636 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000637 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000638 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000639 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000640 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000641
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000642 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000643 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000644 StateMap Memory;
645
Daniel Jasperf7935112012-12-03 18:12:45 +0000646 OptimizationParameters Parameters;
647};
648
649/// \brief Determines extra information about the tokens comprising an
650/// \c UnwrappedLine.
651class TokenAnnotator {
652public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000653 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
654 AnnotatedLine &Line)
655 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000656
657 /// \brief A parser that gathers additional information about tokens.
658 ///
659 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
660 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
661 /// into template parameter lists.
662 class AnnotatingParser {
663 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000664 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000665 : CurrentToken(&RootToken), KeywordVirtualFound(false),
666 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000667
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000668 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000669 while (CurrentToken != NULL) {
670 if (CurrentToken->is(tok::greater)) {
671 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000672 next();
673 return true;
674 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000675 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
676 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000677 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000678 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
679 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000680 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000681 if (!consumeToken())
682 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000683 }
684 return false;
685 }
686
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000687 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000688 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
689 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000690 while (CurrentToken != NULL) {
691 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 next();
693 return true;
694 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000695 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000696 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000697 if (!consumeToken())
698 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000699 }
700 return false;
701 }
702
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000703 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000704 if (!CurrentToken)
705 return false;
706
707 // A '[' could be an index subscript (after an indentifier or after
708 // ')' or ']'), or it could be the start of an Objective-C method
709 // expression.
710 AnnotatedToken *LSquare = CurrentToken->Parent;
711 bool StartsObjCMethodExpr =
712 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
713 LSquare->Parent->is(tok::l_square) ||
714 LSquare->Parent->is(tok::l_paren) ||
715 LSquare->Parent->is(tok::kw_return) ||
716 LSquare->Parent->is(tok::kw_throw) ||
717 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
718 true, true) > prec::Unknown;
719
720 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
721 if (StartsObjCMethodExpr) {
722 ColonIsObjCMethodExpr = true;
723 LSquare->Type = TT_ObjCMethodExpr;
724 }
725
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000726 while (CurrentToken != NULL) {
727 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000728 if (StartsObjCMethodExpr) {
729 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
730 CurrentToken->Type = TT_ObjCMethodExpr;
731 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000732 next();
733 return true;
734 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000735 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000736 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000737 if (!consumeToken())
738 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000739 }
740 return false;
741 }
742
Daniel Jasper83a54d22013-01-10 09:26:47 +0000743 bool parseBrace() {
744 while (CurrentToken != NULL) {
745 if (CurrentToken->is(tok::r_brace)) {
746 next();
747 return true;
748 }
749 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
750 return false;
751 if (!consumeToken())
752 return false;
753 }
754 // Lines can currently end with '{'.
755 return true;
756 }
757
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000758 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000759 while (CurrentToken != NULL) {
760 if (CurrentToken->is(tok::colon)) {
761 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000762 next();
763 return true;
764 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000765 if (!consumeToken())
766 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000767 }
768 return false;
769 }
770
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000771 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000772 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
773 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000774 next();
775 if (!parseAngle())
776 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000777 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000778 parseLine();
779 return true;
780 }
781 return false;
782 }
783
Daniel Jasperc0880a92013-01-04 18:52:56 +0000784 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000785 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000786 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000787 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000788 case tok::plus:
789 case tok::minus:
790 // At the start of the line, +/- specific ObjectiveC method
791 // declarations.
792 if (Tok->Parent == NULL)
793 Tok->Type = TT_ObjCMethodSpecifier;
794 break;
Nico Webera7252d82013-01-12 06:18:40 +0000795 case tok::colon:
796 // Colons from ?: are handled in parseConditional().
797 if (ColonIsObjCMethodExpr)
798 Tok->Type = TT_ObjCMethodExpr;
799 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000800 case tok::l_paren: {
Daniel Jasper25837aa2013-01-14 14:14:23 +0000801 bool ParensWereObjCReturnType = Tok->Parent && Tok->Parent->Type ==
802 TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000803 if (!parseParens())
804 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000805 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
806 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000807 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000808 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
809 CurrentToken->Type = TT_ObjCSelectorStart;
810 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000811 }
Nico Weber9efe2912013-01-10 23:11:41 +0000812 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000813 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000814 if (!parseSquare())
815 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000816 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000817 case tok::l_brace:
818 if (!parseBrace())
819 return false;
820 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000821 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000822 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000823 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000824 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000825 Tok->Type = TT_BinaryOperator;
826 CurrentToken = Tok;
827 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000828 }
829 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000830 case tok::r_paren:
831 case tok::r_square:
832 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000833 case tok::r_brace:
834 // Lines can start with '}'.
835 if (Tok->Parent != NULL)
836 return false;
837 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000838 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000839 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000840 break;
841 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000842 if (CurrentToken->is(tok::l_paren)) {
843 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000844 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000845 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
846 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000847 next();
848 }
849 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000850 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
851 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000852 next();
853 }
854 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000855 break;
856 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000857 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000858 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000859 case tok::kw_template:
860 parseTemplateDeclaration();
861 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000862 default:
863 break;
864 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000865 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000866 }
867
Daniel Jasper050948a52012-12-21 17:58:39 +0000868 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000869 next();
870 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
871 next();
872 while (CurrentToken != NULL) {
873 CurrentToken->Type = TT_ImplicitStringLiteral;
874 next();
875 }
876 } else {
877 while (CurrentToken != NULL) {
878 next();
879 }
880 }
881 }
882
883 void parseWarningOrError() {
884 next();
885 // We still want to format the whitespace left of the first token of the
886 // warning or error.
887 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000888 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000889 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +0000890 next();
891 }
892 }
893
894 void parsePreprocessorDirective() {
895 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000896 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000897 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000898 // Hashes in the middle of a line can lead to any strange token
899 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000900 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000901 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000902 switch (
903 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000904 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000905 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000906 parseIncludeDirective();
907 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +0000908 case tok::pp_error:
909 case tok::pp_warning:
910 parseWarningOrError();
911 break;
Daniel Jasper050948a52012-12-21 17:58:39 +0000912 default:
913 break;
914 }
915 }
916
Daniel Jasperda16db32013-01-07 10:48:50 +0000917 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000918 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000919 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000920 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000921 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000922 while (CurrentToken != NULL) {
923 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000924 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000925 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000926 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000927 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000928 if (KeywordVirtualFound)
929 return LT_VirtualFunctionDecl;
930 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000931 }
932
933 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000934 if (CurrentToken != NULL && !CurrentToken->Children.empty())
935 CurrentToken = &CurrentToken->Children[0];
936 else
937 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000938 }
939
940 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000941 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000942 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +0000943 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000944 };
945
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000946 void calculateExtraInformation(AnnotatedToken &Current) {
947 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
948
Manuel Klimek52b15152013-01-09 15:25:02 +0000949 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000950 Current.MustBreakBefore = true;
951 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +0000952 if (Current.Type == TT_LineComment) {
953 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000954 } else if (Current.Parent->Type == TT_LineComment ||
Daniel Jasper942ee722013-01-13 16:10:20 +0000955 (Current.is(tok::string_literal) &&
956 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +0000957 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000958 } else {
959 Current.MustBreakBefore = false;
960 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000961 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000962 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000963 if (Current.MustBreakBefore)
964 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
965 else
966 Current.TotalLength = Current.Parent->TotalLength +
967 Current.FormatTok.TokenLength +
968 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000969 if (!Current.Children.empty())
970 calculateExtraInformation(Current.Children[0]);
971 }
972
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000973 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000974 AnnotatingParser Parser(Line.First);
975 Line.Type = Parser.parseLine();
976 if (Line.Type == LT_Invalid)
977 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000978
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000979 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000980
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000981 if (Line.First.Type == TT_ObjCMethodSpecifier)
982 Line.Type = LT_ObjCMethodDecl;
983 else if (Line.First.Type == TT_ObjCDecl)
984 Line.Type = LT_ObjCDecl;
985 else if (Line.First.Type == TT_ObjCProperty)
986 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000987
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000988 Line.First.SpaceRequiredBefore = true;
989 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
990 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +0000991
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000992 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000993 if (!Line.First.Children.empty())
994 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +0000995 }
996
997private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000998 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
999 if (getPrecedence(Current) == prec::Assignment ||
1000 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1001 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001002
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001003 if (Current.Type == TT_Unknown) {
1004 if (Current.is(tok::star) || Current.is(tok::amp)) {
1005 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001006 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1007 Current.is(tok::caret)) {
1008 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001009 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1010 Current.Type = determineIncrementUsage(Current);
1011 } else if (Current.is(tok::exclaim)) {
1012 Current.Type = TT_UnaryOperator;
1013 } else if (isBinaryOperator(Current)) {
1014 Current.Type = TT_BinaryOperator;
1015 } else if (Current.is(tok::comment)) {
1016 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1017 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001018 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001019 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001020 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001021 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001022 } else if (Current.is(tok::r_paren) &&
1023 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001024 Current.Parent->Type == TT_TemplateCloser) &&
1025 (Current.Children.empty() ||
1026 (Current.Children[0].isNot(tok::equal) &&
1027 Current.Children[0].isNot(tok::semi) &&
1028 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001029 // FIXME: We need to get smarter and understand more cases of casts.
1030 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001031 } else if (Current.is(tok::at) && Current.Children.size()) {
1032 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1033 case tok::objc_interface:
1034 case tok::objc_implementation:
1035 case tok::objc_protocol:
1036 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001037 break;
1038 case tok::objc_property:
1039 Current.Type = TT_ObjCProperty;
1040 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001041 default:
1042 break;
1043 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001044 }
1045 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001046
1047 if (!Current.Children.empty())
1048 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001049 }
1050
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001051 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001052 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001053 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001054 }
1055
Daniel Jasper71945272013-01-15 14:27:39 +00001056 /// \brief Returns the previous token ignoring comments.
1057 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1058 const AnnotatedToken *PrevToken = Tok.Parent;
1059 while (PrevToken != NULL && PrevToken->is(tok::comment))
1060 PrevToken = PrevToken->Parent;
1061 return PrevToken;
1062 }
1063
1064 /// \brief Returns the next token ignoring comments.
1065 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1066 if (Tok.Children.empty())
1067 return NULL;
1068 const AnnotatedToken *NextToken = &Tok.Children[0];
1069 while (NextToken->is(tok::comment)) {
1070 if (NextToken->Children.empty())
1071 return NULL;
1072 NextToken = &NextToken->Children[0];
1073 }
1074 return NextToken;
1075 }
1076
1077 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001078 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001079 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1080 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001081 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001082
1083 const AnnotatedToken *NextToken = getNextToken(Tok);
1084 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001085 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001086
Daniel Jasper71945272013-01-15 14:27:39 +00001087 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1088 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1089 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1090 PrevToken->Type == TT_BinaryOperator ||
1091 PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001092 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001093
Daniel Jasper71945272013-01-15 14:27:39 +00001094 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1095 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1096 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1097 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1098 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1099 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1100 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001101 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001102
Daniel Jasper71945272013-01-15 14:27:39 +00001103 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1104 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001105 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001106
Daniel Jasper426702d2012-12-05 07:51:39 +00001107 // It is very unlikely that we are going to find a pointer or reference type
1108 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001109 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001110 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001111
Daniel Jasperda16db32013-01-07 10:48:50 +00001112 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001113 }
1114
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001115 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001116 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1117 if (PrevToken == NULL)
1118 return TT_UnaryOperator;
1119
Daniel Jasper8dd40472012-12-21 09:41:31 +00001120 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001121 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1122 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1123 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1124 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1125 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001126 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001127
1128 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001129 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001130 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001131
1132 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001133 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001134 }
1135
1136 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001137 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001138 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1139 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001140 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001141 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1142 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001143 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001144
Daniel Jasperda16db32013-01-07 10:48:50 +00001145 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001146 }
1147
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001148 bool spaceRequiredBetween(const AnnotatedToken &Left,
1149 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001150 if (Right.is(tok::hashhash))
1151 return Left.is(tok::hash);
1152 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1153 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001154 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1155 return false;
Nico Webera6087752013-01-10 20:12:55 +00001156 if (Right.is(tok::less) &&
1157 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001158 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001159 return true;
1160 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1161 return false;
1162 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1163 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001164 if (Left.is(tok::at) &&
1165 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1166 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001167 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1168 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001169 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001170 if (Left.is(tok::coloncolon))
1171 return false;
1172 if (Right.is(tok::coloncolon))
1173 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001174 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1175 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001176 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001177 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001178 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1179 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001180 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001181 return Right.FormatTok.Tok.isLiteral() ||
1182 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001183 if (Right.is(tok::star) && Left.is(tok::l_paren))
1184 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001185 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1186 return false;
1187 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001188 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001189 if (Left.is(tok::period) || Right.is(tok::period))
1190 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001191 if (Left.is(tok::colon))
1192 return Left.Type != TT_ObjCMethodExpr;
1193 if (Right.is(tok::colon))
1194 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001195 if (Left.is(tok::l_paren))
1196 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001197 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001198 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001199 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001200 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001201 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1202 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001203 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001204 if (Left.is(tok::at) &&
1205 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001206 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001207 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1208 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001209 return true;
1210 }
1211
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001212 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001213 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001214 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1215 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001216 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001217 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001218 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001219 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001220 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1221 if (Tok.Type == TT_ObjCSelectorStart)
1222 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001223 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001224 // Don't space between ')' and <id>
1225 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001226 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001227 // Don't space between ':' and '('
1228 return false;
1229 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001230 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001231 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1232 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001233
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001234 if (Tok.Parent->is(tok::comma))
1235 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001236 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001237 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001238 if (Tok.Type == TT_OverloadedOperator)
1239 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001240 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001241 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001242 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001243 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001244 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001245 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001246 if (Tok.Parent->Type == TT_UnaryOperator ||
1247 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001248 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001249 if (Tok.Type == TT_UnaryOperator)
1250 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001251 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1252 (Tok.Parent->isNot(tok::colon) ||
1253 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001254 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1255 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001256 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1257 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001258 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001259 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001260 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001261 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001262 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001263 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001264 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001265 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001266 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001267 }
1268
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001269 bool canBreakBefore(const AnnotatedToken &Right) {
1270 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001271 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001272 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1273 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001274 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001275 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1276 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001277 // Don't break this identifier as ':' or identifier
1278 // before it will break.
1279 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001280 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1281 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001282 // Don't break at ':' if identifier before it can beak.
1283 return false;
1284 }
Nico Webera7252d82013-01-12 06:18:40 +00001285 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1286 return false;
1287 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1288 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001289 if (isObjCSelectorName(Right))
1290 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001291 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001292 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001293 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001294 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001295 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001296 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001297 return false;
1298
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001299 if (Right.is(tok::comment))
Daniel Jasper942ee722013-01-13 16:10:20 +00001300 // We rely on MustBreakBefore being set correctly here as we should not
1301 // change the "binding" behavior of a comment.
1302 return false;
1303
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001304 // We only break before r_brace if there was a corresponding break before
1305 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1306 if (Right.is(tok::r_brace))
1307 return false;
1308
Daniel Jasper71945272013-01-15 14:27:39 +00001309 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001310 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001311 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1312 Left.is(tok::comma) || Right.is(tok::lessless) ||
1313 Right.is(tok::arrow) || Right.is(tok::period) ||
1314 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001315 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1316 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1317 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001318 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001319 }
1320
Daniel Jasperf7935112012-12-03 18:12:45 +00001321 FormatStyle Style;
1322 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001323 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001324 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001325};
1326
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001327class LexerBasedFormatTokenSource : public FormatTokenSource {
1328public:
1329 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001330 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001331 IdentTable(Lex.getLangOpts()) {
1332 Lex.SetKeepWhitespaceMode(true);
1333 }
1334
1335 virtual FormatToken getNextToken() {
1336 if (GreaterStashed) {
1337 FormatTok.NewlinesBefore = 0;
1338 FormatTok.WhiteSpaceStart =
1339 FormatTok.Tok.getLocation().getLocWithOffset(1);
1340 FormatTok.WhiteSpaceLength = 0;
1341 GreaterStashed = false;
1342 return FormatTok;
1343 }
1344
1345 FormatTok = FormatToken();
1346 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001347 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001348 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001349 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1350 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001351
1352 // Consume and record whitespace until we find a significant token.
1353 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001354 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001355 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1356 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001357 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1358
1359 if (FormatTok.Tok.is(tok::eof))
1360 return FormatTok;
1361 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001362 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001363 }
Manuel Klimekef920692013-01-07 07:56:50 +00001364
1365 // Now FormatTok is the next non-whitespace token.
1366 FormatTok.TokenLength = Text.size();
1367
Manuel Klimek1abf7892013-01-04 23:34:14 +00001368 // In case the token starts with escaped newlines, we want to
1369 // take them into account as whitespace - this pattern is quite frequent
1370 // in macro definitions.
1371 // FIXME: What do we want to do with other escaped spaces, and escaped
1372 // spaces or newlines in the middle of tokens?
1373 // FIXME: Add a more explicit test.
1374 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001375 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001376 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001377 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001378 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001379 }
1380
1381 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001382 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001383 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001384 FormatTok.Tok.setKind(Info.getTokenID());
1385 }
1386
1387 if (FormatTok.Tok.is(tok::greatergreater)) {
1388 FormatTok.Tok.setKind(tok::greater);
1389 GreaterStashed = true;
1390 }
1391
1392 return FormatTok;
1393 }
1394
1395private:
1396 FormatToken FormatTok;
1397 bool GreaterStashed;
1398 Lexer &Lex;
1399 SourceManager &SourceMgr;
1400 IdentifierTable IdentTable;
1401
1402 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001403 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001404 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1405 Tok.getLength());
1406 }
1407};
1408
Daniel Jasperf7935112012-12-03 18:12:45 +00001409class Formatter : public UnwrappedLineConsumer {
1410public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001411 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1412 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001413 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001414 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001415 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001416
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001417 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001418
Daniel Jasperf7935112012-12-03 18:12:45 +00001419 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001420 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001421 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001422 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001423 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001424 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1425 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1426 Annotator.annotate();
1427 }
1428 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1429 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001430 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001431 const AnnotatedLine &TheLine = *I;
1432 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1433 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1434 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001435 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001436 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001437 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001438 TheLine.First, Replaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001439 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001440 PreviousEndOfLineColumn = Formatter.format();
1441 } else {
1442 // If we did not reformat this unwrapped line, the column at the end of
1443 // the last token is unchanged - thus, we can calculate the end of the
1444 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001445 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001446 SourceMgr.getSpellingColumnNumber(
1447 TheLine.Last->FormatTok.Tok.getLocation()) +
1448 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1449 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001450 1;
1451 }
1452 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001453 return Replaces;
1454 }
1455
1456private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001457 /// \brief Tries to merge lines into one.
1458 ///
1459 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1460 /// if possible; note that \c I will be incremented when lines are merged.
1461 ///
1462 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001463 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001464 std::vector<AnnotatedLine>::iterator &I,
1465 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001466 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1467
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001468 // We can never merge stuff if there are trailing line comments.
1469 if (I->Last->Type == TT_LineComment)
1470 return;
1471
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001472 // Check whether the UnwrappedLine can be put onto a single line. If
1473 // so, this is bound to be the optimal solution (by definition) and we
1474 // don't need to analyze the entire solution space.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001475 if (I->Last->TotalLength >= Limit)
1476 return;
1477 Limit -= I->Last->TotalLength + 1; // One space.
Daniel Jasperc36492b2013-01-16 07:02:34 +00001478
Daniel Jasper25837aa2013-01-14 14:14:23 +00001479 if (I + 1 == E)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001480 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001481
Daniel Jasper25837aa2013-01-14 14:14:23 +00001482 if (I->Last->is(tok::l_brace)) {
1483 tryMergeSimpleBlock(I, E, Limit);
1484 } else if (I->First.is(tok::kw_if)) {
1485 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001486 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1487 I->First.FormatTok.IsFirst)) {
1488 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001489 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001490 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001491 }
1492
Daniel Jasper39825ea2013-01-14 15:40:57 +00001493 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1494 std::vector<AnnotatedLine>::iterator E,
1495 unsigned Limit) {
1496 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001497 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1498 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001499 if (I + 2 != E && (I + 2)->InPPDirective &&
1500 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1501 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001502 if ((I + 1)->Last->TotalLength > Limit)
1503 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001504 join(Line, *(++I));
1505 }
1506
Daniel Jasper25837aa2013-01-14 14:14:23 +00001507 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1508 std::vector<AnnotatedLine>::iterator E,
1509 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001510 if (!Style.AllowShortIfStatementsOnASingleLine)
1511 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001512 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001513 if (Line.Last->isNot(tok::r_paren))
1514 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001515 if ((I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001516 return;
1517 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1518 return;
1519 // Only inline simple if's (no nested if or else).
1520 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1521 return;
1522 join(Line, *(++I));
1523 }
1524
1525 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1526 std::vector<AnnotatedLine>::iterator E,
1527 unsigned Limit){
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001528 // Check that we still have three lines and they fit into the limit.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001529 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1530 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001531
1532 // First, check that the current line allows merging. This is the case if
1533 // we're not in a control flow statement and the last token is an opening
1534 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001535 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001536 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001537 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1538 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1539 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1540 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001541 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001542 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1543 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001544 if (!AllowedTokens)
1545 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001546
1547 // Second, check that the next line does not contain any braces - if it
1548 // does, readability declines when putting it into a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001549 const AnnotatedToken *Tok = &(I + 1)->First;
1550 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001551 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001552 do {
1553 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001554 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001555 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1556 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001557
1558 // Last, check that the third line contains a single closing brace.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001559 Tok = &(I + 2)->First;
1560 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1561 Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001562 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001563
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001564 // If the merged line fits, we use that instead and skip the next two lines.
1565 Line.Last->Children.push_back((I + 1)->First);
1566 while (!Line.Last->Children.empty()) {
1567 Line.Last->Children[0].Parent = Line.Last;
1568 Line.Last = &Line.Last->Children[0];
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001569 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001570
1571 join(Line, *(I + 1));
1572 join(Line, *(I + 2));
1573 I += 2;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001574 }
1575
1576 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1577 unsigned Limit) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001578 return (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001579 }
1580
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001581 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1582 A.Last->Children.push_back(B.First);
1583 while (!A.Last->Children.empty()) {
1584 A.Last->Children[0].Parent = A.Last;
1585 A.Last = &A.Last->Children[0];
1586 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001587 }
1588
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001589 bool touchesRanges(const AnnotatedLine &TheLine) {
1590 const FormatToken *First = &TheLine.First.FormatTok;
1591 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001592 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001593 First->Tok.getLocation(),
1594 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001595 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001596 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1597 Ranges[i].getBegin()) &&
1598 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1599 LineRange.getBegin()))
1600 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001601 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001602 return false;
1603 }
1604
1605 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001606 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001607 }
1608
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001609 /// \brief Add a new line and the required indent before the first Token
1610 /// of the \c UnwrappedLine if there was no structural parsing error.
1611 /// Returns the indent level of the \c UnwrappedLine.
1612 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1613 bool InPPDirective,
1614 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001615 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001616 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1617 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1618
1619 unsigned Newlines = std::min(Tok.NewlinesBefore,
1620 Style.MaxEmptyLinesToKeep + 1);
1621 if (Newlines == 0 && !Tok.IsFirst)
1622 Newlines = 1;
1623 unsigned Indent = Level * 2;
1624
1625 bool IsAccessModifier = false;
1626 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1627 RootToken.is(tok::kw_private))
1628 IsAccessModifier = true;
1629 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1630 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1631 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1632 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1633 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1634 IsAccessModifier = true;
1635
1636 if (IsAccessModifier &&
1637 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1638 Indent += Style.AccessModifierOffset;
1639 if (!InPPDirective || Tok.HasUnescapedNewline) {
1640 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1641 } else {
1642 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1643 SourceMgr, Replaces);
1644 }
1645 return Indent;
1646 }
1647
Alexander Kornienko116ba682013-01-14 11:34:14 +00001648 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001649 FormatStyle Style;
1650 Lexer &Lex;
1651 SourceManager &SourceMgr;
1652 tooling::Replacements Replaces;
1653 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001654 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001655 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001656};
1657
1658tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1659 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001660 std::vector<CharSourceRange> Ranges,
1661 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001662 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001663 OwningPtr<DiagnosticConsumer> DiagPrinter;
1664 if (DiagClient == 0) {
1665 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1666 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1667 DiagClient = DiagPrinter.get();
1668 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001669 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001670 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001671 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001672 Diagnostics.setSourceManager(&SourceMgr);
1673 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001674 return formatter.format();
1675}
1676
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001677LangOptions getFormattingLangOpts() {
1678 LangOptions LangOpts;
1679 LangOpts.CPlusPlus = 1;
1680 LangOpts.CPlusPlus11 = 1;
1681 LangOpts.Bool = 1;
1682 LangOpts.ObjC1 = 1;
1683 LangOpts.ObjC2 = 1;
1684 return LangOpts;
1685}
1686
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001687} // namespace format
1688} // namespace clang