blob: afa9840619efe3bb44fd043089ac5077bae73c9a [file] [log] [blame]
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001//===--- TokenAnnotator.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 a token annotator, i.e. creates
12/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
13///
14//===----------------------------------------------------------------------===//
15
16#include "TokenAnnotator.h"
17#include "clang/Basic/SourceManager.h"
Daniel Jasperbf71ba22013-04-08 20:33:42 +000018#include "llvm/Support/Debug.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019
Stephen Hines6bcf27b2014-05-29 04:14:42 -070020#define DEBUG_TYPE "format-token-annotator"
21
Daniel Jasper32d28ee2013-01-29 21:01:14 +000022namespace clang {
23namespace format {
24
Craig Topper14e66492013-07-01 04:03:19 +000025namespace {
26
Daniel Jasper32d28ee2013-01-29 21:01:14 +000027/// \brief A parser that gathers additional information about tokens.
28///
Alexander Kornienko3fd9ccd2013-03-12 16:28:18 +000029/// The \c TokenAnnotator tries to match parenthesis and square brakets and
Daniel Jasper32d28ee2013-01-29 21:01:14 +000030/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
31/// into template parameter lists.
32class AnnotatingParser {
33public:
Daniel Jasperd4a03db2013-08-22 15:00:41 +000034 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
35 IdentifierInfo &Ident_in)
36 : Style(Style), Line(Line), CurrentToken(Line.First),
Daniel Jasper59875ac2013-11-07 17:43:07 +000037 KeywordVirtualFound(false), AutoFound(false), Ident_in(Ident_in) {
Nico Weber27268772013-06-26 00:30:14 +000038 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
Stephen Hines651f13c2014-04-23 16:59:28 -070039 resetTokenMetadata(CurrentToken);
Daniel Jasper32d28ee2013-01-29 21:01:14 +000040 }
41
Nico Weber95e8e462013-02-12 16:17:07 +000042private:
Daniel Jasper32d28ee2013-01-29 21:01:14 +000043 bool parseAngle() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070044 if (!CurrentToken)
Daniel Jasper32d28ee2013-01-29 21:01:14 +000045 return false;
Daniel Jasper923ebef2013-03-14 13:45:21 +000046 ScopedContextCreator ContextCreator(*this, tok::less, 10);
Manuel Klimekb3987012013-05-29 14:47:47 +000047 FormatToken *Left = CurrentToken->Previous;
Daniel Jasper4e778092013-02-06 10:05:46 +000048 Contexts.back().IsExpression = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070049 // If there's a template keyword before the opening angle bracket, this is a
50 // template parameter, not an argument.
51 Contexts.back().InTemplateArgument =
Stephen Hines6bcf27b2014-05-29 04:14:42 -070052 Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
Stephen Hines651f13c2014-04-23 16:59:28 -070053
Stephen Hines6bcf27b2014-05-29 04:14:42 -070054 while (CurrentToken) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +000055 if (CurrentToken->is(tok::greater)) {
56 Left->MatchingParen = CurrentToken;
57 CurrentToken->MatchingParen = Left;
58 CurrentToken->Type = TT_TemplateCloser;
59 next();
60 return true;
61 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +000062 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace,
Daniel Jasper5d823e32013-05-15 13:46:48 +000063 tok::question, tok::colon))
64 return false;
Daniel Jasper0348be02013-06-01 18:56:00 +000065 // If a && or || is found and interpreted as a binary operator, this set
Daniel Jasper15f33f02013-06-03 16:16:41 +000066 // of angles is likely part of something like "a < b && c > d". If the
Daniel Jasper0348be02013-06-01 18:56:00 +000067 // angles are inside an expression, the ||/&& might also be a binary
68 // operator that was misinterpreted because we are parsing template
69 // parameters.
70 // FIXME: This is getting out of hand, write a decent parser.
Manuel Klimekb3987012013-05-29 14:47:47 +000071 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
Stephen Hines651f13c2014-04-23 16:59:28 -070072 ((CurrentToken->Previous->Type == TT_BinaryOperator &&
73 // Toplevel bool expressions do not make lots of sense;
74 // If we're on the top level, it contains only the base context and
75 // the context for the current opening angle bracket.
76 Contexts.size() > 2) ||
Daniel Jasper0348be02013-06-01 18:56:00 +000077 Contexts[Contexts.size() - 2].IsExpression) &&
Manuel Klimekb3987012013-05-29 14:47:47 +000078 Line.First->isNot(tok::kw_template))
Daniel Jasper32d28ee2013-01-29 21:01:14 +000079 return false;
Daniel Jasper9fc56f22013-02-14 15:01:34 +000080 updateParameterCount(Left, CurrentToken);
Daniel Jasper32d28ee2013-01-29 21:01:14 +000081 if (!consumeToken())
82 return false;
83 }
84 return false;
85 }
86
87 bool parseParens(bool LookForDecls = false) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070088 if (!CurrentToken)
Daniel Jasper32d28ee2013-01-29 21:01:14 +000089 return false;
Daniel Jasper923ebef2013-03-14 13:45:21 +000090 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
Daniel Jasper4e778092013-02-06 10:05:46 +000091
92 // FIXME: This is a bit of a hack. Do better.
93 Contexts.back().ColonIsForRangeExpr =
94 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
95
Daniel Jasper32d28ee2013-01-29 21:01:14 +000096 bool StartsObjCMethodExpr = false;
Manuel Klimekb3987012013-05-29 14:47:47 +000097 FormatToken *Left = CurrentToken->Previous;
Daniel Jasper32d28ee2013-01-29 21:01:14 +000098 if (CurrentToken->is(tok::caret)) {
Stephen Hines651f13c2014-04-23 16:59:28 -070099 // (^ can start a block type.
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000100 Left->Type = TT_ObjCBlockLParen;
Manuel Klimekb3987012013-05-29 14:47:47 +0000101 } else if (FormatToken *MaybeSel = Left->Previous) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000102 // @selector( starts a selector.
Manuel Klimekb3987012013-05-29 14:47:47 +0000103 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
104 MaybeSel->Previous->is(tok::at)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000105 StartsObjCMethodExpr = true;
106 }
107 }
108
Stephen Hines651f13c2014-04-23 16:59:28 -0700109 if (Left->Previous &&
110 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_if,
111 tok::kw_while, tok::l_paren, tok::comma) ||
112 Left->Previous->Type == TT_BinaryOperator)) {
Daniel Jasper363193b2013-10-20 18:15:30 +0000113 // static_assert, if and while usually contain expressions.
Daniel Jasperb7000ca2013-08-01 17:58:23 +0000114 Contexts.back().IsExpression = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700115 } else if (Line.InPPDirective &&
116 (!Left->Previous ||
117 (Left->Previous->isNot(tok::identifier) &&
118 Left->Previous->Type != TT_OverloadedOperator))) {
119 Contexts.back().IsExpression = true;
Daniel Jasper363193b2013-10-20 18:15:30 +0000120 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
121 Left->Previous->MatchingParen &&
122 Left->Previous->MatchingParen->Type == TT_LambdaLSquare) {
123 // This is a parameter list of a lambda expression.
124 Contexts.back().IsExpression = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700125 } else if (Contexts[Contexts.size() - 2].CaretFound) {
126 // This is the parameter list of an ObjC block.
127 Contexts.back().IsExpression = false;
128 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
129 Left->Type = TT_AttributeParen;
130 } else if (Left->Previous && Left->Previous->IsForEachMacro) {
131 // The first argument to a foreach macro is a declaration.
132 Contexts.back().IsForEachMacro = true;
133 Contexts.back().IsExpression = false;
Daniel Jasper363193b2013-10-20 18:15:30 +0000134 }
Daniel Jasperb7000ca2013-08-01 17:58:23 +0000135
Daniel Jasper4e778092013-02-06 10:05:46 +0000136 if (StartsObjCMethodExpr) {
137 Contexts.back().ColonIsObjCMethodExpr = true;
138 Left->Type = TT_ObjCMethodExpr;
139 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000140
Daniel Jasper431f5912013-05-28 08:33:00 +0000141 bool MightBeFunctionType = CurrentToken->is(tok::star);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000142 bool HasMultipleLines = false;
143 bool HasMultipleParametersOnALine = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700144 while (CurrentToken) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000145 // LookForDecls is set when "if (" has been seen. Check for
146 // 'identifier' '*' 'identifier' followed by not '=' -- this
147 // '*' has to be a binary operator but determineStarAmpUsage() will
148 // categorize it as an unary operator, so set the right type here.
Manuel Klimekb3987012013-05-29 14:47:47 +0000149 if (LookForDecls && CurrentToken->Next) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000150 FormatToken *Prev = CurrentToken->getPreviousNonComment();
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000151 if (Prev) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000152 FormatToken *PrevPrev = Prev->getPreviousNonComment();
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000153 FormatToken *Next = CurrentToken->Next;
154 if (PrevPrev && PrevPrev->is(tok::identifier) &&
155 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
156 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
157 Prev->Type = TT_BinaryOperator;
158 LookForDecls = false;
159 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000160 }
161 }
162
Daniel Jasper53352602013-08-12 12:16:34 +0000163 if (CurrentToken->Previous->Type == TT_PointerOrReference &&
164 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
165 tok::coloncolon))
166 MightBeFunctionType = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700167 if (CurrentToken->Previous->Type == TT_BinaryOperator)
168 Contexts.back().IsExpression = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000169 if (CurrentToken->is(tok::r_paren)) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000170 if (MightBeFunctionType && CurrentToken->Next &&
Daniel Jaspere7d3bff2013-07-16 11:37:21 +0000171 (CurrentToken->Next->is(tok::l_paren) ||
172 (CurrentToken->Next->is(tok::l_square) &&
173 !Contexts.back().IsExpression)))
Daniel Jasper431f5912013-05-28 08:33:00 +0000174 Left->Type = TT_FunctionTypeLParen;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000175 Left->MatchingParen = CurrentToken;
176 CurrentToken->MatchingParen = Left;
177
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000178 if (StartsObjCMethodExpr) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000179 CurrentToken->Type = TT_ObjCMethodExpr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700180 if (Contexts.back().FirstObjCSelectorName) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000181 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
182 Contexts.back().LongestObjCSelectorName;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000183 }
184 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000185
Stephen Hines651f13c2014-04-23 16:59:28 -0700186 if (Left->Type == TT_AttributeParen)
187 CurrentToken->Type = TT_AttributeParen;
188
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000189 if (!HasMultipleLines)
190 Left->PackingKind = PPK_Inconclusive;
191 else if (HasMultipleParametersOnALine)
192 Left->PackingKind = PPK_BinPacked;
193 else
194 Left->PackingKind = PPK_OnePerLine;
195
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000196 next();
197 return true;
198 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000199 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000200 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700201 else if (CurrentToken->is(tok::l_brace))
202 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000203 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
204 !CurrentToken->Next->HasUnescapedNewline &&
205 !CurrentToken->Next->isTrailingComment())
206 HasMultipleParametersOnALine = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700207 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
208 CurrentToken->isSimpleTypeSpecifier())
209 Contexts.back().IsExpression = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700210 FormatToken *Tok = CurrentToken;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000211 if (!consumeToken())
212 return false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700213 updateParameterCount(Left, Tok);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000214 if (CurrentToken && CurrentToken->HasUnescapedNewline)
215 HasMultipleLines = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000216 }
217 return false;
218 }
219
220 bool parseSquare() {
221 if (!CurrentToken)
222 return false;
223
Alexander Kornienkod71b15b2013-06-17 13:19:53 +0000224 // A '[' could be an index subscript (after an identifier or after
Nico Weber051860e2013-02-10 02:08:05 +0000225 // ')' or ']'), it could be the start of an Objective-C method
226 // expression, or it could the the start of an Objective-C array literal.
Manuel Klimekb3987012013-05-29 14:47:47 +0000227 FormatToken *Left = CurrentToken->Previous;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000228 FormatToken *Parent = Left->getPreviousNonComment();
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000229 bool StartsObjCMethodExpr =
Daniel Jasper567dcf92013-09-05 09:29:45 +0000230 Contexts.back().CanBeExpression && Left->Type != TT_LambdaLSquare &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700231 CurrentToken->isNot(tok::l_brace) &&
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000232 (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
233 tok::kw_return, tok::kw_throw) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000234 Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000235 Parent->Type == TT_CastRParen ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000236 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
Daniel Jasper923ebef2013-03-14 13:45:21 +0000237 ScopedContextCreator ContextCreator(*this, tok::l_square, 10);
Daniel Jasper6f21a982013-03-13 07:49:51 +0000238 Contexts.back().IsExpression = true;
Daniel Jasper8f54d882013-10-26 17:00:22 +0000239 bool ColonFound = false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000240
Daniel Jasper4e778092013-02-06 10:05:46 +0000241 if (StartsObjCMethodExpr) {
242 Contexts.back().ColonIsObjCMethodExpr = true;
243 Left->Type = TT_ObjCMethodExpr;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000244 } else if (Parent && Parent->is(tok::at)) {
245 Left->Type = TT_ArrayInitializerLSquare;
246 } else if (Left->Type == TT_Unknown) {
247 Left->Type = TT_ArraySubscriptLSquare;
Daniel Jasper4e778092013-02-06 10:05:46 +0000248 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000249
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700250 while (CurrentToken) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000251 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperac2c9742013-09-05 10:04:31 +0000252 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
253 Left->Type == TT_ObjCMethodExpr) {
Nico Webere8a97982013-02-06 06:20:11 +0000254 // An ObjC method call is rarely followed by an open parenthesis.
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000255 // FIXME: Do we incorrectly label ":" with this?
256 StartsObjCMethodExpr = false;
257 Left->Type = TT_Unknown;
258 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700259 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000260 CurrentToken->Type = TT_ObjCMethodExpr;
Nico Webere8a97982013-02-06 06:20:11 +0000261 // determineStarAmpUsage() thinks that '*' '[' is allocating an
262 // array of pointers, but if '[' starts a selector then '*' is a
263 // binary operator.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700264 if (Parent && Parent->Type == TT_PointerOrReference)
Nico Weber4ed7f3e2013-02-06 16:54:35 +0000265 Parent->Type = TT_BinaryOperator;
Daniel Jasper01786732013-02-04 07:21:18 +0000266 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000267 Left->MatchingParen = CurrentToken;
268 CurrentToken->MatchingParen = Left;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700269 if (Contexts.back().FirstObjCSelectorName) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000270 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
271 Contexts.back().LongestObjCSelectorName;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700272 if (Left->BlockParameterCount > 1)
Stephen Hines651f13c2014-04-23 16:59:28 -0700273 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
274 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000275 next();
276 return true;
277 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000278 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000279 return false;
Daniel Jasper8f54d882013-10-26 17:00:22 +0000280 if (CurrentToken->is(tok::colon))
281 ColonFound = true;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000282 if (CurrentToken->is(tok::comma) &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700283 Style.Language != FormatStyle::LK_Proto &&
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000284 (Left->Type == TT_ArraySubscriptLSquare ||
Daniel Jasper8f54d882013-10-26 17:00:22 +0000285 (Left->Type == TT_ObjCMethodExpr && !ColonFound)))
Daniel Jaspera07aa662013-10-22 15:30:28 +0000286 Left->Type = TT_ArrayInitializerLSquare;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700287 FormatToken* Tok = CurrentToken;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000288 if (!consumeToken())
289 return false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700290 updateParameterCount(Left, Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000291 }
292 return false;
293 }
294
295 bool parseBrace() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700296 if (CurrentToken) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000297 FormatToken *Left = CurrentToken->Previous;
Stephen Hines651f13c2014-04-23 16:59:28 -0700298
299 if (Contexts.back().CaretFound)
300 Left->Type = TT_ObjCBlockLBrace;
301 Contexts.back().CaretFound = false;
302
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000303 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
304 Contexts.back().ColonIsDictLiteral = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700305 if (Left->BlockKind == BK_BracedInit)
306 Contexts.back().IsExpression = true;
Nico Weberf2ff8122013-05-26 05:39:26 +0000307
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700308 while (CurrentToken) {
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000309 if (CurrentToken->is(tok::r_brace)) {
310 Left->MatchingParen = CurrentToken;
311 CurrentToken->MatchingParen = Left;
312 next();
313 return true;
314 }
315 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
316 return false;
317 updateParameterCount(Left, CurrentToken);
Stephen Hines651f13c2014-04-23 16:59:28 -0700318 if (CurrentToken->is(tok::colon) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700319 Style.Language != FormatStyle::LK_Proto) {
320 if (CurrentToken->getPreviousNonComment()->is(tok::identifier))
321 CurrentToken->getPreviousNonComment()->Type = TT_SelectorName;
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000322 Left->Type = TT_DictLiteral;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700323 }
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000324 if (!consumeToken())
325 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000326 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000327 }
328 return true;
329 }
Daniel Jasperc4615b72013-02-20 12:56:39 +0000330
Manuel Klimekb3987012013-05-29 14:47:47 +0000331 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700332 if (Current->Type == TT_LambdaLSquare ||
333 (Current->is(tok::caret) && Current->Type == TT_UnaryOperator) ||
334 (Style.Language == FormatStyle::LK_JavaScript &&
335 Current->TokenText == "function")) {
336 ++Left->BlockParameterCount;
337 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000338 if (Current->is(tok::comma)) {
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000339 ++Left->ParameterCount;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000340 if (!Left->Role)
341 Left->Role.reset(new CommaSeparatedList(Style));
342 Left->Role->CommaFound(Current);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000343 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000344 Left->ParameterCount = 1;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000345 }
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000346 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000347
348 bool parseConditional() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700349 while (CurrentToken) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000350 if (CurrentToken->is(tok::colon)) {
351 CurrentToken->Type = TT_ConditionalExpr;
352 next();
353 return true;
354 }
355 if (!consumeToken())
356 return false;
357 }
358 return false;
359 }
360
361 bool parseTemplateDeclaration() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700362 if (CurrentToken && CurrentToken->is(tok::less)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000363 CurrentToken->Type = TT_TemplateOpener;
364 next();
365 if (!parseAngle())
366 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700367 if (CurrentToken)
Manuel Klimekb3987012013-05-29 14:47:47 +0000368 CurrentToken->Previous->ClosesTemplateDeclaration = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000369 return true;
370 }
371 return false;
372 }
373
374 bool consumeToken() {
Manuel Klimekb3987012013-05-29 14:47:47 +0000375 FormatToken *Tok = CurrentToken;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000376 next();
Manuel Klimekb3987012013-05-29 14:47:47 +0000377 switch (Tok->Tok.getKind()) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000378 case tok::plus:
379 case tok::minus:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700380 if (!Tok->Previous && Line.MustBeDeclaration)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000381 Tok->Type = TT_ObjCMethodSpecifier;
382 break;
383 case tok::colon:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700384 if (!Tok->Previous)
Daniel Jaspercf6d76a2013-03-18 12:50:26 +0000385 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000386 // Colons from ?: are handled in parseConditional().
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700387 if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1 &&
388 Line.First->isNot(tok::kw_case)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000389 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000390 } else if (Contexts.back().ColonIsDictLiteral) {
391 Tok->Type = TT_DictLiteral;
Daniel Jasper4e778092013-02-06 10:05:46 +0000392 } else if (Contexts.back().ColonIsObjCMethodExpr ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000393 Line.First->Type == TT_ObjCMethodSpecifier) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000394 Tok->Type = TT_ObjCMethodExpr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700395 Tok->Previous->Type = TT_SelectorName;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000396 if (Tok->Previous->ColumnWidth >
Alexander Kornienko00895102013-06-05 14:09:10 +0000397 Contexts.back().LongestObjCSelectorName) {
Alexander Kornienko01fe9f92013-10-10 13:36:20 +0000398 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
Alexander Kornienko00895102013-06-05 14:09:10 +0000399 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700400 if (!Contexts.back().FirstObjCSelectorName)
Manuel Klimekb3987012013-05-29 14:47:47 +0000401 Contexts.back().FirstObjCSelectorName = Tok->Previous;
Daniel Jasper4e778092013-02-06 10:05:46 +0000402 } else if (Contexts.back().ColonIsForRangeExpr) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000403 Tok->Type = TT_RangeBasedForLoopColon;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700404 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
Alexander Kornienko01fe9f92013-10-10 13:36:20 +0000405 Tok->Type = TT_BitFieldColon;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700406 } else if (Contexts.size() == 1 &&
407 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
Daniel Jasper6cabab42013-02-14 08:42:54 +0000408 Tok->Type = TT_InheritanceColon;
Daniel Jasper923ebef2013-03-14 13:45:21 +0000409 } else if (Contexts.back().ContextKind == tok::l_paren) {
410 Tok->Type = TT_InlineASMColon;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000411 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000412 break;
413 case tok::kw_if:
414 case tok::kw_while:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700415 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000416 next();
Nico Weber27268772013-06-26 00:30:14 +0000417 if (!parseParens(/*LookForDecls=*/true))
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000418 return false;
419 }
420 break;
421 case tok::kw_for:
Daniel Jasper4e778092013-02-06 10:05:46 +0000422 Contexts.back().ColonIsForRangeExpr = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000423 next();
424 if (!parseParens())
425 return false;
426 break;
427 case tok::l_paren:
428 if (!parseParens())
429 return false;
Daniel Jasper59875ac2013-11-07 17:43:07 +0000430 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700431 !Contexts.back().IsExpression &&
432 Line.First->Type != TT_ObjCProperty &&
433 (!Tok->Previous || Tok->Previous->isNot(tok::kw_decltype)))
Daniel Jasper3c08a812013-02-24 18:54:32 +0000434 Line.MightBeFunctionDecl = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000435 break;
436 case tok::l_square:
437 if (!parseSquare())
438 return false;
439 break;
440 case tok::l_brace:
441 if (!parseBrace())
442 return false;
443 break;
444 case tok::less:
Daniel Jasper0236dd02013-07-30 22:37:19 +0000445 if (Tok->Previous && !Tok->Previous->Tok.isLiteral() && parseAngle())
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000446 Tok->Type = TT_TemplateOpener;
447 else {
448 Tok->Type = TT_BinaryOperator;
449 CurrentToken = Tok;
450 next();
451 }
452 break;
453 case tok::r_paren:
454 case tok::r_square:
455 return false;
456 case tok::r_brace:
457 // Lines can start with '}'.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700458 if (Tok->Previous)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000459 return false;
460 break;
461 case tok::greater:
462 Tok->Type = TT_BinaryOperator;
463 break;
464 case tok::kw_operator:
Daniel Jasper174f60f2013-09-02 09:20:39 +0000465 while (CurrentToken &&
466 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000467 if (CurrentToken->isOneOf(tok::star, tok::amp))
Daniel Jasper2b4c9242013-02-11 08:01:18 +0000468 CurrentToken->Type = TT_PointerOrReference;
469 consumeToken();
Daniel Jasper174f60f2013-09-02 09:20:39 +0000470 if (CurrentToken && CurrentToken->Previous->Type == TT_BinaryOperator)
Daniel Jasperc476ea92013-08-28 07:27:35 +0000471 CurrentToken->Previous->Type = TT_OverloadedOperator;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000472 }
Daniel Jasper6ea933c2013-05-10 07:59:58 +0000473 if (CurrentToken) {
Daniel Jasper2b4c9242013-02-11 08:01:18 +0000474 CurrentToken->Type = TT_OverloadedOperatorLParen;
Manuel Klimekb3987012013-05-29 14:47:47 +0000475 if (CurrentToken->Previous->Type == TT_BinaryOperator)
476 CurrentToken->Previous->Type = TT_OverloadedOperator;
Daniel Jasper6ea933c2013-05-10 07:59:58 +0000477 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000478 break;
479 case tok::question:
480 parseConditional();
481 break;
482 case tok::kw_template:
483 parseTemplateDeclaration();
484 break;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000485 case tok::identifier:
Manuel Klimekb3987012013-05-29 14:47:47 +0000486 if (Line.First->is(tok::kw_for) &&
487 Tok->Tok.getIdentifierInfo() == &Ident_in)
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000488 Tok->Type = TT_ObjCForIn;
489 break;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000490 case tok::comma:
491 if (Contexts.back().FirstStartOfName)
492 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000493 if (Contexts.back().InCtorInitializer)
494 Tok->Type = TT_CtorInitializerComma;
Stephen Hines651f13c2014-04-23 16:59:28 -0700495 if (Contexts.back().IsForEachMacro)
496 Contexts.back().IsExpression = true;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000497 break;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000498 default:
499 break;
500 }
501 return true;
502 }
503
504 void parseIncludeDirective() {
505 next();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700506 if (CurrentToken && CurrentToken->is(tok::less)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000507 next();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700508 while (CurrentToken) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000509 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000510 CurrentToken->Type = TT_ImplicitStringLiteral;
511 next();
512 }
513 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700514 while (CurrentToken) {
Daniel Jasper3a204412013-02-23 07:46:38 +0000515 if (CurrentToken->is(tok::string_literal))
516 // Mark these string literals as "implicit" literals, too, so that
517 // they are not split or line-wrapped.
518 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000519 next();
520 }
521 }
522 }
523
524 void parseWarningOrError() {
525 next();
526 // We still want to format the whitespace left of the first token of the
527 // warning or error.
528 next();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700529 while (CurrentToken) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000530 CurrentToken->Type = TT_ImplicitStringLiteral;
531 next();
532 }
533 }
534
Stephen Hines651f13c2014-04-23 16:59:28 -0700535 void parsePragma() {
536 next(); // Consume "pragma".
537 if (CurrentToken && CurrentToken->TokenText == "mark") {
538 next(); // Consume "mark".
539 next(); // Consume first token (so we fix leading whitespace).
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700540 while (CurrentToken) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700541 CurrentToken->Type = TT_ImplicitStringLiteral;
542 next();
543 }
544 }
545 }
546
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000547 void parsePreprocessorDirective() {
548 next();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700549 if (!CurrentToken)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000550 return;
Alexander Kornienkob18c2582013-10-11 21:43:05 +0000551 if (CurrentToken->Tok.is(tok::numeric_constant)) {
552 CurrentToken->SpacesRequiredBefore = 1;
553 return;
554 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000555 // Hashes in the middle of a line can lead to any strange token
556 // sequence.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700557 if (!CurrentToken->Tok.getIdentifierInfo())
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000558 return;
Manuel Klimekb3987012013-05-29 14:47:47 +0000559 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000560 case tok::pp_include:
561 case tok::pp_import:
562 parseIncludeDirective();
563 break;
564 case tok::pp_error:
565 case tok::pp_warning:
566 parseWarningOrError();
567 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700568 case tok::pp_pragma:
569 parsePragma();
570 break;
Daniel Jasperaae7bad2013-04-23 13:54:04 +0000571 case tok::pp_if:
572 case tok::pp_elif:
Stephen Hines651f13c2014-04-23 16:59:28 -0700573 Contexts.back().IsExpression = true;
Daniel Jasperaae7bad2013-04-23 13:54:04 +0000574 parseLine();
575 break;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000576 default:
577 break;
578 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700579 while (CurrentToken)
Daniel Jasper5b7e7b02013-02-05 09:34:14 +0000580 next();
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000581 }
582
Nico Weber95e8e462013-02-12 16:17:07 +0000583public:
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000584 LineType parseLine() {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000585 if (CurrentToken->is(tok::hash)) {
586 parsePreprocessorDirective();
587 return LT_PreprocessorDirective;
588 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700589
590 // Directly allow to 'import <string-literal>' to support protocol buffer
591 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
592 // should not break the line).
593 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
594 if (Info && Info->getPPKeywordID() == tok::pp_import &&
595 CurrentToken->Next && CurrentToken->Next->is(tok::string_literal))
596 parseIncludeDirective();
597
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700598 while (CurrentToken) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000599 if (CurrentToken->is(tok::kw_virtual))
600 KeywordVirtualFound = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000601 if (!consumeToken())
602 return LT_Invalid;
603 }
604 if (KeywordVirtualFound)
605 return LT_VirtualFunctionDecl;
606
Manuel Klimekb3987012013-05-29 14:47:47 +0000607 if (Line.First->Type == TT_ObjCMethodSpecifier) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700608 if (Contexts.back().FirstObjCSelectorName)
Daniel Jasper4e778092013-02-06 10:05:46 +0000609 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
610 Contexts.back().LongestObjCSelectorName;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000611 return LT_ObjCMethodDecl;
612 }
613
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000614 return LT_Other;
615 }
616
Nico Weber95e8e462013-02-12 16:17:07 +0000617private:
Stephen Hines651f13c2014-04-23 16:59:28 -0700618 void resetTokenMetadata(FormatToken *Token) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700619 if (!Token)
620 return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700621
622 // Reset token type in case we have already looked at it and then
623 // recovered from an error (e.g. failure to find the matching >).
624 if (CurrentToken->Type != TT_LambdaLSquare &&
625 CurrentToken->Type != TT_FunctionLBrace &&
626 CurrentToken->Type != TT_ImplicitStringLiteral &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700627 CurrentToken->Type != TT_RegexLiteral &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700628 CurrentToken->Type != TT_TrailingReturnArrow)
629 CurrentToken->Type = TT_Unknown;
630 if (CurrentToken->Role)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700631 CurrentToken->Role.reset(nullptr);
Stephen Hines651f13c2014-04-23 16:59:28 -0700632 CurrentToken->FakeLParens.clear();
633 CurrentToken->FakeRParens = 0;
634 }
635
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000636 void next() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700637 if (CurrentToken) {
Daniel Jasper01786732013-02-04 07:21:18 +0000638 determineTokenType(*CurrentToken);
Daniel Jasper4e778092013-02-06 10:05:46 +0000639 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
Stephen Hines651f13c2014-04-23 16:59:28 -0700640 CurrentToken->NestingLevel = Contexts.size() - 1;
Manuel Klimekb3987012013-05-29 14:47:47 +0000641 CurrentToken = CurrentToken->Next;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700642 }
Daniel Jasperd0f349b2013-02-18 12:44:35 +0000643
Stephen Hines651f13c2014-04-23 16:59:28 -0700644 resetTokenMetadata(CurrentToken);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000645 }
646
Daniel Jasper4e778092013-02-06 10:05:46 +0000647 /// \brief A struct to hold information valid in a specific context, e.g.
648 /// a pair of parenthesis.
649 struct Context {
Daniel Jasper923ebef2013-03-14 13:45:21 +0000650 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
651 bool IsExpression)
652 : ContextKind(ContextKind), BindingStrength(BindingStrength),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700653 LongestObjCSelectorName(0), ColonIsForRangeExpr(false),
654 ColonIsDictLiteral(false), ColonIsObjCMethodExpr(false),
655 FirstObjCSelectorName(nullptr), FirstStartOfName(nullptr),
656 IsExpression(IsExpression), CanBeExpression(true),
657 InTemplateArgument(false), InCtorInitializer(false),
658 CaretFound(false), IsForEachMacro(false) {}
Daniel Jasper01786732013-02-04 07:21:18 +0000659
Daniel Jasper923ebef2013-03-14 13:45:21 +0000660 tok::TokenKind ContextKind;
Daniel Jasper4e778092013-02-06 10:05:46 +0000661 unsigned BindingStrength;
662 unsigned LongestObjCSelectorName;
663 bool ColonIsForRangeExpr;
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000664 bool ColonIsDictLiteral;
Daniel Jasper4e778092013-02-06 10:05:46 +0000665 bool ColonIsObjCMethodExpr;
Manuel Klimekb3987012013-05-29 14:47:47 +0000666 FormatToken *FirstObjCSelectorName;
667 FormatToken *FirstStartOfName;
Daniel Jasper4e778092013-02-06 10:05:46 +0000668 bool IsExpression;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000669 bool CanBeExpression;
Stephen Hines651f13c2014-04-23 16:59:28 -0700670 bool InTemplateArgument;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000671 bool InCtorInitializer;
Stephen Hines651f13c2014-04-23 16:59:28 -0700672 bool CaretFound;
673 bool IsForEachMacro;
Daniel Jasper4e778092013-02-06 10:05:46 +0000674 };
675
676 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
677 /// of each instance.
678 struct ScopedContextCreator {
679 AnnotatingParser &P;
680
Daniel Jasper923ebef2013-03-14 13:45:21 +0000681 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
682 unsigned Increase)
683 : P(P) {
Daniel Jasper2a409b62013-07-08 14:34:09 +0000684 P.Contexts.push_back(Context(ContextKind,
685 P.Contexts.back().BindingStrength + Increase,
686 P.Contexts.back().IsExpression));
Daniel Jasper4e778092013-02-06 10:05:46 +0000687 }
688
689 ~ScopedContextCreator() { P.Contexts.pop_back(); }
690 };
Daniel Jasper01786732013-02-04 07:21:18 +0000691
Manuel Klimekb3987012013-05-29 14:47:47 +0000692 void determineTokenType(FormatToken &Current) {
693 if (Current.getPrecedence() == prec::Assignment &&
Daniel Jasper53352602013-08-12 12:16:34 +0000694 !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000695 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000696 Contexts.back().IsExpression = true;
Manuel Klimekb3987012013-05-29 14:47:47 +0000697 for (FormatToken *Previous = Current.Previous;
Daniel Jasper7e274002013-09-11 20:37:10 +0000698 Previous && !Previous->isOneOf(tok::comma, tok::semi);
Manuel Klimekb3987012013-05-29 14:47:47 +0000699 Previous = Previous->Previous) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700700 if (Previous->isOneOf(tok::r_square, tok::r_paren))
Daniel Jasper9c65b062013-02-27 11:43:50 +0000701 Previous = Previous->MatchingParen;
Daniel Jasper01786732013-02-04 07:21:18 +0000702 if (Previous->Type == TT_BinaryOperator &&
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000703 Previous->isOneOf(tok::star, tok::amp)) {
Daniel Jasper01786732013-02-04 07:21:18 +0000704 Previous->Type = TT_PointerOrReference;
705 }
Daniel Jasper01786732013-02-04 07:21:18 +0000706 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700707 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000708 Contexts.back().IsExpression = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700709 } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700710 !Line.InPPDirective &&
711 (!Current.Previous ||
712 Current.Previous->isNot(tok::kw_decltype))) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700713 bool ParametersOfFunctionType =
714 Current.Previous && Current.Previous->is(tok::r_paren) &&
715 Current.Previous->MatchingParen &&
716 Current.Previous->MatchingParen->Type == TT_FunctionTypeLParen;
717 bool IsForOrCatch = Current.Previous &&
718 Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
719 Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000720 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000721 for (FormatToken *Previous = Current.Previous;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000722 Previous && Previous->isOneOf(tok::star, tok::amp);
Manuel Klimekb3987012013-05-29 14:47:47 +0000723 Previous = Previous->Previous)
Nico Weber95e8e462013-02-12 16:17:07 +0000724 Previous->Type = TT_PointerOrReference;
Manuel Klimekb3987012013-05-29 14:47:47 +0000725 } else if (Current.Previous &&
726 Current.Previous->Type == TT_CtorInitializerColon) {
Daniel Jasperd0f349b2013-02-18 12:44:35 +0000727 Contexts.back().IsExpression = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000728 Contexts.back().InCtorInitializer = true;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000729 } else if (Current.is(tok::kw_new)) {
730 Contexts.back().CanBeExpression = false;
Daniel Jasperf9504aa2013-11-07 19:56:07 +0000731 } else if (Current.is(tok::semi) || Current.is(tok::exclaim)) {
Daniel Jasper16a69ef2013-05-03 14:41:24 +0000732 // This should be the condition or increment in a for-loop.
733 Contexts.back().IsExpression = true;
Nico Weber95e8e462013-02-12 16:17:07 +0000734 }
Daniel Jasper01786732013-02-04 07:21:18 +0000735
736 if (Current.Type == TT_Unknown) {
Daniel Jasper6b3ff8c2013-09-27 08:29:16 +0000737 // Line.MightBeFunctionDecl can only be true after the parentheses of a
738 // function declaration have been found. In this case, 'Current' is a
739 // trailing token of this declaration and thus cannot be a name.
740 if (isStartOfName(Current) && !Line.MightBeFunctionDecl) {
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000741 Contexts.back().FirstStartOfName = &Current;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000742 Current.Type = TT_StartOfName;
Daniel Jasper2ca37412013-07-09 14:36:48 +0000743 } else if (Current.is(tok::kw_auto)) {
744 AutoFound = true;
Daniel Jasper3262f4c2013-07-11 14:33:06 +0000745 } else if (Current.is(tok::arrow) && AutoFound &&
746 Line.MustBeDeclaration) {
Daniel Jasper2ca37412013-07-09 14:36:48 +0000747 Current.Type = TT_TrailingReturnArrow;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000748 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000749 Current.Type =
Daniel Jasperd6104f62013-07-05 13:30:40 +0000750 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700751 Contexts.back().IsExpression,
752 Contexts.back().InTemplateArgument);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000753 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
Daniel Jasper01786732013-02-04 07:21:18 +0000754 Current.Type = determinePlusMinusCaretUsage(Current);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700755 if (Current.Type == TT_UnaryOperator && Current.is(tok::caret))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700756 Contexts.back().CaretFound = true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000757 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
Daniel Jasper01786732013-02-04 07:21:18 +0000758 Current.Type = determineIncrementUsage(Current);
759 } else if (Current.is(tok::exclaim)) {
760 Current.Type = TT_UnaryOperator;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700761 } else if (Current.is(tok::question)) {
762 Current.Type = TT_ConditionalExpr;
Manuel Klimek31e44f72013-09-04 08:20:47 +0000763 } else if (Current.isBinaryOperator() &&
764 (!Current.Previous ||
765 Current.Previous->isNot(tok::l_square))) {
Daniel Jasper01786732013-02-04 07:21:18 +0000766 Current.Type = TT_BinaryOperator;
767 } else if (Current.is(tok::comment)) {
Alexander Kornienko00895102013-06-05 14:09:10 +0000768 if (Current.TokenText.startswith("//"))
Daniel Jasper01786732013-02-04 07:21:18 +0000769 Current.Type = TT_LineComment;
770 else
771 Current.Type = TT_BlockComment;
Nico Weber37d69312013-02-13 04:13:13 +0000772 } else if (Current.is(tok::r_paren)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700773 if (rParenEndsCast(Current))
Nico Weber37d69312013-02-13 04:13:13 +0000774 Current.Type = TT_CastRParen;
Manuel Klimekb3987012013-05-29 14:47:47 +0000775 } else if (Current.is(tok::at) && Current.Next) {
776 switch (Current.Next->Tok.getObjCKeywordID()) {
Daniel Jasper01786732013-02-04 07:21:18 +0000777 case tok::objc_interface:
778 case tok::objc_implementation:
779 case tok::objc_protocol:
780 Current.Type = TT_ObjCDecl;
781 break;
782 case tok::objc_property:
783 Current.Type = TT_ObjCProperty;
784 break;
785 default:
786 break;
787 }
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000788 } else if (Current.is(tok::period)) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000789 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000790 if (PreviousNoComment &&
791 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
792 Current.Type = TT_DesignatedInitializerPeriod;
Stephen Hines651f13c2014-04-23 16:59:28 -0700793 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700794 Current.Previous && Current.Previous->isNot(tok::equal) &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700795 Line.MightBeFunctionDecl && Contexts.size() == 1) {
796 // Line.MightBeFunctionDecl can only be true after the parentheses of a
797 // function declaration have been found.
798 Current.Type = TT_TrailingAnnotation;
Daniel Jasper01786732013-02-04 07:21:18 +0000799 }
800 }
801 }
802
Daniel Jasper6ac431c2013-07-02 09:47:29 +0000803 /// \brief Take a guess at whether \p Tok starts a name of a function or
804 /// variable declaration.
805 ///
806 /// This is a heuristic based on whether \p Tok is an identifier following
807 /// something that is likely a type.
808 bool isStartOfName(const FormatToken &Tok) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700809 if (Tok.isNot(tok::identifier) || !Tok.Previous)
Daniel Jasper6ac431c2013-07-02 09:47:29 +0000810 return false;
811
812 // Skip "const" as it does not have an influence on whether this is a name.
813 FormatToken *PreviousNotConst = Tok.Previous;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700814 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
Daniel Jasper6ac431c2013-07-02 09:47:29 +0000815 PreviousNotConst = PreviousNotConst->Previous;
816
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700817 if (!PreviousNotConst)
Daniel Jasper6ac431c2013-07-02 09:47:29 +0000818 return false;
819
Daniel Jasper2a409b62013-07-08 14:34:09 +0000820 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
821 PreviousNotConst->Previous &&
822 PreviousNotConst->Previous->is(tok::hash);
Daniel Jasper6ac431c2013-07-02 09:47:29 +0000823
Daniel Jasper92495a82013-08-19 10:16:18 +0000824 if (PreviousNotConst->Type == TT_TemplateCloser)
825 return PreviousNotConst && PreviousNotConst->MatchingParen &&
826 PreviousNotConst->MatchingParen->Previous &&
827 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
828
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700829 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
830 PreviousNotConst->MatchingParen->Previous &&
831 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
832 return true;
833
Daniel Jasper6ac431c2013-07-02 09:47:29 +0000834 return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
835 PreviousNotConst->Type == TT_PointerOrReference ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700836 PreviousNotConst->isSimpleTypeSpecifier();
Daniel Jasper6ac431c2013-07-02 09:47:29 +0000837 }
838
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700839 /// \brief Determine whether ')' is ending a cast.
840 bool rParenEndsCast(const FormatToken &Tok) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700841 FormatToken *LeftOfParens = nullptr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700842 if (Tok.MatchingParen)
843 LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
844 bool IsCast = false;
845 bool ParensAreEmpty = Tok.Previous == Tok.MatchingParen;
846 bool ParensAreType = !Tok.Previous ||
847 Tok.Previous->Type == TT_PointerOrReference ||
848 Tok.Previous->Type == TT_TemplateCloser ||
849 Tok.Previous->isSimpleTypeSpecifier();
850 bool ParensCouldEndDecl =
851 Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
852 bool IsSizeOfOrAlignOf =
853 LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
854 if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
855 ((Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression) ||
856 (Tok.Next && Tok.Next->isBinaryOperator())))
857 IsCast = true;
858 else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
859 (Tok.Next->Tok.isLiteral() ||
860 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
861 IsCast = true;
862 // If there is an identifier after the (), it is likely a cast, unless
863 // there is also an identifier before the ().
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700864 else if (LeftOfParens &&
865 (LeftOfParens->Tok.getIdentifierInfo() == nullptr ||
866 LeftOfParens->is(tok::kw_return)) &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700867 LeftOfParens->Type != TT_OverloadedOperator &&
868 LeftOfParens->isNot(tok::at) &&
869 LeftOfParens->Type != TT_TemplateCloser && Tok.Next) {
870 if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
871 IsCast = true;
872 } else {
873 // Use heuristics to recognize c style casting.
874 FormatToken *Prev = Tok.Previous;
875 if (Prev && Prev->isOneOf(tok::amp, tok::star))
876 Prev = Prev->Previous;
877
878 if (Prev && Tok.Next && Tok.Next->Next) {
879 bool NextIsUnary = Tok.Next->isUnaryOperator() ||
880 Tok.Next->isOneOf(tok::amp, tok::star);
881 IsCast = NextIsUnary && Tok.Next->Next->isOneOf(
882 tok::identifier, tok::numeric_constant);
883 }
884
885 for (; Prev != Tok.MatchingParen; Prev = Prev->Previous) {
886 if (!Prev || !Prev->isOneOf(tok::kw_const, tok::identifier)) {
887 IsCast = false;
888 break;
889 }
890 }
891 }
892 }
893 return IsCast && !ParensAreEmpty;
894 }
895
Daniel Jasper01786732013-02-04 07:21:18 +0000896 /// \brief Return the type of the given token assuming it is * or &.
Stephen Hines651f13c2014-04-23 16:59:28 -0700897 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
898 bool InTemplateArgument) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000899 const FormatToken *PrevToken = Tok.getPreviousNonComment();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700900 if (!PrevToken)
Daniel Jasper01786732013-02-04 07:21:18 +0000901 return TT_UnaryOperator;
902
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000903 const FormatToken *NextToken = Tok.getNextNonComment();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700904 if (!NextToken || NextToken->is(tok::l_brace))
Daniel Jasper01786732013-02-04 07:21:18 +0000905 return TT_Unknown;
906
Daniel Jasper431f5912013-05-28 08:33:00 +0000907 if (PrevToken->is(tok::coloncolon) ||
908 (PrevToken->is(tok::l_paren) && !IsExpression))
Daniel Jasper8a5d7cd2013-03-01 17:13:29 +0000909 return TT_PointerOrReference;
910
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000911 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
Daniel Jasperd3cf17b2013-03-14 10:50:25 +0000912 tok::comma, tok::semi, tok::kw_return, tok::colon,
Daniel Jasper65da8e92013-09-21 17:31:51 +0000913 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000914 PrevToken->Type == TT_BinaryOperator ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700915 PrevToken->Type == TT_ConditionalExpr ||
Daniel Jasper01786732013-02-04 07:21:18 +0000916 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
917 return TT_UnaryOperator;
918
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700919 if (NextToken->is(tok::l_square) && NextToken->Type != TT_LambdaLSquare)
Nico Webere8a97982013-02-06 06:20:11 +0000920 return TT_PointerOrReference;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700921 if (NextToken->is(tok::kw_operator))
922 return TT_PointerOrReference;
Nico Webere8a97982013-02-06 06:20:11 +0000923
Daniel Jasperdb8afe42013-09-10 10:26:38 +0000924 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
925 PrevToken->MatchingParen->Previous &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700926 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
927 tok::kw_decltype))
Daniel Jasperdb8afe42013-09-10 10:26:38 +0000928 return TT_PointerOrReference;
929
Manuel Klimekb3987012013-05-29 14:47:47 +0000930 if (PrevToken->Tok.isLiteral() ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700931 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
932 tok::kw_false) ||
933 NextToken->Tok.isLiteral() ||
934 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
935 NextToken->isUnaryOperator() ||
936 // If we know we're in a template argument, there are no named
937 // declarations. Thus, having an identifier on the right-hand side
938 // indicates a binary operator.
939 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
Daniel Jasper01786732013-02-04 07:21:18 +0000940 return TT_BinaryOperator;
941
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700942 // This catches some cases where evaluation order is used as control flow:
943 // aaa && aaa->f();
944 const FormatToken *NextNextToken = NextToken->getNextNonComment();
945 if (NextNextToken && NextNextToken->is(tok::arrow))
946 return TT_BinaryOperator;
947
Daniel Jasper01786732013-02-04 07:21:18 +0000948 // It is very unlikely that we are going to find a pointer or reference type
949 // definition on the RHS of an assignment.
950 if (IsExpression)
951 return TT_BinaryOperator;
952
953 return TT_PointerOrReference;
954 }
955
Manuel Klimekb3987012013-05-29 14:47:47 +0000956 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000957 const FormatToken *PrevToken = Tok.getPreviousNonComment();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700958 if (!PrevToken || PrevToken->Type == TT_CastRParen)
Daniel Jasper01786732013-02-04 07:21:18 +0000959 return TT_UnaryOperator;
960
961 // Use heuristics to recognize unary operators.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000962 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
963 tok::question, tok::colon, tok::kw_return,
964 tok::kw_case, tok::at, tok::l_brace))
Daniel Jasper01786732013-02-04 07:21:18 +0000965 return TT_UnaryOperator;
966
Nico Weberee0feec2013-02-05 16:21:00 +0000967 // There can't be two consecutive binary operators.
Daniel Jasper01786732013-02-04 07:21:18 +0000968 if (PrevToken->Type == TT_BinaryOperator)
969 return TT_UnaryOperator;
970
971 // Fall back to marking the token as binary operator.
972 return TT_BinaryOperator;
973 }
974
975 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Manuel Klimekb3987012013-05-29 14:47:47 +0000976 TokenType determineIncrementUsage(const FormatToken &Tok) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000977 const FormatToken *PrevToken = Tok.getPreviousNonComment();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700978 if (!PrevToken || PrevToken->Type == TT_CastRParen)
Daniel Jasper01786732013-02-04 07:21:18 +0000979 return TT_UnaryOperator;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000980 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
Daniel Jasper01786732013-02-04 07:21:18 +0000981 return TT_TrailingUnaryOperator;
982
983 return TT_UnaryOperator;
984 }
Daniel Jasper4e778092013-02-06 10:05:46 +0000985
986 SmallVector<Context, 8> Contexts;
987
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000988 const FormatStyle &Style;
Daniel Jasper4e778092013-02-06 10:05:46 +0000989 AnnotatedLine &Line;
Manuel Klimekb3987012013-05-29 14:47:47 +0000990 FormatToken *CurrentToken;
Daniel Jasper4e778092013-02-06 10:05:46 +0000991 bool KeywordVirtualFound;
Daniel Jasper2ca37412013-07-09 14:36:48 +0000992 bool AutoFound;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000993 IdentifierInfo &Ident_in;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000994};
995
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000996static int PrecedenceUnaryOperator = prec::PointerToMember + 1;
997static int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
998
Daniel Jasper29f123b2013-02-08 15:28:42 +0000999/// \brief Parses binary expressions by inserting fake parenthesis based on
1000/// operator precedence.
1001class ExpressionParser {
1002public:
Daniel Jasper9acb8b42013-06-06 09:11:58 +00001003 ExpressionParser(AnnotatedLine &Line) : Current(Line.First) {
1004 // Skip leading "}", e.g. in "} else if (...) {".
1005 if (Current->is(tok::r_brace))
1006 next();
1007 }
Daniel Jasper29f123b2013-02-08 15:28:42 +00001008
1009 /// \brief Parse expressions with the given operatore precedence.
Daniel Jasper237d4c12013-02-23 21:01:55 +00001010 void parse(int Precedence = 0) {
Daniel Jasper966e6d32013-11-07 19:23:49 +00001011 // Skip 'return' and ObjC selector colons as they are not part of a binary
1012 // expression.
1013 while (Current &&
1014 (Current->is(tok::kw_return) ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001015 (Current->is(tok::colon) && (Current->Type == TT_ObjCMethodExpr ||
1016 Current->Type == TT_DictLiteral))))
Daniel Jasperf78bf4a2013-09-30 08:29:03 +00001017 next();
1018
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001019 if (!Current || Precedence > PrecedenceArrowAndPeriod)
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001020 return;
1021
Daniel Jasperc01897c2013-05-31 14:56:12 +00001022 // Conditional expressions need to be parsed separately for proper nesting.
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001023 if (Precedence == prec::Conditional) {
Daniel Jasperc01897c2013-05-31 14:56:12 +00001024 parseConditionalExpr();
1025 return;
1026 }
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001027
1028 // Parse unary operators, which all have a higher precedence than binary
1029 // operators.
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001030 if (Precedence == PrecedenceUnaryOperator) {
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001031 parseUnaryOperator();
Daniel Jasper29f123b2013-02-08 15:28:42 +00001032 return;
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001033 }
Daniel Jasper29f123b2013-02-08 15:28:42 +00001034
Manuel Klimekb3987012013-05-29 14:47:47 +00001035 FormatToken *Start = Current;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001036 FormatToken *LatestOperator = nullptr;
1037 unsigned OperatorIndex = 0;
Daniel Jasper29f123b2013-02-08 15:28:42 +00001038
Daniel Jasper237d4c12013-02-23 21:01:55 +00001039 while (Current) {
Daniel Jasper29f123b2013-02-08 15:28:42 +00001040 // Consume operators with higher precedence.
Daniel Jasperbf71ba22013-04-08 20:33:42 +00001041 parse(Precedence + 1);
Daniel Jasper29f123b2013-02-08 15:28:42 +00001042
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001043 int CurrentPrecedence = getCurrentPrecedence();
1044
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001045 if (Current && Current->Type == TT_SelectorName &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001046 Precedence == CurrentPrecedence) {
1047 if (LatestOperator)
1048 addFakeParenthesis(Start, prec::Level(Precedence));
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001049 Start = Current;
Stephen Hines651f13c2014-04-23 16:59:28 -07001050 }
Daniel Jasper237d4c12013-02-23 21:01:55 +00001051
Daniel Jasper29f123b2013-02-08 15:28:42 +00001052 // At the end of the line or when an operator with higher precedence is
1053 // found, insert fake parenthesis and return.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001054 if (!Current || Current->closesScope() ||
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001055 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence)) {
1056 if (LatestOperator) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001057 LatestOperator->LastOperator = true;
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001058 if (Precedence == PrecedenceArrowAndPeriod) {
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001059 // Call expressions don't have a binary operator precedence.
1060 addFakeParenthesis(Start, prec::Unknown);
1061 } else {
1062 addFakeParenthesis(Start, prec::Level(Precedence));
1063 }
1064 }
Daniel Jasper29f123b2013-02-08 15:28:42 +00001065 return;
1066 }
1067
1068 // Consume scopes: (), [], <> and {}
Daniel Jasperac3223e2013-04-10 09:49:49 +00001069 if (Current->opensScope()) {
1070 while (Current && !Current->closesScope()) {
Daniel Jasper29f123b2013-02-08 15:28:42 +00001071 next();
1072 parse();
1073 }
1074 next();
1075 } else {
1076 // Operator found.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001077 if (CurrentPrecedence == Precedence) {
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001078 LatestOperator = Current;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001079 Current->OperatorIndex = OperatorIndex;
1080 ++OperatorIndex;
1081 }
Daniel Jasper29f123b2013-02-08 15:28:42 +00001082
1083 next();
1084 }
1085 }
1086 }
1087
1088private:
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001089 /// \brief Gets the precedence (+1) of the given token for binary operators
1090 /// and other tokens that we treat like binary operators.
1091 int getCurrentPrecedence() {
1092 if (Current) {
1093 if (Current->Type == TT_ConditionalExpr)
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001094 return prec::Conditional;
Daniel Jasper966e6d32013-11-07 19:23:49 +00001095 else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001096 Current->Type == TT_SelectorName)
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001097 return 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07001098 else if (Current->Type == TT_RangeBasedForLoopColon)
1099 return prec::Comma;
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001100 else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001101 return Current->getPrecedence();
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001102 else if (Current->isOneOf(tok::period, tok::arrow))
1103 return PrecedenceArrowAndPeriod;
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001104 }
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001105 return -1;
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001106 }
1107
Daniel Jasperc01897c2013-05-31 14:56:12 +00001108 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1109 Start->FakeLParens.push_back(Precedence);
Daniel Jasperdb4813a2013-09-06 08:08:14 +00001110 if (Precedence > prec::Unknown)
1111 Start->StartsBinaryExpression = true;
1112 if (Current) {
Daniel Jasperc01897c2013-05-31 14:56:12 +00001113 ++Current->Previous->FakeRParens;
Daniel Jasperdb4813a2013-09-06 08:08:14 +00001114 if (Precedence > prec::Unknown)
1115 Current->Previous->EndsBinaryExpression = true;
1116 }
Daniel Jasperc01897c2013-05-31 14:56:12 +00001117 }
1118
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001119 /// \brief Parse unary operator expressions and surround them with fake
1120 /// parentheses if appropriate.
1121 void parseUnaryOperator() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001122 if (!Current || Current->Type != TT_UnaryOperator) {
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001123 parse(PrecedenceArrowAndPeriod);
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001124 return;
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001125 }
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001126
1127 FormatToken *Start = Current;
1128 next();
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001129 parseUnaryOperator();
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001130
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001131 // The actual precedence doesn't matter.
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001132 addFakeParenthesis(Start, prec::Unknown);
Daniel Jasper3618e6f2013-08-23 15:14:03 +00001133 }
1134
Daniel Jasperc01897c2013-05-31 14:56:12 +00001135 void parseConditionalExpr() {
1136 FormatToken *Start = Current;
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001137 parse(prec::LogicalOr);
Daniel Jasperc01897c2013-05-31 14:56:12 +00001138 if (!Current || !Current->is(tok::question))
1139 return;
1140 next();
Daniel Jasperd489f8c2013-08-27 11:09:05 +00001141 parse(prec::LogicalOr);
Daniel Jasperc01897c2013-05-31 14:56:12 +00001142 if (!Current || Current->Type != TT_ConditionalExpr)
1143 return;
1144 next();
1145 parseConditionalExpr();
1146 addFakeParenthesis(Start, prec::Conditional);
1147 }
1148
Daniel Jasper29f123b2013-02-08 15:28:42 +00001149 void next() {
Alexander Kornienkod71b15b2013-06-17 13:19:53 +00001150 if (Current)
1151 Current = Current->Next;
1152 while (Current && Current->isTrailingComment())
Manuel Klimekb3987012013-05-29 14:47:47 +00001153 Current = Current->Next;
Daniel Jasper29f123b2013-02-08 15:28:42 +00001154 }
1155
Manuel Klimekb3987012013-05-29 14:47:47 +00001156 FormatToken *Current;
Daniel Jasper29f123b2013-02-08 15:28:42 +00001157};
1158
Craig Topper14e66492013-07-01 04:03:19 +00001159} // end anonymous namespace
1160
Daniel Jasperb77d7412013-09-06 07:54:20 +00001161void
1162TokenAnnotator::setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001163 const AnnotatedLine *NextNonCommentLine = nullptr;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001164 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1165 E = Lines.rend();
1166 I != E; ++I) {
1167 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001168 (*I)->First->Next == nullptr)
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001169 (*I)->Level = NextNonCommentLine->Level;
Daniel Jasperb77d7412013-09-06 07:54:20 +00001170 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001171 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001172
1173 setCommentLineLevels((*I)->Children);
Daniel Jasperb77d7412013-09-06 07:54:20 +00001174 }
1175}
1176
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001177void TokenAnnotator::annotate(AnnotatedLine &Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +00001178 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1179 E = Line.Children.end();
Daniel Jasper567dcf92013-09-05 09:29:45 +00001180 I != E; ++I) {
1181 annotate(**I);
1182 }
Daniel Jasperd4a03db2013-08-22 15:00:41 +00001183 AnnotatingParser Parser(Style, Line, Ident_in);
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001184 Line.Type = Parser.parseLine();
1185 if (Line.Type == LT_Invalid)
1186 return;
1187
Daniel Jasper29f123b2013-02-08 15:28:42 +00001188 ExpressionParser ExprParser(Line);
1189 ExprParser.parse();
1190
Manuel Klimekb3987012013-05-29 14:47:47 +00001191 if (Line.First->Type == TT_ObjCMethodSpecifier)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001192 Line.Type = LT_ObjCMethodDecl;
Manuel Klimekb3987012013-05-29 14:47:47 +00001193 else if (Line.First->Type == TT_ObjCDecl)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001194 Line.Type = LT_ObjCDecl;
Manuel Klimekb3987012013-05-29 14:47:47 +00001195 else if (Line.First->Type == TT_ObjCProperty)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001196 Line.Type = LT_ObjCProperty;
1197
Manuel Klimekb3987012013-05-29 14:47:47 +00001198 Line.First->SpacesRequiredBefore = 1;
1199 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001200}
1201
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001202// This function heuristically determines whether 'Current' starts the name of a
1203// function declaration.
1204static bool isFunctionDeclarationName(const FormatToken &Current) {
1205 if (Current.Type != TT_StartOfName ||
1206 Current.NestingLevel != 0 ||
1207 Current.Previous->Type == TT_StartOfName)
1208 return false;
1209 const FormatToken *Next = Current.Next;
1210 for (; Next; Next = Next->Next) {
1211 if (Next->Type == TT_TemplateOpener) {
1212 Next = Next->MatchingParen;
1213 } else if (Next->is(tok::coloncolon)) {
1214 Next = Next->Next;
1215 if (!Next || !Next->is(tok::identifier))
1216 return false;
1217 } else if (Next->is(tok::l_paren)) {
1218 break;
1219 } else {
1220 return false;
1221 }
1222 }
1223 if (!Next)
1224 return false;
1225 assert(Next->is(tok::l_paren));
1226 if (Next->Next == Next->MatchingParen)
1227 return true;
1228 for (const FormatToken *Tok = Next->Next; Tok != Next->MatchingParen;
1229 Tok = Tok->Next) {
1230 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1231 Tok->Type == TT_PointerOrReference || Tok->Type == TT_StartOfName)
1232 return true;
1233 if (Tok->isOneOf(tok::l_brace, tok::string_literal) || Tok->Tok.isLiteral())
1234 return false;
1235 }
1236 return false;
1237}
1238
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001239void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001240 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1241 E = Line.Children.end();
1242 I != E; ++I) {
1243 calculateFormattingInformation(**I);
1244 }
1245
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001246 Line.First->TotalLength =
1247 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
Manuel Klimekb3987012013-05-29 14:47:47 +00001248 if (!Line.First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001249 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001250 FormatToken *Current = Line.First->Next;
Daniel Jasperdbfb5f32013-11-07 17:52:51 +00001251 bool InFunctionDecl = Line.MightBeFunctionDecl;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001252 while (Current) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001253 if (isFunctionDeclarationName(*Current))
1254 Current->Type = TT_FunctionDeclarationName;
Stephen Hines651f13c2014-04-23 16:59:28 -07001255 if (Current->Type == TT_LineComment) {
1256 if (Current->Previous->BlockKind == BK_BracedInit &&
1257 Current->Previous->opensScope())
1258 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1259 else
1260 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1261
1262 // If we find a trailing comment, iterate backwards to determine whether
1263 // it seems to relate to a specific parameter. If so, break before that
1264 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1265 // to the previous line in:
1266 // SomeFunction(a,
1267 // b, // comment
1268 // c);
1269 if (!Current->HasUnescapedNewline) {
1270 for (FormatToken *Parameter = Current->Previous; Parameter;
1271 Parameter = Parameter->Previous) {
1272 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1273 break;
1274 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1275 if (Parameter->Previous->Type != TT_CtorInitializerComma &&
1276 Parameter->HasUnescapedNewline)
1277 Parameter->MustBreakBefore = true;
1278 break;
1279 }
1280 }
1281 }
1282 } else if (Current->SpacesRequiredBefore == 0 &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001283 spaceRequiredBefore(Line, *Current)) {
Alexander Kornienkob18c2582013-10-11 21:43:05 +00001284 Current->SpacesRequiredBefore = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07001285 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001286
Daniel Jasperebaa1712013-09-17 09:52:48 +00001287 Current->MustBreakBefore =
1288 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1289
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001290 Current->CanBreakBefore =
1291 Current->MustBreakBefore || canBreakBefore(Line, *Current);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001292 unsigned ChildSize = 0;
1293 if (Current->Previous->Children.size() == 1) {
1294 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1295 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1296 : LastOfChild.TotalLength + 1;
1297 }
1298 if (Current->MustBreakBefore || Current->Previous->Children.size() > 1 ||
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001299 Current->IsMultiline)
Manuel Klimekb3987012013-05-29 14:47:47 +00001300 Current->TotalLength = Current->Previous->TotalLength + Style.ColumnLimit;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001301 else
Daniel Jasper2a409b62013-07-08 14:34:09 +00001302 Current->TotalLength = Current->Previous->TotalLength +
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001303 Current->ColumnWidth + ChildSize +
Daniel Jasper2a409b62013-07-08 14:34:09 +00001304 Current->SpacesRequiredBefore;
Daniel Jasperdbfb5f32013-11-07 17:52:51 +00001305
1306 if (Current->Type == TT_CtorInitializerColon)
1307 InFunctionDecl = false;
1308
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001309 // FIXME: Only calculate this if CanBreakBefore is true once static
1310 // initializers etc. are sorted out.
1311 // FIXME: Move magic numbers to a better place.
Daniel Jasperdbfb5f32013-11-07 17:52:51 +00001312 Current->SplitPenalty = 20 * Current->BindingStrength +
1313 splitPenalty(Line, *Current, InFunctionDecl);
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001314
Manuel Klimekb3987012013-05-29 14:47:47 +00001315 Current = Current->Next;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001316 }
Daniel Jasperbf71ba22013-04-08 20:33:42 +00001317
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001318 calculateUnbreakableTailLengths(Line);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001319 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +00001320 if (Current->Role)
1321 Current->Role->precomputeFormattingInfos(Current);
1322 }
1323
Daniel Jasper567dcf92013-09-05 09:29:45 +00001324 DEBUG({ printDebugInfo(Line); });
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001325}
1326
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001327void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1328 unsigned UnbreakableTailLength = 0;
Manuel Klimekb3987012013-05-29 14:47:47 +00001329 FormatToken *Current = Line.Last;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001330 while (Current) {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001331 Current->UnbreakableTailLength = UnbreakableTailLength;
1332 if (Current->CanBreakBefore ||
1333 Current->isOneOf(tok::comment, tok::string_literal)) {
1334 UnbreakableTailLength = 0;
1335 } else {
1336 UnbreakableTailLength +=
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001337 Current->ColumnWidth + Current->SpacesRequiredBefore;
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001338 }
Manuel Klimekb3987012013-05-29 14:47:47 +00001339 Current = Current->Previous;
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001340 }
1341}
1342
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001343unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
Daniel Jasperdbfb5f32013-11-07 17:52:51 +00001344 const FormatToken &Tok,
1345 bool InFunctionDecl) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001346 const FormatToken &Left = *Tok.Previous;
1347 const FormatToken &Right = Tok;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001348
Daniel Jasper5ad390d2013-05-28 11:30:49 +00001349 if (Left.is(tok::semi))
1350 return 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001351 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1352 Right.Next->Type == TT_DictLiteral))
Daniel Jasper5ad390d2013-05-28 11:30:49 +00001353 return 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07001354 if (Right.is(tok::l_square)) {
1355 if (Style.Language == FormatStyle::LK_Proto)
1356 return 1;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001357 if (Right.Type != TT_ObjCMethodExpr && Right.Type != TT_LambdaLSquare)
1358 return 500;
Stephen Hines651f13c2014-04-23 16:59:28 -07001359 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001360 if (Right.Type == TT_StartOfName ||
1361 Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator)) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001362 if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
Daniel Jasper3c08a812013-02-24 18:54:32 +00001363 return 3;
Daniel Jasperc18cff32013-07-11 12:34:23 +00001364 if (Left.Type == TT_StartOfName)
1365 return 20;
Stephen Hines651f13c2014-04-23 16:59:28 -07001366 if (InFunctionDecl && Right.NestingLevel == 0)
Daniel Jasper3c08a812013-02-24 18:54:32 +00001367 return Style.PenaltyReturnTypeOnItsOwnLine;
Daniel Jasper92495a82013-08-19 10:16:18 +00001368 return 200;
Daniel Jasper3c08a812013-02-24 18:54:32 +00001369 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001370 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1371 return 150;
Daniel Jasper198c8bf2013-07-05 07:58:34 +00001372 if (Left.Type == TT_CastRParen)
1373 return 100;
Stephen Hines651f13c2014-04-23 16:59:28 -07001374 if (Left.is(tok::coloncolon) ||
1375 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001376 return 500;
Daniel Jasper6b119d62013-04-05 17:22:09 +00001377 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1378 return 5000;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001379
Daniel Jasper6cabab42013-02-14 08:42:54 +00001380 if (Left.Type == TT_RangeBasedForLoopColon ||
1381 Left.Type == TT_InheritanceColon)
Daniel Jasper84a1a632013-02-26 13:18:08 +00001382 return 2;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001383
Daniel Jasperd3fef0f2013-08-27 14:24:43 +00001384 if (Right.isMemberAccess()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001385 if (Left.is(tok::r_paren) && Left.MatchingParen &&
Daniel Jasper2f0a0202013-09-06 08:54:24 +00001386 Left.MatchingParen->ParameterCount > 0)
Daniel Jasper518ee342013-02-26 13:59:14 +00001387 return 20; // Should be smaller than breaking at a nested comma.
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001388 return 150;
1389 }
1390
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001391 if (Right.Type == TT_TrailingAnnotation &&
1392 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001393 // Generally, breaking before a trailing annotation is bad unless it is
1394 // function-like. It seems to be especially preferable to keep standard
1395 // annotations (i.e. "const", "final" and "override") on the same line.
1396 // Use a slightly higher penalty after ")" so that annotations like
1397 // "const override" are kept together.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001398 bool is_short_annotation = Right.TokenText.size() < 10;
1399 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
Stephen Hines651f13c2014-04-23 16:59:28 -07001400 }
Daniel Jasper5ad72bb2013-05-22 08:28:26 +00001401
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001402 // In for-loops, prefer breaking at ',' and ';'.
Manuel Klimekb3987012013-05-29 14:47:47 +00001403 if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
Daniel Jasper7d812812013-02-21 15:00:29 +00001404 return 4;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001405
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001406 // In Objective-C method expressions, prefer breaking before "param:" over
1407 // breaking after it.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001408 if (Right.Type == TT_SelectorName)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001409 return 0;
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001410 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
Stephen Hines651f13c2014-04-23 16:59:28 -07001411 return Line.MightBeFunctionDecl ? 50 : 500;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001412
Daniel Jasperdbfb5f32013-11-07 17:52:51 +00001413 if (Left.is(tok::l_paren) && InFunctionDecl)
Daniel Jasper1407bee2013-04-11 14:29:13 +00001414 return 100;
Stephen Hines651f13c2014-04-23 16:59:28 -07001415 if (Left.is(tok::equal) && InFunctionDecl)
1416 return 110;
Daniel Jasperac3223e2013-04-10 09:49:49 +00001417 if (Left.opensScope())
Daniel Jasper47066e42013-10-25 14:29:37 +00001418 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1419 : 19;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001420
Daniel Jasper4e8a7b42013-02-06 21:04:05 +00001421 if (Right.is(tok::lessless)) {
1422 if (Left.is(tok::string_literal)) {
Alexander Kornienko00895102013-06-05 14:09:10 +00001423 StringRef Content = Left.TokenText;
Daniel Jasper20376982013-09-29 12:02:57 +00001424 if (Content.startswith("\""))
1425 Content = Content.drop_front(1);
1426 if (Content.endswith("\""))
1427 Content = Content.drop_back(1);
1428 Content = Content.trim();
Daniel Jasperbfa1edd2013-03-14 14:00:17 +00001429 if (Content.size() > 1 &&
1430 (Content.back() == ':' || Content.back() == '='))
Daniel Jasper9637dda2013-07-15 14:33:14 +00001431 return 25;
Daniel Jasper4e8a7b42013-02-06 21:04:05 +00001432 }
Daniel Jasper0c368782013-07-15 15:04:42 +00001433 return 1; // Breaking at a << is really cheap.
Daniel Jasper4e8a7b42013-02-06 21:04:05 +00001434 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001435 if (Left.Type == TT_ConditionalExpr)
Daniel Jasper518ee342013-02-26 13:59:14 +00001436 return prec::Conditional;
Manuel Klimekb3987012013-05-29 14:47:47 +00001437 prec::Level Level = Left.getPrecedence();
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001438
1439 if (Level != prec::Unknown)
1440 return Level;
Daniel Jasper24849712013-03-01 16:48:32 +00001441
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001442 return 3;
1443}
1444
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001445bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
Manuel Klimekb3987012013-05-29 14:47:47 +00001446 const FormatToken &Left,
1447 const FormatToken &Right) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001448 if (Style.Language == FormatStyle::LK_Proto) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001449 if (Right.is(tok::period) &&
1450 (Left.TokenText == "optional" || Left.TokenText == "required" ||
1451 Left.TokenText == "repeated"))
1452 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001453 if (Right.is(tok::l_paren) &&
1454 (Left.TokenText == "returns" || Left.TokenText == "option"))
1455 return true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001456 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1457 if (Left.TokenText == "var")
1458 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001459 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001460 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1461 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001462 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1463 Left.Tok.getObjCKeywordID() == tok::objc_property)
1464 return true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001465 if (Right.is(tok::hashhash))
1466 return Left.is(tok::hash);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001467 if (Left.isOneOf(tok::hashhash, tok::hash))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001468 return Right.is(tok::hash);
Daniel Jasper7df56bf2013-08-20 12:36:34 +00001469 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1470 return Style.SpaceInEmptyParentheses;
1471 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
Daniel Jasper34f3d052013-08-21 08:39:01 +00001472 return (Right.Type == TT_CastRParen ||
1473 (Left.MatchingParen && Left.MatchingParen->Type == TT_CastRParen))
Daniel Jasper7df56bf2013-08-20 12:36:34 +00001474 ? Style.SpacesInCStyleCastParentheses
1475 : Style.SpacesInParentheses;
Daniel Jasperd8ee5c12013-10-29 14:52:02 +00001476 if (Style.SpacesInAngles &&
1477 ((Left.Type == TT_TemplateOpener) != (Right.Type == TT_TemplateCloser)))
1478 return true;
Daniel Jasper7df56bf2013-08-20 12:36:34 +00001479 if (Right.isOneOf(tok::semi, tok::comma))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001480 return false;
1481 if (Right.is(tok::less) &&
1482 (Left.is(tok::kw_template) ||
1483 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1484 return true;
1485 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1486 return false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001487 if (Left.isOneOf(tok::exclaim, tok::tilde))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001488 return false;
1489 if (Left.is(tok::at) &&
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001490 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1491 tok::numeric_constant, tok::l_paren, tok::l_brace,
1492 tok::kw_true, tok::kw_false))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001493 return false;
1494 if (Left.is(tok::coloncolon))
1495 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001496 if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
Daniel Jasper78a4e612013-10-12 05:16:06 +00001497 return (Left.is(tok::less) && Style.Standard == FormatStyle::LS_Cpp03) ||
1498 !Left.isOneOf(tok::identifier, tok::greater, tok::l_paren,
1499 tok::r_paren, tok::less);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001500 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001501 return false;
Daniel Jasperc47d7f12013-07-01 09:47:25 +00001502 if (Right.is(tok::ellipsis))
Daniel Jasperb3c887d2013-10-20 16:56:16 +00001503 return Left.Tok.isLiteral();
Manuel Klimek31e44f72013-09-04 08:20:47 +00001504 if (Left.is(tok::l_square) && Right.is(tok::amp))
1505 return false;
Alexander Kornienko3fd9ccd2013-03-12 16:28:18 +00001506 if (Right.Type == TT_PointerOrReference)
Manuel Klimekb3987012013-05-29 14:47:47 +00001507 return Left.Tok.isLiteral() ||
Alexander Kornienko3fd9ccd2013-03-12 16:28:18 +00001508 ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001509 Style.PointerAlignment != FormatStyle::PAS_Left);
Daniel Jasper3ff4a2f2013-05-28 15:27:10 +00001510 if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001511 (Left.Type != TT_PointerOrReference || Style.PointerAlignment != FormatStyle::PAS_Right))
Daniel Jasper395228f2013-05-08 14:58:20 +00001512 return true;
Alexander Kornienko3fd9ccd2013-03-12 16:28:18 +00001513 if (Left.Type == TT_PointerOrReference)
Daniel Jasper3a1847e2013-07-01 09:34:09 +00001514 return Right.Tok.isLiteral() || Right.Type == TT_BlockComment ||
Daniel Jasper9322aae2013-03-20 09:53:18 +00001515 ((Right.Type != TT_PointerOrReference) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001516 Right.isNot(tok::l_paren) && Style.PointerAlignment != FormatStyle::PAS_Right &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001517 Left.Previous &&
1518 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001519 if (Right.is(tok::star) && Left.is(tok::l_paren))
1520 return false;
Nico Weber051860e2013-02-10 02:08:05 +00001521 if (Left.is(tok::l_square))
Daniel Jaspera07aa662013-10-22 15:30:28 +00001522 return Left.Type == TT_ArrayInitializerLSquare &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001523 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square);
Nico Weber051860e2013-02-10 02:08:05 +00001524 if (Right.is(tok::r_square))
Stephen Hines651f13c2014-04-23 16:59:28 -07001525 return Right.MatchingParen && Style.SpacesInContainerLiterals &&
Daniel Jaspera07aa662013-10-22 15:30:28 +00001526 Right.MatchingParen->Type == TT_ArrayInitializerLSquare;
Daniel Jasperec172262013-08-30 10:36:58 +00001527 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001528 Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant) &&
1529 Left.Type != TT_DictLiteral)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001530 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001531 if (Left.is(tok::colon))
1532 return Left.Type != TT_ObjCMethodExpr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001533 if (Left.Type == TT_BlockComment)
1534 return !Left.TokenText.endswith("=*/");
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001535 if (Right.is(tok::l_paren)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001536 if (Left.is(tok::r_paren) && Left.Type == TT_AttributeParen)
Daniel Jaspere0fa4c52013-07-17 20:25:02 +00001537 return true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001538 return Line.Type == LT_ObjCDecl ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001539 Left.isOneOf(tok::kw_new, tok::kw_delete, tok::semi) ||
Stephen Hines651f13c2014-04-23 16:59:28 -07001540 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1541 (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001542 tok::kw_switch, tok::kw_catch, tok::kw_case) ||
Stephen Hines651f13c2014-04-23 16:59:28 -07001543 Left.IsForEachMacro)) ||
1544 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1545 Left.isOneOf(tok::identifier, tok::kw___attribute) &&
1546 Line.Type != LT_PreprocessorDirective);
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001547 }
Manuel Klimekb3987012013-05-29 14:47:47 +00001548 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001549 return false;
1550 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
Daniel Jasper567dcf92013-09-05 09:29:45 +00001551 return !Left.Children.empty(); // No spaces in "{}".
Stephen Hines651f13c2014-04-23 16:59:28 -07001552 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1553 (Right.is(tok::r_brace) && Right.MatchingParen &&
1554 Right.MatchingParen->BlockKind != BK_Block))
Daniel Jasperb5dc3f42013-07-16 18:22:10 +00001555 return !Style.Cpp11BracedListStyle;
Daniel Jasper1bee0732013-05-23 18:05:18 +00001556 if (Right.Type == TT_UnaryOperator)
1557 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1558 (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001559 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1560 tok::r_paren) ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001561 Left.isSimpleTypeSpecifier()) &&
Manuel Klimek31e44f72013-09-04 08:20:47 +00001562 Right.is(tok::l_brace) && Right.getNextNonComment() &&
1563 Right.BlockKind != BK_Block)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001564 return false;
Daniel Jasper5ad390d2013-05-28 11:30:49 +00001565 if (Left.is(tok::period) || Right.is(tok::period))
1566 return false;
Alexander Kornienkodaa07e92013-09-10 13:41:43 +00001567 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1568 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001569 return true;
1570}
1571
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001572bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
Manuel Klimekb3987012013-05-29 14:47:47 +00001573 const FormatToken &Tok) {
1574 if (Tok.Tok.getIdentifierInfo() && Tok.Previous->Tok.getIdentifierInfo())
Daniel Jasper2b4c9242013-02-11 08:01:18 +00001575 return true; // Never ever merge two identifiers.
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001576 if (Tok.Previous->Type == TT_ImplicitStringLiteral)
1577 return Tok.WhitespaceRange.getBegin() != Tok.WhitespaceRange.getEnd();
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001578 if (Line.Type == LT_ObjCMethodDecl) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001579 if (Tok.Previous->Type == TT_ObjCMethodSpecifier)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001580 return true;
Manuel Klimekb3987012013-05-29 14:47:47 +00001581 if (Tok.Previous->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001582 // Don't space between ')' and <id>
1583 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001584 }
1585 if (Line.Type == LT_ObjCProperty &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001586 (Tok.is(tok::equal) || Tok.Previous->is(tok::equal)))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001587 return false;
1588
Daniel Jasper2ca37412013-07-09 14:36:48 +00001589 if (Tok.Type == TT_TrailingReturnArrow ||
1590 Tok.Previous->Type == TT_TrailingReturnArrow)
1591 return true;
Manuel Klimekb3987012013-05-29 14:47:47 +00001592 if (Tok.Previous->is(tok::comma))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001593 return true;
Daniel Jasper9c3c7b32013-02-28 13:40:17 +00001594 if (Tok.is(tok::comma))
1595 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001596 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
1597 return true;
Manuel Klimekb3987012013-05-29 14:47:47 +00001598 if (Tok.Previous->Tok.is(tok::kw_operator))
Daniel Jasper52af9442013-10-29 12:24:23 +00001599 return Tok.is(tok::coloncolon);
Daniel Jasper2b4c9242013-02-11 08:01:18 +00001600 if (Tok.Type == TT_OverloadedOperatorLParen)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001601 return false;
1602 if (Tok.is(tok::colon))
Manuel Klimekb3987012013-05-29 14:47:47 +00001603 return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001604 Tok.getNextNonComment() && Tok.Type != TT_ObjCMethodExpr &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001605 !Tok.Previous->is(tok::question) &&
1606 (Tok.Type != TT_DictLiteral || Style.SpacesInContainerLiterals);
Manuel Klimekb3987012013-05-29 14:47:47 +00001607 if (Tok.Previous->Type == TT_UnaryOperator ||
1608 Tok.Previous->Type == TT_CastRParen)
Stephen Hines651f13c2014-04-23 16:59:28 -07001609 return Tok.Type == TT_BinaryOperator;
Manuel Klimekb3987012013-05-29 14:47:47 +00001610 if (Tok.Previous->is(tok::greater) && Tok.is(tok::greater)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +00001611 return Tok.Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001612 Tok.Previous->Type == TT_TemplateCloser &&
Daniel Jasperd8ee5c12013-10-29 14:52:02 +00001613 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001614 }
Alexander Kornienko54a38bd2013-03-20 16:41:56 +00001615 if (Tok.isOneOf(tok::arrowstar, tok::periodstar) ||
Manuel Klimekb3987012013-05-29 14:47:47 +00001616 Tok.Previous->isOneOf(tok::arrowstar, tok::periodstar))
Daniel Jasper9c3c7b32013-02-28 13:40:17 +00001617 return false;
Daniel Jasper9b4de852013-09-25 15:15:02 +00001618 if (!Style.SpaceBeforeAssignmentOperators &&
1619 Tok.getPrecedence() == prec::Assignment)
1620 return false;
Daniel Jasper1dc6f742013-08-07 16:29:23 +00001621 if ((Tok.Type == TT_BinaryOperator && !Tok.Previous->is(tok::l_paren)) ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001622 Tok.Previous->Type == TT_BinaryOperator ||
1623 Tok.Previous->Type == TT_ConditionalExpr)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001624 return true;
Manuel Klimekb3987012013-05-29 14:47:47 +00001625 if (Tok.Previous->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001626 return false;
Daniel Jaspera4dd9822013-08-28 08:24:04 +00001627 if (Tok.is(tok::less) && Tok.Previous->isNot(tok::l_paren) &&
1628 Line.First->is(tok::hash))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001629 return true;
1630 if (Tok.Type == TT_TrailingUnaryOperator)
1631 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001632 if (Tok.Previous->Type == TT_RegexLiteral)
1633 return false;
Manuel Klimekb3987012013-05-29 14:47:47 +00001634 return spaceRequiredBetween(Line, *Tok.Previous, Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001635}
1636
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001637// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
1638static bool isAllmanBrace(const FormatToken &Tok) {
1639 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
1640 Tok.Type != TT_ObjCBlockLBrace && Tok.Type != TT_DictLiteral;
1641}
1642
Daniel Jasperebaa1712013-09-17 09:52:48 +00001643bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
1644 const FormatToken &Right) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001645 const FormatToken &Left = *Right.Previous;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001646 if (Right.NewlinesBefore > 1)
1647 return true;
Daniel Jasperebaa1712013-09-17 09:52:48 +00001648 if (Right.is(tok::comment)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001649 return Right.Previous->BlockKind != BK_BracedInit &&
1650 Right.Previous->Type != TT_CtorInitializerColon &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001651 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
Daniel Jasperebaa1712013-09-17 09:52:48 +00001652 } else if (Right.Previous->isTrailingComment() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07001653 (Right.isStringLiteral() && Right.Previous->isStringLiteral())) {
Daniel Jasperebaa1712013-09-17 09:52:48 +00001654 return true;
1655 } else if (Right.Previous->IsUnterminatedLiteral) {
1656 return true;
1657 } else if (Right.is(tok::lessless) && Right.Next &&
1658 Right.Previous->is(tok::string_literal) &&
1659 Right.Next->is(tok::string_literal)) {
1660 return true;
1661 } else if (Right.Previous->ClosesTemplateDeclaration &&
1662 Right.Previous->MatchingParen &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001663 Right.Previous->MatchingParen->NestingLevel == 0 &&
Daniel Jasperebaa1712013-09-17 09:52:48 +00001664 Style.AlwaysBreakTemplateDeclarations) {
Daniel Jasperebaa1712013-09-17 09:52:48 +00001665 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001666 } else if ((Right.Type == TT_CtorInitializerComma ||
1667 Right.Type == TT_CtorInitializerColon) &&
Daniel Jasper19ccb122013-10-08 05:11:18 +00001668 Style.BreakConstructorInitializersBeforeComma &&
1669 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
Daniel Jasperebaa1712013-09-17 09:52:48 +00001670 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001671 } else if (Right.is(tok::string_literal) &&
1672 Right.TokenText.startswith("R\"")) {
1673 // Raw string literals are special wrt. line breaks. The author has made a
1674 // deliberate choice and might have aligned the contents of the string
1675 // literal accordingly. Thus, we try keep existing line breaks.
1676 return Right.NewlinesBefore > 0;
1677 } else if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
1678 Style.Language == FormatStyle::LK_Proto) {
1679 // Don't enums onto single lines in protocol buffers.
1680 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001681 } else if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
1682 return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1683 Style.BreakBeforeBraces == FormatStyle::BS_GNU;
Daniel Jasperebaa1712013-09-17 09:52:48 +00001684 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001685
1686 // If the last token before a '}' is a comma or a comment, the intention is to
1687 // insert a line break after it in order to make shuffling around entries
1688 // easier.
1689 const FormatToken *BeforeClosingBrace = nullptr;
1690 if (Left.is(tok::l_brace) && Left.MatchingParen)
1691 BeforeClosingBrace = Left.MatchingParen->Previous;
1692 else if (Right.is(tok::r_brace))
1693 BeforeClosingBrace = Right.Previous;
1694 if (BeforeClosingBrace &&
1695 BeforeClosingBrace->isOneOf(tok::comma, tok::comment))
1696 return true;
1697
1698 if (Style.Language == FormatStyle::LK_JavaScript) {
1699 // FIXME: This might apply to other languages and token kinds.
1700 if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
1701 Left.Previous->is(tok::char_constant))
1702 return true;
1703 }
1704
Daniel Jasperebaa1712013-09-17 09:52:48 +00001705 return false;
1706}
1707
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001708bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
Manuel Klimekb3987012013-05-29 14:47:47 +00001709 const FormatToken &Right) {
1710 const FormatToken &Left = *Right.Previous;
Stephen Hines651f13c2014-04-23 16:59:28 -07001711 if (Left.is(tok::at))
1712 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001713 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
1714 return false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001715 if (Right.Type == TT_StartOfName ||
1716 Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001717 return true;
Daniel Jasper1a896a52013-11-08 00:57:11 +00001718 if (Right.isTrailingComment())
1719 // We rely on MustBreakBefore being set correctly here as we should not
1720 // change the "binding" behavior of a comment.
Stephen Hines651f13c2014-04-23 16:59:28 -07001721 // The first comment in a braced lists is always interpreted as belonging to
1722 // the first list element. Otherwise, it should be placed outside of the
1723 // list.
1724 return Left.BlockKind == BK_BracedInit;
Daniel Jasper1a896a52013-11-08 00:57:11 +00001725 if (Left.is(tok::question) && Right.is(tok::colon))
1726 return false;
1727 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1728 return Style.BreakBeforeTernaryOperators;
1729 if (Left.Type == TT_ConditionalExpr || Left.is(tok::question))
1730 return !Style.BreakBeforeTernaryOperators;
Stephen Hines651f13c2014-04-23 16:59:28 -07001731 if (Right.Type == TT_InheritanceColon)
1732 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001733 if (Right.is(tok::colon) && (Right.Type != TT_CtorInitializerColon &&
1734 Right.Type != TT_InlineASMColon))
1735 return false;
Nico Weberf2ff8122013-05-26 05:39:26 +00001736 if (Left.is(tok::colon) &&
Daniel Jasper3c6aea72013-10-24 10:31:50 +00001737 (Left.Type == TT_DictLiteral || Left.Type == TT_ObjCMethodExpr))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001738 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001739 if (Right.Type == TT_SelectorName)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001740 return true;
Daniel Jasperaa9e7b12013-08-01 13:46:58 +00001741 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
1742 return true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001743 if (Left.ClosesTemplateDeclaration)
1744 return true;
Daniel Jasper6cabab42013-02-14 08:42:54 +00001745 if (Right.Type == TT_RangeBasedForLoopColon ||
Daniel Jasperc476ea92013-08-28 07:27:35 +00001746 Right.Type == TT_OverloadedOperatorLParen ||
1747 Right.Type == TT_OverloadedOperator)
Daniel Jasper6cabab42013-02-14 08:42:54 +00001748 return false;
Daniel Jasperc194c952013-05-06 06:45:09 +00001749 if (Left.Type == TT_RangeBasedForLoopColon)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001750 return true;
Daniel Jasper7d812812013-02-21 15:00:29 +00001751 if (Right.Type == TT_RangeBasedForLoopColon)
1752 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001753 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper1a896a52013-11-08 00:57:11 +00001754 Left.Type == TT_UnaryOperator || Left.is(tok::kw_operator))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001755 return false;
1756 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
1757 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001758 if (Left.is(tok::l_paren) && Left.Type == TT_AttributeParen)
1759 return false;
1760 if (Left.is(tok::l_paren) && Left.Previous &&
1761 (Left.Previous->Type == TT_BinaryOperator ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001762 Left.Previous->Type == TT_CastRParen || Left.Previous->is(tok::kw_if)))
Stephen Hines651f13c2014-04-23 16:59:28 -07001763 return false;
Daniel Jasper84379572013-10-30 13:54:53 +00001764 if (Right.Type == TT_ImplicitStringLiteral)
1765 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001766
Daniel Jasper567dcf92013-09-05 09:29:45 +00001767 if (Right.is(tok::r_paren) || Right.Type == TT_TemplateCloser)
1768 return false;
1769
Daniel Jasper5ad72bb2013-05-22 08:28:26 +00001770 // We only break before r_brace if there was a corresponding break before
1771 // the l_brace, which is tracked by BreakBeforeClosingBrace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001772 if (Right.is(tok::r_brace))
1773 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
Daniel Jasper5ad72bb2013-05-22 08:28:26 +00001774
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001775 // Allow breaking after a trailing annotation, e.g. after a method
1776 // declaration.
1777 if (Left.Type == TT_TrailingAnnotation)
1778 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
1779 tok::less, tok::coloncolon);
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001780
Daniel Jasper8ef19a22013-03-14 09:50:46 +00001781 if (Right.is(tok::kw___attribute))
1782 return true;
1783
Daniel Jasper3a204412013-02-23 07:46:38 +00001784 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
1785 return true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +00001786
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001787 if (Right.is(tok::identifier) && Right.Next &&
1788 Right.Next->Type == TT_DictLiteral)
1789 return true;
1790
Daniel Jaspere8b10d32013-07-26 16:56:36 +00001791 if (Left.Type == TT_CtorInitializerComma &&
1792 Style.BreakConstructorInitializersBeforeComma)
1793 return false;
Daniel Jasper19ccb122013-10-08 05:11:18 +00001794 if (Right.Type == TT_CtorInitializerComma &&
1795 Style.BreakConstructorInitializersBeforeComma)
1796 return true;
Daniel Jasper26356cc2013-09-17 08:15:46 +00001797 if (Left.is(tok::greater) && Right.is(tok::greater) &&
1798 Left.Type != TT_TemplateCloser)
1799 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001800 if (Right.Type == TT_BinaryOperator && Style.BreakBeforeBinaryOperators)
1801 return true;
Daniel Jaspera07aa662013-10-22 15:30:28 +00001802 if (Left.Type == TT_ArrayInitializerLSquare)
1803 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001804 return (Left.isBinaryOperator() &&
1805 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
Daniel Jaspere8b10d32013-07-26 16:56:36 +00001806 !Style.BreakBeforeBinaryOperators) ||
Daniel Jasper6b119d62013-04-05 17:22:09 +00001807 Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
1808 tok::kw_class, tok::kw_struct) ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001809 Right.isMemberAccess() ||
1810 Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at) ||
Daniel Jasper198c8bf2013-07-05 07:58:34 +00001811 (Left.is(tok::r_paren) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001812 Right.isOneOf(tok::identifier, tok::kw_const)) ||
Daniel Jaspera07aa662013-10-22 15:30:28 +00001813 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001814}
1815
Daniel Jasperbf71ba22013-04-08 20:33:42 +00001816void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
1817 llvm::errs() << "AnnotatedTokens:\n";
Manuel Klimekb3987012013-05-29 14:47:47 +00001818 const FormatToken *Tok = Line.First;
Daniel Jasperbf71ba22013-04-08 20:33:42 +00001819 while (Tok) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001820 llvm::errs() << " M=" << Tok->MustBreakBefore
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001821 << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
1822 << " S=" << Tok->SpacesRequiredBefore
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001823 << " B=" << Tok->BlockParameterCount
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001824 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001825 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
1826 << " FakeLParens=";
Daniel Jasperbf71ba22013-04-08 20:33:42 +00001827 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
1828 llvm::errs() << Tok->FakeLParens[i] << "/";
1829 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001830 if (!Tok->Next)
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001831 assert(Tok == Line.Last);
Manuel Klimekb3987012013-05-29 14:47:47 +00001832 Tok = Tok->Next;
Daniel Jasperbf71ba22013-04-08 20:33:42 +00001833 }
1834 llvm::errs() << "----\n";
1835}
1836
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001837} // namespace format
1838} // namespace clang