blob: f642a7030917f5cfd9b31b7874f5faae069c7e16 [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"
18#include "clang/Lex/Lexer.h"
19
20namespace clang {
21namespace format {
22
Nico Weberee0feec2013-02-05 16:21:00 +000023static bool isUnaryOperator(const AnnotatedToken &Tok) {
24 switch (Tok.FormatTok.Tok.getKind()) {
25 case tok::plus:
26 case tok::plusplus:
27 case tok::minus:
28 case tok::minusminus:
29 case tok::exclaim:
30 case tok::tilde:
31 case tok::kw_sizeof:
32 case tok::kw_alignof:
33 return true;
34 default:
35 return false;
36 }
37}
38
Daniel Jasper32d28ee2013-01-29 21:01:14 +000039static bool isBinaryOperator(const AnnotatedToken &Tok) {
40 // Comma is a binary operator, but does not behave as such wrt. formatting.
41 return getPrecedence(Tok) > prec::Comma;
42}
43
Daniel Jasper01786732013-02-04 07:21:18 +000044// Returns the previous token ignoring comments.
Nico Weber4ed7f3e2013-02-06 16:54:35 +000045static AnnotatedToken *getPreviousToken(AnnotatedToken &Tok) {
46 AnnotatedToken *PrevToken = Tok.Parent;
Daniel Jasper01786732013-02-04 07:21:18 +000047 while (PrevToken != NULL && PrevToken->is(tok::comment))
48 PrevToken = PrevToken->Parent;
49 return PrevToken;
50}
Nico Weber4ed7f3e2013-02-06 16:54:35 +000051static const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
52 return getPreviousToken(const_cast<AnnotatedToken &>(Tok));
53}
Daniel Jasper01786732013-02-04 07:21:18 +000054
Daniel Jasper29f123b2013-02-08 15:28:42 +000055static bool isTrailingComment(AnnotatedToken *Tok) {
56 return Tok != NULL && Tok->is(tok::comment) &&
57 (Tok->Children.empty() ||
58 Tok->Children[0].FormatTok.NewlinesBefore > 0);
59}
60
Daniel Jasper01786732013-02-04 07:21:18 +000061// Returns the next token ignoring comments.
62static const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
63 if (Tok.Children.empty())
64 return NULL;
65 const AnnotatedToken *NextToken = &Tok.Children[0];
66 while (NextToken->is(tok::comment)) {
67 if (NextToken->Children.empty())
68 return NULL;
69 NextToken = &NextToken->Children[0];
70 }
71 return NextToken;
72}
73
Daniel Jasper32d28ee2013-01-29 21:01:14 +000074/// \brief A parser that gathers additional information about tokens.
75///
76/// The \c TokenAnnotator tries to matches parenthesis and square brakets and
77/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
78/// into template parameter lists.
79class AnnotatingParser {
80public:
Nico Weberc2e6d2a2013-02-11 15:32:15 +000081 AnnotatingParser(SourceManager &SourceMgr, Lexer &Lex, AnnotatedLine &Line,
82 IdentifierInfo &Ident_in)
Daniel Jasper01786732013-02-04 07:21:18 +000083 : SourceMgr(SourceMgr), Lex(Lex), Line(Line), CurrentToken(&Line.First),
Nico Weberc2e6d2a2013-02-11 15:32:15 +000084 KeywordVirtualFound(false), Ident_in(Ident_in) {
Daniel Jasper4e778092013-02-06 10:05:46 +000085 Contexts.push_back(Context(1, /*IsExpression=*/ false));
Daniel Jasper32d28ee2013-01-29 21:01:14 +000086 }
87
Nico Weber95e8e462013-02-12 16:17:07 +000088private:
Daniel Jasper32d28ee2013-01-29 21:01:14 +000089 bool parseAngle() {
90 if (CurrentToken == NULL)
91 return false;
Daniel Jasper4e778092013-02-06 10:05:46 +000092 ScopedContextCreator ContextCreator(*this, 10);
Daniel Jasper32d28ee2013-01-29 21:01:14 +000093 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper4e778092013-02-06 10:05:46 +000094 Contexts.back().IsExpression = false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +000095 while (CurrentToken != NULL) {
96 if (CurrentToken->is(tok::greater)) {
97 Left->MatchingParen = CurrentToken;
98 CurrentToken->MatchingParen = Left;
99 CurrentToken->Type = TT_TemplateCloser;
100 next();
101 return true;
102 }
103 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
104 CurrentToken->is(tok::r_brace))
105 return false;
106 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
107 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
108 return false;
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000109 updateParameterCount(Left, CurrentToken);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000110 if (!consumeToken())
111 return false;
112 }
113 return false;
114 }
115
116 bool parseParens(bool LookForDecls = false) {
117 if (CurrentToken == NULL)
118 return false;
Daniel Jasper4e778092013-02-06 10:05:46 +0000119 ScopedContextCreator ContextCreator(*this, 1);
120
121 // FIXME: This is a bit of a hack. Do better.
122 Contexts.back().ColonIsForRangeExpr =
123 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
124
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000125 bool StartsObjCMethodExpr = false;
126 AnnotatedToken *Left = CurrentToken->Parent;
127 if (CurrentToken->is(tok::caret)) {
128 // ^( starts a block.
129 Left->Type = TT_ObjCBlockLParen;
130 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
131 // @selector( starts a selector.
132 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
133 MaybeSel->Parent->is(tok::at)) {
134 StartsObjCMethodExpr = true;
135 }
136 }
137
Daniel Jasper4e778092013-02-06 10:05:46 +0000138 if (StartsObjCMethodExpr) {
139 Contexts.back().ColonIsObjCMethodExpr = true;
140 Left->Type = TT_ObjCMethodExpr;
141 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000142
143 while (CurrentToken != NULL) {
144 // LookForDecls is set when "if (" has been seen. Check for
145 // 'identifier' '*' 'identifier' followed by not '=' -- this
146 // '*' has to be a binary operator but determineStarAmpUsage() will
147 // categorize it as an unary operator, so set the right type here.
148 if (LookForDecls && !CurrentToken->Children.empty()) {
149 AnnotatedToken &Prev = *CurrentToken->Parent;
150 AnnotatedToken &Next = CurrentToken->Children[0];
151 if (Prev.Parent->is(tok::identifier) &&
152 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
153 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
154 Prev.Type = TT_BinaryOperator;
155 LookForDecls = false;
156 }
157 }
158
159 if (CurrentToken->is(tok::r_paren)) {
160 Left->MatchingParen = CurrentToken;
161 CurrentToken->MatchingParen = Left;
162
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000163 if (StartsObjCMethodExpr) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000164 CurrentToken->Type = TT_ObjCMethodExpr;
165 if (Contexts.back().FirstObjCSelectorName != NULL) {
166 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
167 Contexts.back().LongestObjCSelectorName;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000168 }
169 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000170
171 next();
172 return true;
173 }
174 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
175 return false;
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000176 updateParameterCount(Left, CurrentToken);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000177 if (!consumeToken())
178 return false;
179 }
180 return false;
181 }
182
183 bool parseSquare() {
184 if (!CurrentToken)
185 return false;
Daniel Jasper4e778092013-02-06 10:05:46 +0000186 ScopedContextCreator ContextCreator(*this, 10);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000187
188 // A '[' could be an index subscript (after an indentifier or after
Nico Weber051860e2013-02-10 02:08:05 +0000189 // ')' or ']'), it could be the start of an Objective-C method
190 // expression, or it could the the start of an Objective-C array literal.
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000191 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber4ed7f3e2013-02-06 16:54:35 +0000192 AnnotatedToken *Parent = getPreviousToken(*Left);
Daniel Jasper9c65b062013-02-27 11:43:50 +0000193 Contexts.back().IsExpression = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000194 bool StartsObjCMethodExpr =
Nico Weber4ed7f3e2013-02-06 16:54:35 +0000195 !Parent || Parent->is(tok::colon) || Parent->is(tok::l_square) ||
196 Parent->is(tok::l_paren) || Parent->is(tok::kw_return) ||
197 Parent->is(tok::kw_throw) || isUnaryOperator(*Parent) ||
Nico Weber4c2cc602013-02-13 03:48:27 +0000198 Parent->Type == TT_ObjCForIn || Parent->Type == TT_CastRParen ||
Nico Weber4ed7f3e2013-02-06 16:54:35 +0000199 getBinOpPrecedence(Parent->FormatTok.Tok.getKind(), true, true) >
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000200 prec::Unknown;
Nico Weber051860e2013-02-10 02:08:05 +0000201 bool StartsObjCArrayLiteral = Parent && Parent->is(tok::at);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000202
Daniel Jasper4e778092013-02-06 10:05:46 +0000203 if (StartsObjCMethodExpr) {
204 Contexts.back().ColonIsObjCMethodExpr = true;
205 Left->Type = TT_ObjCMethodExpr;
Nico Weber051860e2013-02-10 02:08:05 +0000206 } else if (StartsObjCArrayLiteral) {
207 Left->Type = TT_ObjCArrayLiteral;
Daniel Jasper4e778092013-02-06 10:05:46 +0000208 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000209
210 while (CurrentToken != NULL) {
211 if (CurrentToken->is(tok::r_square)) {
212 if (!CurrentToken->Children.empty() &&
213 CurrentToken->Children[0].is(tok::l_paren)) {
Nico Webere8a97982013-02-06 06:20:11 +0000214 // An ObjC method call is rarely followed by an open parenthesis.
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000215 // FIXME: Do we incorrectly label ":" with this?
216 StartsObjCMethodExpr = false;
217 Left->Type = TT_Unknown;
218 }
Daniel Jasper01786732013-02-04 07:21:18 +0000219 if (StartsObjCMethodExpr) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000220 CurrentToken->Type = TT_ObjCMethodExpr;
Nico Webere8a97982013-02-06 06:20:11 +0000221 // determineStarAmpUsage() thinks that '*' '[' is allocating an
222 // array of pointers, but if '[' starts a selector then '*' is a
223 // binary operator.
Nico Weber4ed7f3e2013-02-06 16:54:35 +0000224 if (Parent != NULL &&
225 (Parent->is(tok::star) || Parent->is(tok::amp)) &&
226 Parent->Type == TT_PointerOrReference)
227 Parent->Type = TT_BinaryOperator;
Nico Weber051860e2013-02-10 02:08:05 +0000228 } else if (StartsObjCArrayLiteral) {
229 CurrentToken->Type = TT_ObjCArrayLiteral;
Daniel Jasper01786732013-02-04 07:21:18 +0000230 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000231 Left->MatchingParen = CurrentToken;
232 CurrentToken->MatchingParen = Left;
Daniel Jasper4e778092013-02-06 10:05:46 +0000233 if (Contexts.back().FirstObjCSelectorName != NULL)
234 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
235 Contexts.back().LongestObjCSelectorName;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000236 next();
237 return true;
238 }
239 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
240 return false;
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000241 updateParameterCount(Left, CurrentToken);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000242 if (!consumeToken())
243 return false;
244 }
245 return false;
246 }
247
248 bool parseBrace() {
249 // Lines are fine to end with '{'.
250 if (CurrentToken == NULL)
251 return true;
Daniel Jasper4e778092013-02-06 10:05:46 +0000252 ScopedContextCreator ContextCreator(*this, 1);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000253 AnnotatedToken *Left = CurrentToken->Parent;
254 while (CurrentToken != NULL) {
255 if (CurrentToken->is(tok::r_brace)) {
256 Left->MatchingParen = CurrentToken;
257 CurrentToken->MatchingParen = Left;
258 next();
259 return true;
260 }
261 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
262 return false;
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000263 updateParameterCount(Left, CurrentToken);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000264 if (!consumeToken())
265 return false;
266 }
267 return true;
268 }
Daniel Jasperc4615b72013-02-20 12:56:39 +0000269
Daniel Jasper9fc56f22013-02-14 15:01:34 +0000270 void updateParameterCount(AnnotatedToken *Left, AnnotatedToken *Current) {
271 if (Current->is(tok::comma))
272 ++Left->ParameterCount;
273 else if (Left->ParameterCount == 0 && Current->isNot(tok::comment))
274 Left->ParameterCount = 1;
275 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000276
277 bool parseConditional() {
278 while (CurrentToken != NULL) {
279 if (CurrentToken->is(tok::colon)) {
280 CurrentToken->Type = TT_ConditionalExpr;
281 next();
282 return true;
283 }
284 if (!consumeToken())
285 return false;
286 }
287 return false;
288 }
289
290 bool parseTemplateDeclaration() {
291 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
292 CurrentToken->Type = TT_TemplateOpener;
293 next();
294 if (!parseAngle())
295 return false;
Daniel Jasper34511fb2013-02-19 17:14:38 +0000296 if (CurrentToken != NULL)
297 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000298 return true;
299 }
300 return false;
301 }
302
303 bool consumeToken() {
304 AnnotatedToken *Tok = CurrentToken;
305 next();
306 switch (Tok->FormatTok.Tok.getKind()) {
307 case tok::plus:
308 case tok::minus:
309 // At the start of the line, +/- specific ObjectiveC method
310 // declarations.
311 if (Tok->Parent == NULL)
312 Tok->Type = TT_ObjCMethodSpecifier;
313 break;
314 case tok::colon:
315 // Colons from ?: are handled in parseConditional().
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000316 if (Tok->Parent->is(tok::r_paren)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000317 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper4e778092013-02-06 10:05:46 +0000318 } else if (Contexts.back().ColonIsObjCMethodExpr ||
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000319 Line.First.Type == TT_ObjCMethodSpecifier) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000320 Tok->Type = TT_ObjCMethodExpr;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000321 Tok->Parent->Type = TT_ObjCSelectorName;
Daniel Jasper4e778092013-02-06 10:05:46 +0000322 if (Tok->Parent->FormatTok.TokenLength >
323 Contexts.back().LongestObjCSelectorName)
324 Contexts.back().LongestObjCSelectorName =
325 Tok->Parent->FormatTok.TokenLength;
326 if (Contexts.back().FirstObjCSelectorName == NULL)
327 Contexts.back().FirstObjCSelectorName = Tok->Parent;
328 } else if (Contexts.back().ColonIsForRangeExpr) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000329 Tok->Type = TT_RangeBasedForLoopColon;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000330 } else if (Contexts.size() == 1) {
331 Tok->Type = TT_InheritanceColon;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000332 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000333 break;
334 case tok::kw_if:
335 case tok::kw_while:
336 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
337 next();
338 if (!parseParens(/*LookForDecls=*/ true))
339 return false;
340 }
341 break;
342 case tok::kw_for:
Daniel Jasper4e778092013-02-06 10:05:46 +0000343 Contexts.back().ColonIsForRangeExpr = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000344 next();
345 if (!parseParens())
346 return false;
347 break;
348 case tok::l_paren:
349 if (!parseParens())
350 return false;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000351 if (Line.MustBeDeclaration)
352 Line.MightBeFunctionDecl = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000353 break;
354 case tok::l_square:
355 if (!parseSquare())
356 return false;
357 break;
358 case tok::l_brace:
359 if (!parseBrace())
360 return false;
361 break;
362 case tok::less:
363 if (parseAngle())
364 Tok->Type = TT_TemplateOpener;
365 else {
366 Tok->Type = TT_BinaryOperator;
367 CurrentToken = Tok;
368 next();
369 }
370 break;
371 case tok::r_paren:
372 case tok::r_square:
373 return false;
374 case tok::r_brace:
375 // Lines can start with '}'.
376 if (Tok->Parent != NULL)
377 return false;
378 break;
379 case tok::greater:
380 Tok->Type = TT_BinaryOperator;
381 break;
382 case tok::kw_operator:
Daniel Jasper2b4c9242013-02-11 08:01:18 +0000383 while (CurrentToken && CurrentToken->isNot(tok::l_paren)) {
384 if (CurrentToken->is(tok::star) || CurrentToken->is(tok::amp))
385 CurrentToken->Type = TT_PointerOrReference;
386 consumeToken();
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000387 }
Daniel Jasper2b4c9242013-02-11 08:01:18 +0000388 if (CurrentToken)
389 CurrentToken->Type = TT_OverloadedOperatorLParen;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000390 break;
391 case tok::question:
392 parseConditional();
393 break;
394 case tok::kw_template:
395 parseTemplateDeclaration();
396 break;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000397 case tok::identifier:
398 if (Line.First.is(tok::kw_for) &&
399 Tok->FormatTok.Tok.getIdentifierInfo() == &Ident_in)
400 Tok->Type = TT_ObjCForIn;
401 break;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000402 default:
403 break;
404 }
405 return true;
406 }
407
408 void parseIncludeDirective() {
409 next();
410 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
411 next();
412 while (CurrentToken != NULL) {
413 if (CurrentToken->isNot(tok::comment) ||
414 !CurrentToken->Children.empty())
415 CurrentToken->Type = TT_ImplicitStringLiteral;
416 next();
417 }
418 } else {
419 while (CurrentToken != NULL) {
Daniel Jasper3a204412013-02-23 07:46:38 +0000420 if (CurrentToken->is(tok::string_literal))
421 // Mark these string literals as "implicit" literals, too, so that
422 // they are not split or line-wrapped.
423 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000424 next();
425 }
426 }
427 }
428
429 void parseWarningOrError() {
430 next();
431 // We still want to format the whitespace left of the first token of the
432 // warning or error.
433 next();
434 while (CurrentToken != NULL) {
435 CurrentToken->Type = TT_ImplicitStringLiteral;
436 next();
437 }
438 }
439
440 void parsePreprocessorDirective() {
441 next();
442 if (CurrentToken == NULL)
443 return;
444 // Hashes in the middle of a line can lead to any strange token
445 // sequence.
446 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
447 return;
448 switch (CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
449 case tok::pp_include:
450 case tok::pp_import:
451 parseIncludeDirective();
452 break;
453 case tok::pp_error:
454 case tok::pp_warning:
455 parseWarningOrError();
456 break;
457 default:
458 break;
459 }
Daniel Jasper5b7e7b02013-02-05 09:34:14 +0000460 while (CurrentToken != NULL)
461 next();
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000462 }
463
Nico Weber95e8e462013-02-12 16:17:07 +0000464public:
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000465 LineType parseLine() {
466 int PeriodsAndArrows = 0;
Daniel Jasper24849712013-03-01 16:48:32 +0000467 AnnotatedToken *LastPeriodOrArrow = NULL;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000468 bool CanBeBuilderTypeStmt = true;
469 if (CurrentToken->is(tok::hash)) {
470 parsePreprocessorDirective();
471 return LT_PreprocessorDirective;
472 }
473 while (CurrentToken != NULL) {
474 if (CurrentToken->is(tok::kw_virtual))
475 KeywordVirtualFound = true;
Daniel Jasper24849712013-03-01 16:48:32 +0000476 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000477 ++PeriodsAndArrows;
Daniel Jasper24849712013-03-01 16:48:32 +0000478 LastPeriodOrArrow = CurrentToken;
479 }
Daniel Jasper4a544e52013-02-15 20:33:06 +0000480 AnnotatedToken *TheToken = CurrentToken;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000481 if (!consumeToken())
482 return LT_Invalid;
Daniel Jasper4a544e52013-02-15 20:33:06 +0000483 if (getPrecedence(*TheToken) > prec::Assignment &&
Daniel Jasper82282dc2013-02-18 13:52:06 +0000484 TheToken->Type == TT_BinaryOperator)
Daniel Jasper4a544e52013-02-15 20:33:06 +0000485 CanBeBuilderTypeStmt = false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000486 }
487 if (KeywordVirtualFound)
488 return LT_VirtualFunctionDecl;
489
490 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasper24849712013-03-01 16:48:32 +0000491 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt) {
492 LastPeriodOrArrow->LastInChainOfCalls = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000493 return LT_BuilderTypeCall;
Daniel Jasper24849712013-03-01 16:48:32 +0000494 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000495
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000496 if (Line.First.Type == TT_ObjCMethodSpecifier) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000497 if (Contexts.back().FirstObjCSelectorName != NULL)
498 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
499 Contexts.back().LongestObjCSelectorName;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000500 return LT_ObjCMethodDecl;
501 }
502
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000503 return LT_Other;
504 }
505
Nico Weber95e8e462013-02-12 16:17:07 +0000506private:
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000507 void next() {
Daniel Jasper01786732013-02-04 07:21:18 +0000508 if (CurrentToken != NULL) {
509 determineTokenType(*CurrentToken);
Daniel Jasper4e778092013-02-06 10:05:46 +0000510 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
Daniel Jasper01786732013-02-04 07:21:18 +0000511 }
512
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000513 if (CurrentToken != NULL && !CurrentToken->Children.empty())
514 CurrentToken = &CurrentToken->Children[0];
515 else
516 CurrentToken = NULL;
Daniel Jasperd0f349b2013-02-18 12:44:35 +0000517
518 // Reset token type in case we have already looked at it and then recovered
519 // from an error (e.g. failure to find the matching >).
520 if (CurrentToken != NULL)
521 CurrentToken->Type = TT_Unknown;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000522 }
523
Daniel Jasper4e778092013-02-06 10:05:46 +0000524 /// \brief A struct to hold information valid in a specific context, e.g.
525 /// a pair of parenthesis.
526 struct Context {
527 Context(unsigned BindingStrength, bool IsExpression)
528 : BindingStrength(BindingStrength), LongestObjCSelectorName(0),
529 ColonIsForRangeExpr(false), ColonIsObjCMethodExpr(false),
Daniel Jasper3c08a812013-02-24 18:54:32 +0000530 FirstObjCSelectorName(NULL), IsExpression(IsExpression) {}
Daniel Jasper01786732013-02-04 07:21:18 +0000531
Daniel Jasper4e778092013-02-06 10:05:46 +0000532 unsigned BindingStrength;
533 unsigned LongestObjCSelectorName;
534 bool ColonIsForRangeExpr;
535 bool ColonIsObjCMethodExpr;
536 AnnotatedToken *FirstObjCSelectorName;
537 bool IsExpression;
Daniel Jasper4e778092013-02-06 10:05:46 +0000538 };
539
540 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
541 /// of each instance.
542 struct ScopedContextCreator {
543 AnnotatingParser &P;
544
Daniel Jasperfc759082013-02-14 14:26:07 +0000545 ScopedContextCreator(AnnotatingParser &P, unsigned Increase) : P(P) {
546 P.Contexts.push_back(Context(P.Contexts.back().BindingStrength + Increase,
547 P.Contexts.back().IsExpression));
Daniel Jasper4e778092013-02-06 10:05:46 +0000548 }
549
550 ~ScopedContextCreator() { P.Contexts.pop_back(); }
551 };
Daniel Jasper01786732013-02-04 07:21:18 +0000552
553 void determineTokenType(AnnotatedToken &Current) {
554 if (getPrecedence(Current) == prec::Assignment) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000555 Contexts.back().IsExpression = true;
Nico Weber95e8e462013-02-12 16:17:07 +0000556 for (AnnotatedToken *Previous = Current.Parent;
557 Previous && Previous->isNot(tok::comma);
558 Previous = Previous->Parent) {
Daniel Jasper9c65b062013-02-27 11:43:50 +0000559 if (Previous->is(tok::r_square))
560 Previous = Previous->MatchingParen;
Daniel Jasper01786732013-02-04 07:21:18 +0000561 if (Previous->Type == TT_BinaryOperator &&
562 (Previous->is(tok::star) || Previous->is(tok::amp))) {
563 Previous->Type = TT_PointerOrReference;
564 }
Daniel Jasper01786732013-02-04 07:21:18 +0000565 }
Nico Weber95e8e462013-02-12 16:17:07 +0000566 } else if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
567 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
568 (!Current.Parent || Current.Parent->isNot(tok::kw_for)))) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000569 Contexts.back().IsExpression = true;
Nico Weber95e8e462013-02-12 16:17:07 +0000570 } else if (Current.is(tok::r_paren) || Current.is(tok::greater) ||
571 Current.is(tok::comma)) {
572 for (AnnotatedToken *Previous = Current.Parent;
573 Previous && (Previous->is(tok::star) || Previous->is(tok::amp));
574 Previous = Previous->Parent)
575 Previous->Type = TT_PointerOrReference;
Daniel Jasperd0f349b2013-02-18 12:44:35 +0000576 } else if (Current.Parent &&
577 Current.Parent->Type == TT_CtorInitializerColon) {
578 Contexts.back().IsExpression = true;
Nico Weber95e8e462013-02-12 16:17:07 +0000579 }
Daniel Jasper01786732013-02-04 07:21:18 +0000580
581 if (Current.Type == TT_Unknown) {
Daniel Jasper3c08a812013-02-24 18:54:32 +0000582 if (Current.Parent && Current.is(tok::identifier) &&
583 ((Current.Parent->is(tok::identifier) &&
584 Current.Parent->FormatTok.Tok.getIdentifierInfo()
585 ->getPPKeywordID() == tok::pp_not_keyword) ||
586 Current.Parent->Type == TT_PointerOrReference ||
587 Current.Parent->Type == TT_TemplateCloser)) {
588 Current.Type = TT_StartOfName;
Daniel Jasper01786732013-02-04 07:21:18 +0000589 } else if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000590 Current.Type =
591 determineStarAmpUsage(Current, Contexts.back().IsExpression);
Daniel Jasper01786732013-02-04 07:21:18 +0000592 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
593 Current.is(tok::caret)) {
594 Current.Type = determinePlusMinusCaretUsage(Current);
595 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
596 Current.Type = determineIncrementUsage(Current);
597 } else if (Current.is(tok::exclaim)) {
598 Current.Type = TT_UnaryOperator;
599 } else if (isBinaryOperator(Current)) {
600 Current.Type = TT_BinaryOperator;
601 } else if (Current.is(tok::comment)) {
602 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
603 Lex.getLangOpts()));
604 if (StringRef(Data).startswith("//"))
605 Current.Type = TT_LineComment;
606 else
607 Current.Type = TT_BlockComment;
Nico Weber37d69312013-02-13 04:13:13 +0000608 } else if (Current.is(tok::r_paren)) {
Daniel Jasper03628b82013-02-19 20:05:41 +0000609 bool ParensNotExpr = !Current.Parent ||
610 Current.Parent->Type == TT_PointerOrReference ||
Nico Weber37d69312013-02-13 04:13:13 +0000611 Current.Parent->Type == TT_TemplateCloser;
612 bool ParensCouldEndDecl =
613 !Current.Children.empty() && (Current.Children[0].is(tok::equal) ||
614 Current.Children[0].is(tok::semi) ||
615 Current.Children[0].is(tok::l_brace));
Daniel Jasper37eff832013-02-23 08:07:18 +0000616 if (ParensNotExpr && !ParensCouldEndDecl &&
617 Contexts.back().IsExpression)
Nico Weber37d69312013-02-13 04:13:13 +0000618 // FIXME: We need to get smarter and understand more cases of casts.
619 Current.Type = TT_CastRParen;
Daniel Jasper01786732013-02-04 07:21:18 +0000620 } else if (Current.is(tok::at) && Current.Children.size()) {
621 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
622 case tok::objc_interface:
623 case tok::objc_implementation:
624 case tok::objc_protocol:
625 Current.Type = TT_ObjCDecl;
626 break;
627 case tok::objc_property:
628 Current.Type = TT_ObjCProperty;
629 break;
630 default:
631 break;
632 }
633 }
634 }
635 }
636
Daniel Jasper01786732013-02-04 07:21:18 +0000637 /// \brief Return the type of the given token assuming it is * or &.
638 TokenType
639 determineStarAmpUsage(const AnnotatedToken &Tok, bool IsExpression) {
640 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
641 if (PrevToken == NULL)
642 return TT_UnaryOperator;
643
644 const AnnotatedToken *NextToken = getNextToken(Tok);
645 if (NextToken == NULL)
646 return TT_Unknown;
647
Daniel Jasper8a5d7cd2013-03-01 17:13:29 +0000648 if (PrevToken->is(tok::l_paren) && !IsExpression)
649 return TT_PointerOrReference;
650
Daniel Jasper01786732013-02-04 07:21:18 +0000651 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
652 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
653 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
Nico Webere8a97982013-02-06 06:20:11 +0000654 PrevToken->is(tok::equal) || PrevToken->Type == TT_BinaryOperator ||
Daniel Jasper01786732013-02-04 07:21:18 +0000655 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
656 return TT_UnaryOperator;
657
Nico Webere8a97982013-02-06 06:20:11 +0000658 if (NextToken->is(tok::l_square))
659 return TT_PointerOrReference;
660
Daniel Jasper01786732013-02-04 07:21:18 +0000661 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
662 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
Nico Weberee0feec2013-02-05 16:21:00 +0000663 isUnaryOperator(*NextToken) || NextToken->is(tok::l_paren) ||
664 NextToken->is(tok::l_square))
Daniel Jasper01786732013-02-04 07:21:18 +0000665 return TT_BinaryOperator;
666
Daniel Jasper01786732013-02-04 07:21:18 +0000667 // It is very unlikely that we are going to find a pointer or reference type
668 // definition on the RHS of an assignment.
669 if (IsExpression)
670 return TT_BinaryOperator;
671
672 return TT_PointerOrReference;
673 }
674
675 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
676 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
677 if (PrevToken == NULL)
678 return TT_UnaryOperator;
679
680 // Use heuristics to recognize unary operators.
681 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
682 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
683 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
684 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
685 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
686 return TT_UnaryOperator;
687
Nico Weberee0feec2013-02-05 16:21:00 +0000688 // There can't be two consecutive binary operators.
Daniel Jasper01786732013-02-04 07:21:18 +0000689 if (PrevToken->Type == TT_BinaryOperator)
690 return TT_UnaryOperator;
691
692 // Fall back to marking the token as binary operator.
693 return TT_BinaryOperator;
694 }
695
696 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
697 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
698 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
699 if (PrevToken == NULL)
700 return TT_UnaryOperator;
701 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
702 PrevToken->is(tok::identifier))
703 return TT_TrailingUnaryOperator;
704
705 return TT_UnaryOperator;
706 }
Daniel Jasper4e778092013-02-06 10:05:46 +0000707
708 SmallVector<Context, 8> Contexts;
709
710 SourceManager &SourceMgr;
711 Lexer &Lex;
712 AnnotatedLine &Line;
713 AnnotatedToken *CurrentToken;
714 bool KeywordVirtualFound;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000715 IdentifierInfo &Ident_in;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000716};
717
Daniel Jasper29f123b2013-02-08 15:28:42 +0000718/// \brief Parses binary expressions by inserting fake parenthesis based on
719/// operator precedence.
720class ExpressionParser {
721public:
722 ExpressionParser(AnnotatedLine &Line) : Current(&Line.First) {}
723
724 /// \brief Parse expressions with the given operatore precedence.
Daniel Jasper237d4c12013-02-23 21:01:55 +0000725 void parse(int Precedence = 0) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000726 if (Precedence > prec::PointerToMember || Current == NULL)
727 return;
728
729 // Skip over "return" until we can properly parse it.
730 if (Current->is(tok::kw_return))
731 next();
732
733 // Eagerly consume trailing comments.
734 while (isTrailingComment(Current)) {
735 next();
736 }
737
738 AnnotatedToken *Start = Current;
739 bool OperatorFound = false;
740
Daniel Jasper237d4c12013-02-23 21:01:55 +0000741 while (Current) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000742 // Consume operators with higher precedence.
Dmitri Gribenko6ba52aa2013-02-16 20:03:26 +0000743 parse(prec::Level(Precedence + 1));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000744
Daniel Jasper237d4c12013-02-23 21:01:55 +0000745 int CurrentPrecedence = 0;
746 if (Current) {
747 if (Current->Type == TT_ConditionalExpr)
748 CurrentPrecedence = 1 + (int) prec::Conditional;
749 else if (Current->is(tok::semi))
750 CurrentPrecedence = 1;
751 else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
752 CurrentPrecedence = 1 + (int) getPrecedence(*Current);
753 }
754
Daniel Jasper29f123b2013-02-08 15:28:42 +0000755 // At the end of the line or when an operator with higher precedence is
756 // found, insert fake parenthesis and return.
Daniel Jasper237d4c12013-02-23 21:01:55 +0000757 if (Current == NULL || closesScope(*Current) ||
758 (CurrentPrecedence != 0 && CurrentPrecedence < Precedence)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000759 if (OperatorFound) {
760 ++Start->FakeLParens;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000761 if (Current)
Daniel Jasper087387a2013-02-08 16:49:27 +0000762 ++Current->Parent->FakeRParens;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000763 }
764 return;
765 }
766
767 // Consume scopes: (), [], <> and {}
768 if (opensScope(*Current)) {
Daniel Jasper237d4c12013-02-23 21:01:55 +0000769 AnnotatedToken *Left = Current;
770 while (Current && !closesScope(*Current)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000771 next();
772 parse();
773 }
Daniel Jasper237d4c12013-02-23 21:01:55 +0000774 // Remove fake parens that just duplicate the real parens.
775 if (Current && Left->Children[0].FakeLParens > 0 &&
776 Current->Parent->FakeRParens > 0) {
777 --Left->Children[0].FakeLParens;
778 --Current->Parent->FakeRParens;
779 }
Daniel Jasper29f123b2013-02-08 15:28:42 +0000780 next();
781 } else {
782 // Operator found.
Daniel Jasper237d4c12013-02-23 21:01:55 +0000783 if (CurrentPrecedence == Precedence)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000784 OperatorFound = true;
785
786 next();
787 }
788 }
789 }
790
791private:
792 void next() {
793 if (Current != NULL)
794 Current = Current->Children.empty() ? NULL : &Current->Children[0];
795 }
796
797 bool closesScope(const AnnotatedToken &Tok) {
798 return Current->is(tok::r_paren) || Current->Type == TT_TemplateCloser ||
799 Current->is(tok::r_brace) || Current->is(tok::r_square);
800 }
801
802 bool opensScope(const AnnotatedToken &Tok) {
803 return Current->is(tok::l_paren) || Current->Type == TT_TemplateOpener ||
804 Current->is(tok::l_brace) || Current->is(tok::l_square);
805 }
806
807 AnnotatedToken *Current;
808};
809
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000810void TokenAnnotator::annotate(AnnotatedLine &Line) {
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000811 AnnotatingParser Parser(SourceMgr, Lex, Line, Ident_in);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000812 Line.Type = Parser.parseLine();
813 if (Line.Type == LT_Invalid)
814 return;
815
Daniel Jasper29f123b2013-02-08 15:28:42 +0000816 ExpressionParser ExprParser(Line);
817 ExprParser.parse();
818
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000819 if (Line.First.Type == TT_ObjCMethodSpecifier)
820 Line.Type = LT_ObjCMethodDecl;
821 else if (Line.First.Type == TT_ObjCDecl)
822 Line.Type = LT_ObjCDecl;
823 else if (Line.First.Type == TT_ObjCProperty)
824 Line.Type = LT_ObjCProperty;
825
Daniel Jasper729a7432013-02-11 12:36:37 +0000826 Line.First.SpacesRequiredBefore = 1;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000827 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
828 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
829
830 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000831}
832
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000833void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
834 if (Line.First.Children.empty())
835 return;
836 AnnotatedToken *Current = &Line.First.Children[0];
837 while (Current != NULL) {
Daniel Jasper729a7432013-02-11 12:36:37 +0000838 if (Current->Type == TT_LineComment)
839 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
840 else
841 Current->SpacesRequiredBefore =
842 spaceRequiredBefore(Line, *Current) ? 1 : 0;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000843
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000844 if (Current->FormatTok.MustBreakBefore) {
845 Current->MustBreakBefore = true;
846 } else if (Current->Type == TT_LineComment) {
847 Current->MustBreakBefore = Current->FormatTok.NewlinesBefore > 0;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000848 } else if (isTrailingComment(Current->Parent) ||
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000849 (Current->is(tok::string_literal) &&
850 Current->Parent->is(tok::string_literal))) {
851 Current->MustBreakBefore = true;
852 } else if (Current->is(tok::lessless) && !Current->Children.empty() &&
853 Current->Parent->is(tok::string_literal) &&
854 Current->Children[0].is(tok::string_literal)) {
855 Current->MustBreakBefore = true;
856 } else {
857 Current->MustBreakBefore = false;
858 }
859 Current->CanBreakBefore =
860 Current->MustBreakBefore || canBreakBefore(Line, *Current);
861 if (Current->MustBreakBefore)
862 Current->TotalLength = Current->Parent->TotalLength + Style.ColumnLimit;
863 else
864 Current->TotalLength =
865 Current->Parent->TotalLength + Current->FormatTok.TokenLength +
Daniel Jasper729a7432013-02-11 12:36:37 +0000866 Current->SpacesRequiredBefore;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000867 // FIXME: Only calculate this if CanBreakBefore is true once static
868 // initializers etc. are sorted out.
869 // FIXME: Move magic numbers to a better place.
870 Current->SplitPenalty =
871 20 * Current->BindingStrength + splitPenalty(Line, *Current);
872
873 Current = Current->Children.empty() ? NULL : &Current->Children[0];
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000874 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000875}
876
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000877unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
878 const AnnotatedToken &Tok) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000879 const AnnotatedToken &Left = *Tok.Parent;
880 const AnnotatedToken &Right = Tok;
881
Daniel Jasper3c08a812013-02-24 18:54:32 +0000882 if (Right.Type == TT_StartOfName) {
883 if (Line.First.is(tok::kw_for))
884 return 3;
885 else if (Line.MightBeFunctionDecl && Right.BindingStrength == 1)
886 // FIXME: Clean up hack of using BindingStrength to find top-level names.
887 return Style.PenaltyReturnTypeOnItsOwnLine;
888 else
889 return 100;
890 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000891 if (Left.is(tok::equal) && Right.is(tok::l_brace))
892 return 150;
893 if (Left.is(tok::coloncolon))
894 return 500;
895
Daniel Jasper6cabab42013-02-14 08:42:54 +0000896 if (Left.Type == TT_RangeBasedForLoopColon ||
897 Left.Type == TT_InheritanceColon)
Daniel Jasper84a1a632013-02-26 13:18:08 +0000898 return 2;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000899
900 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper515f65d2013-02-18 13:24:21 +0000901 if (Line.Type == LT_BuilderTypeCall)
Daniel Jasper518ee342013-02-26 13:59:14 +0000902 return 5;
Daniel Jasperfc759082013-02-14 14:26:07 +0000903 if ((Left.is(tok::r_paren) || Left.is(tok::r_square)) &&
904 Left.MatchingParen && Left.MatchingParen->ParameterCount > 0)
Daniel Jasper518ee342013-02-26 13:59:14 +0000905 return 20; // Should be smaller than breaking at a nested comma.
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000906 return 150;
907 }
908
909 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7d812812013-02-21 15:00:29 +0000910 if (Line.First.is(tok::kw_for) && Left.is(tok::equal))
911 return 4;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000912
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000913 if (Left.is(tok::semi))
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000914 return 0;
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000915 if (Left.is(tok::comma))
916 return 1;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000917
918 // In Objective-C method expressions, prefer breaking before "param:" over
919 // breaking after it.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000920 if (Right.Type == TT_ObjCSelectorName)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000921 return 0;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000922 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000923 return 20;
924
Daniel Jasper01786732013-02-04 07:21:18 +0000925 if (Left.is(tok::l_paren) || Left.is(tok::l_square) ||
Daniel Jasper25e81b22013-02-28 15:04:12 +0000926 Left.is(tok::l_brace) || Left.Type == TT_TemplateOpener)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000927 return 20;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000928
Daniel Jasper4e8a7b42013-02-06 21:04:05 +0000929 if (Right.is(tok::lessless)) {
930 if (Left.is(tok::string_literal)) {
931 char LastChar =
932 StringRef(Left.FormatTok.Tok.getLiteralData(),
933 Left.FormatTok.TokenLength).drop_back(1).rtrim().back();
934 if (LastChar == ':' || LastChar == '=')
935 return 100;
936 }
Daniel Jasper01786732013-02-04 07:21:18 +0000937 return prec::Shift;
Daniel Jasper4e8a7b42013-02-06 21:04:05 +0000938 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000939 if (Left.Type == TT_ConditionalExpr)
Daniel Jasper518ee342013-02-26 13:59:14 +0000940 return prec::Conditional;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000941 prec::Level Level = getPrecedence(Left);
942
943 if (Level != prec::Unknown)
944 return Level;
Daniel Jasper24849712013-03-01 16:48:32 +0000945
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000946 return 3;
947}
948
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000949bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
950 const AnnotatedToken &Left,
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000951 const AnnotatedToken &Right) {
952 if (Right.is(tok::hashhash))
953 return Left.is(tok::hash);
954 if (Left.is(tok::hashhash) || Left.is(tok::hash))
955 return Right.is(tok::hash);
956 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
957 return false;
958 if (Right.is(tok::less) &&
959 (Left.is(tok::kw_template) ||
960 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
961 return true;
962 if (Left.is(tok::arrow) || Right.is(tok::arrow))
963 return false;
964 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
965 return false;
966 if (Left.is(tok::at) &&
967 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
968 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
969 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
970 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
971 return false;
972 if (Left.is(tok::coloncolon))
973 return false;
974 if (Right.is(tok::coloncolon))
Daniel Jasperdaf1a152013-02-07 21:08:36 +0000975 return Left.isNot(tok::identifier) && Left.isNot(tok::greater) &&
976 Left.isNot(tok::l_paren);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000977 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
978 return false;
979 if (Right.is(tok::amp) || Right.is(tok::star))
980 return Left.FormatTok.Tok.isLiteral() ||
981 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
Nico Weber95e8e462013-02-12 16:17:07 +0000982 Left.isNot(tok::l_paren) && !Style.PointerBindsToType);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000983 if (Left.is(tok::amp) || Left.is(tok::star))
Nico Weber95e8e462013-02-12 16:17:07 +0000984 return Right.FormatTok.Tok.isLiteral() ||
985 (Right.isNot(tok::star) && Right.isNot(tok::amp) &&
986 Style.PointerBindsToType);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000987 if (Right.is(tok::star) && Left.is(tok::l_paren))
988 return false;
Nico Weber051860e2013-02-10 02:08:05 +0000989 if (Left.is(tok::l_square))
990 return Left.Type == TT_ObjCArrayLiteral && Right.isNot(tok::r_square);
991 if (Right.is(tok::r_square))
992 return Right.Type == TT_ObjCArrayLiteral;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000993 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
994 return false;
995 if (Left.is(tok::period) || Right.is(tok::period))
996 return false;
997 if (Left.is(tok::colon))
998 return Left.Type != TT_ObjCMethodExpr;
999 if (Right.is(tok::colon))
1000 return Right.Type != TT_ObjCMethodExpr;
1001 if (Left.is(tok::l_paren))
1002 return false;
1003 if (Right.is(tok::l_paren)) {
1004 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
1005 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
1006 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
1007 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1008 Left.is(tok::kw_delete);
1009 }
1010 if (Left.is(tok::at) &&
1011 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1012 return false;
1013 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1014 return false;
1015 return true;
1016}
1017
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001018bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1019 const AnnotatedToken &Tok) {
Daniel Jasper2b4c9242013-02-11 08:01:18 +00001020 if (Tok.FormatTok.Tok.getIdentifierInfo() &&
1021 Tok.Parent->FormatTok.Tok.getIdentifierInfo())
1022 return true; // Never ever merge two identifiers.
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001023 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001024 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
1025 return true;
1026 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
1027 // Don't space between ')' and <id>
1028 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001029 }
1030 if (Line.Type == LT_ObjCProperty &&
1031 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1032 return false;
1033
1034 if (Tok.Parent->is(tok::comma))
1035 return true;
Daniel Jasper9c3c7b32013-02-28 13:40:17 +00001036 if (Tok.is(tok::comma))
1037 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001038 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
1039 return true;
Daniel Jasper2b4c9242013-02-11 08:01:18 +00001040 if (Tok.Parent->FormatTok.Tok.is(tok::kw_operator))
1041 return false;
1042 if (Tok.Type == TT_OverloadedOperatorLParen)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001043 return false;
1044 if (Tok.is(tok::colon))
1045 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
1046 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper8a5d7cd2013-03-01 17:13:29 +00001047 if (Tok.is(tok::l_paren) && !Tok.Children.empty() &&
1048 Tok.Children[0].Type == TT_PointerOrReference &&
1049 !Tok.Children[0].Children.empty() &&
1050 Tok.Children[0].Children[0].isNot(tok::r_paren))
1051 return true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001052 if (Tok.Parent->Type == TT_UnaryOperator || Tok.Parent->Type == TT_CastRParen)
1053 return false;
1054 if (Tok.Type == TT_UnaryOperator)
1055 return Tok.Parent->isNot(tok::l_paren) &&
1056 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1057 (Tok.Parent->isNot(tok::colon) ||
1058 Tok.Parent->Type != TT_ObjCMethodExpr);
1059 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +00001060 return Tok.Type == TT_TemplateCloser &&
1061 Tok.Parent->Type == TT_TemplateCloser &&
1062 Style.Standard != FormatStyle::LS_Cpp11;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001063 }
Daniel Jasper9c3c7b32013-02-28 13:40:17 +00001064 if (Tok.is(tok::arrowstar) || Tok.Parent->is(tok::arrowstar))
1065 return false;
1066 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001067 return true;
1068 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
1069 return false;
1070 if (Tok.is(tok::less) && Line.First.is(tok::hash))
1071 return true;
1072 if (Tok.Type == TT_TrailingUnaryOperator)
1073 return false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001074 return spaceRequiredBetween(Line, *Tok.Parent, Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001075}
1076
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001077bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
1078 const AnnotatedToken &Right) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001079 const AnnotatedToken &Left = *Right.Parent;
Daniel Jaspera03ab102013-02-13 20:33:44 +00001080 if (Right.Type == TT_StartOfName)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001081 return true;
1082 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1083 return false;
1084 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1085 return true;
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001086 if (Right.Type == TT_ObjCSelectorName)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001087 return true;
1088 if (Left.ClosesTemplateDeclaration)
1089 return true;
1090 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1091 return true;
Daniel Jasper6cabab42013-02-14 08:42:54 +00001092 if (Right.Type == TT_RangeBasedForLoopColon ||
1093 Right.Type == TT_InheritanceColon)
1094 return false;
1095 if (Left.Type == TT_RangeBasedForLoopColon ||
1096 Left.Type == TT_InheritanceColon)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001097 return true;
Daniel Jasper7d812812013-02-21 15:00:29 +00001098 if (Right.Type == TT_RangeBasedForLoopColon)
1099 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001100 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
1101 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
Daniel Jasperdc2efa12013-02-15 19:24:08 +00001102 Left.is(tok::question) || Left.is(tok::kw_operator))
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001103 return false;
1104 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
1105 return false;
Daniel Jasper8ed41002013-02-28 14:44:25 +00001106 if (Left.is(tok::l_paren) && Right.is(tok::l_paren) && Left.Parent &&
1107 Left.Parent->is(tok::kw___attribute))
1108 return false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001109
1110 if (Right.Type == TT_LineComment)
1111 // We rely on MustBreakBefore being set correctly here as we should not
1112 // change the "binding" behavior of a comment.
1113 return false;
1114
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001115 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1116 // unless it is follow by ';', '{' or '='.
1117 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1118 Left.Parent->is(tok::r_paren))
1119 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1120 Right.isNot(tok::equal);
1121
1122 // We only break before r_brace if there was a corresponding break before
1123 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1124 if (Right.is(tok::r_brace))
1125 return false;
1126
1127 if (Right.is(tok::r_paren) || Right.is(tok::greater))
1128 return false;
Daniel Jasper3a204412013-02-23 07:46:38 +00001129 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
1130 return true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001131 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1132 Left.is(tok::comma) || Right.is(tok::lessless) ||
1133 Right.is(tok::arrow) || Right.is(tok::period) ||
1134 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1135 Left.is(tok::semi) || Left.is(tok::l_brace) ||
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001136 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
Daniel Jasper8ed41002013-02-28 14:44:25 +00001137 (Right.is(tok::identifier) || Right.is(tok::kw___attribute))) ||
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001138 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1139 (Left.is(tok::l_square) && !Right.is(tok::r_square));
1140}
1141
1142} // namespace format
1143} // namespace clang