blob: db059018c26fc1900b241520f9dd75dbb88eccf1 [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:
Daniel Jasper01786732013-02-04 07:21:18 +000081 AnnotatingParser(SourceManager &SourceMgr, Lexer &Lex, AnnotatedLine &Line)
82 : SourceMgr(SourceMgr), Lex(Lex), Line(Line), CurrentToken(&Line.First),
Daniel Jasper4e778092013-02-06 10:05:46 +000083 KeywordVirtualFound(false) {
84 Contexts.push_back(Context(1, /*IsExpression=*/ false));
85 Contexts.back().LookForFunctionName = Line.MustBeDeclaration;
Daniel Jasper32d28ee2013-01-29 21:01:14 +000086 }
87
Daniel Jasper32d28ee2013-01-29 21:01:14 +000088 bool parseAngle() {
89 if (CurrentToken == NULL)
90 return false;
Daniel Jasper4e778092013-02-06 10:05:46 +000091 ScopedContextCreator ContextCreator(*this, 10);
Daniel Jasper32d28ee2013-01-29 21:01:14 +000092 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper4e778092013-02-06 10:05:46 +000093 Contexts.back().IsExpression = false;
Daniel Jasper32d28ee2013-01-29 21:01:14 +000094 while (CurrentToken != NULL) {
95 if (CurrentToken->is(tok::greater)) {
96 Left->MatchingParen = CurrentToken;
97 CurrentToken->MatchingParen = Left;
98 CurrentToken->Type = TT_TemplateCloser;
99 next();
100 return true;
101 }
102 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
103 CurrentToken->is(tok::r_brace))
104 return false;
105 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
106 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
107 return false;
108 if (CurrentToken->is(tok::comma))
109 ++Left->ParameterCount;
110 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;
176 if (CurrentToken->is(tok::comma))
177 ++Left->ParameterCount;
178 if (!consumeToken())
179 return false;
180 }
181 return false;
182 }
183
184 bool parseSquare() {
185 if (!CurrentToken)
186 return false;
Daniel Jasper4e778092013-02-06 10:05:46 +0000187 ScopedContextCreator ContextCreator(*this, 10);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000188
189 // A '[' could be an index subscript (after an indentifier or after
190 // ')' or ']'), or it could be the start of an Objective-C method
191 // expression.
192 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber4ed7f3e2013-02-06 16:54:35 +0000193 AnnotatedToken *Parent = getPreviousToken(*Left);
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) ||
198 getBinOpPrecedence(Parent->FormatTok.Tok.getKind(), true, true) >
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000199 prec::Unknown;
200
Daniel Jasper4e778092013-02-06 10:05:46 +0000201 if (StartsObjCMethodExpr) {
202 Contexts.back().ColonIsObjCMethodExpr = true;
203 Left->Type = TT_ObjCMethodExpr;
204 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000205
206 while (CurrentToken != NULL) {
207 if (CurrentToken->is(tok::r_square)) {
208 if (!CurrentToken->Children.empty() &&
209 CurrentToken->Children[0].is(tok::l_paren)) {
Nico Webere8a97982013-02-06 06:20:11 +0000210 // An ObjC method call is rarely followed by an open parenthesis.
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000211 // FIXME: Do we incorrectly label ":" with this?
212 StartsObjCMethodExpr = false;
213 Left->Type = TT_Unknown;
214 }
Daniel Jasper01786732013-02-04 07:21:18 +0000215 if (StartsObjCMethodExpr) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000216 CurrentToken->Type = TT_ObjCMethodExpr;
Nico Webere8a97982013-02-06 06:20:11 +0000217 // determineStarAmpUsage() thinks that '*' '[' is allocating an
218 // array of pointers, but if '[' starts a selector then '*' is a
219 // binary operator.
Nico Weber4ed7f3e2013-02-06 16:54:35 +0000220 if (Parent != NULL &&
221 (Parent->is(tok::star) || Parent->is(tok::amp)) &&
222 Parent->Type == TT_PointerOrReference)
223 Parent->Type = TT_BinaryOperator;
Daniel Jasper01786732013-02-04 07:21:18 +0000224 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000225 Left->MatchingParen = CurrentToken;
226 CurrentToken->MatchingParen = Left;
Daniel Jasper4e778092013-02-06 10:05:46 +0000227 if (Contexts.back().FirstObjCSelectorName != NULL)
228 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
229 Contexts.back().LongestObjCSelectorName;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000230 next();
231 return true;
232 }
233 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
234 return false;
235 if (CurrentToken->is(tok::comma))
236 ++Left->ParameterCount;
237 if (!consumeToken())
238 return false;
239 }
240 return false;
241 }
242
243 bool parseBrace() {
244 // Lines are fine to end with '{'.
245 if (CurrentToken == NULL)
246 return true;
Daniel Jasper4e778092013-02-06 10:05:46 +0000247 ScopedContextCreator ContextCreator(*this, 1);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000248 AnnotatedToken *Left = CurrentToken->Parent;
249 while (CurrentToken != NULL) {
250 if (CurrentToken->is(tok::r_brace)) {
251 Left->MatchingParen = CurrentToken;
252 CurrentToken->MatchingParen = Left;
253 next();
254 return true;
255 }
256 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
257 return false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000258 if (CurrentToken->is(tok::comma))
259 ++Left->ParameterCount;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000260 if (!consumeToken())
261 return false;
262 }
263 return true;
264 }
265
266 bool parseConditional() {
267 while (CurrentToken != NULL) {
268 if (CurrentToken->is(tok::colon)) {
269 CurrentToken->Type = TT_ConditionalExpr;
270 next();
271 return true;
272 }
273 if (!consumeToken())
274 return false;
275 }
276 return false;
277 }
278
279 bool parseTemplateDeclaration() {
280 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
281 CurrentToken->Type = TT_TemplateOpener;
282 next();
283 if (!parseAngle())
284 return false;
285 CurrentToken->Parent->ClosesTemplateDeclaration = true;
286 return true;
287 }
288 return false;
289 }
290
291 bool consumeToken() {
292 AnnotatedToken *Tok = CurrentToken;
293 next();
294 switch (Tok->FormatTok.Tok.getKind()) {
295 case tok::plus:
296 case tok::minus:
297 // At the start of the line, +/- specific ObjectiveC method
298 // declarations.
299 if (Tok->Parent == NULL)
300 Tok->Type = TT_ObjCMethodSpecifier;
301 break;
302 case tok::colon:
303 // Colons from ?: are handled in parseConditional().
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000304 if (Tok->Parent->is(tok::r_paren)) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000305 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper4e778092013-02-06 10:05:46 +0000306 } else if (Contexts.back().ColonIsObjCMethodExpr ||
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000307 Line.First.Type == TT_ObjCMethodSpecifier) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000308 Tok->Type = TT_ObjCMethodExpr;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000309 Tok->Parent->Type = TT_ObjCSelectorName;
Daniel Jasper4e778092013-02-06 10:05:46 +0000310 if (Tok->Parent->FormatTok.TokenLength >
311 Contexts.back().LongestObjCSelectorName)
312 Contexts.back().LongestObjCSelectorName =
313 Tok->Parent->FormatTok.TokenLength;
314 if (Contexts.back().FirstObjCSelectorName == NULL)
315 Contexts.back().FirstObjCSelectorName = Tok->Parent;
316 } else if (Contexts.back().ColonIsForRangeExpr) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000317 Tok->Type = TT_RangeBasedForLoopColon;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000318 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000319 break;
320 case tok::kw_if:
321 case tok::kw_while:
322 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
323 next();
324 if (!parseParens(/*LookForDecls=*/ true))
325 return false;
326 }
327 break;
328 case tok::kw_for:
Daniel Jasper4e778092013-02-06 10:05:46 +0000329 Contexts.back().ColonIsForRangeExpr = true;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000330 next();
331 if (!parseParens())
332 return false;
333 break;
334 case tok::l_paren:
335 if (!parseParens())
336 return false;
337 break;
338 case tok::l_square:
339 if (!parseSquare())
340 return false;
341 break;
342 case tok::l_brace:
343 if (!parseBrace())
344 return false;
345 break;
346 case tok::less:
347 if (parseAngle())
348 Tok->Type = TT_TemplateOpener;
349 else {
350 Tok->Type = TT_BinaryOperator;
351 CurrentToken = Tok;
352 next();
353 }
354 break;
355 case tok::r_paren:
356 case tok::r_square:
357 return false;
358 case tok::r_brace:
359 // Lines can start with '}'.
360 if (Tok->Parent != NULL)
361 return false;
362 break;
363 case tok::greater:
364 Tok->Type = TT_BinaryOperator;
365 break;
366 case tok::kw_operator:
367 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
368 CurrentToken->Type = TT_OverloadedOperator;
369 next();
370 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
371 CurrentToken->Type = TT_OverloadedOperator;
372 next();
373 }
374 } else {
375 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
376 CurrentToken->Type = TT_OverloadedOperator;
377 next();
378 }
379 }
380 break;
381 case tok::question:
382 parseConditional();
383 break;
384 case tok::kw_template:
385 parseTemplateDeclaration();
386 break;
387 default:
388 break;
389 }
390 return true;
391 }
392
393 void parseIncludeDirective() {
394 next();
395 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
396 next();
397 while (CurrentToken != NULL) {
398 if (CurrentToken->isNot(tok::comment) ||
399 !CurrentToken->Children.empty())
400 CurrentToken->Type = TT_ImplicitStringLiteral;
401 next();
402 }
403 } else {
404 while (CurrentToken != NULL) {
405 next();
406 }
407 }
408 }
409
410 void parseWarningOrError() {
411 next();
412 // We still want to format the whitespace left of the first token of the
413 // warning or error.
414 next();
415 while (CurrentToken != NULL) {
416 CurrentToken->Type = TT_ImplicitStringLiteral;
417 next();
418 }
419 }
420
421 void parsePreprocessorDirective() {
422 next();
423 if (CurrentToken == NULL)
424 return;
425 // Hashes in the middle of a line can lead to any strange token
426 // sequence.
427 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
428 return;
429 switch (CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
430 case tok::pp_include:
431 case tok::pp_import:
432 parseIncludeDirective();
433 break;
434 case tok::pp_error:
435 case tok::pp_warning:
436 parseWarningOrError();
437 break;
438 default:
439 break;
440 }
Daniel Jasper5b7e7b02013-02-05 09:34:14 +0000441 while (CurrentToken != NULL)
442 next();
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000443 }
444
445 LineType parseLine() {
446 int PeriodsAndArrows = 0;
447 bool CanBeBuilderTypeStmt = true;
448 if (CurrentToken->is(tok::hash)) {
449 parsePreprocessorDirective();
450 return LT_PreprocessorDirective;
451 }
452 while (CurrentToken != NULL) {
453 if (CurrentToken->is(tok::kw_virtual))
454 KeywordVirtualFound = true;
455 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
456 ++PeriodsAndArrows;
457 if (getPrecedence(*CurrentToken) > prec::Assignment &&
458 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
459 CanBeBuilderTypeStmt = false;
460 if (!consumeToken())
461 return LT_Invalid;
462 }
463 if (KeywordVirtualFound)
464 return LT_VirtualFunctionDecl;
465
466 // Assume a builder-type call if there are 2 or more "." and "->".
467 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
468 return LT_BuilderTypeCall;
469
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000470 if (Line.First.Type == TT_ObjCMethodSpecifier) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000471 if (Contexts.back().FirstObjCSelectorName != NULL)
472 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
473 Contexts.back().LongestObjCSelectorName;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000474 return LT_ObjCMethodDecl;
475 }
476
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000477 return LT_Other;
478 }
479
480 void next() {
Daniel Jasper01786732013-02-04 07:21:18 +0000481 if (CurrentToken != NULL) {
482 determineTokenType(*CurrentToken);
Daniel Jasper4e778092013-02-06 10:05:46 +0000483 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
Daniel Jasper01786732013-02-04 07:21:18 +0000484 }
485
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000486 if (CurrentToken != NULL && !CurrentToken->Children.empty())
487 CurrentToken = &CurrentToken->Children[0];
488 else
489 CurrentToken = NULL;
490 }
491
492private:
Daniel Jasper4e778092013-02-06 10:05:46 +0000493 /// \brief A struct to hold information valid in a specific context, e.g.
494 /// a pair of parenthesis.
495 struct Context {
496 Context(unsigned BindingStrength, bool IsExpression)
497 : BindingStrength(BindingStrength), LongestObjCSelectorName(0),
498 ColonIsForRangeExpr(false), ColonIsObjCMethodExpr(false),
499 FirstObjCSelectorName(NULL), IsExpression(IsExpression),
500 LookForFunctionName(false) {
501 }
Daniel Jasper01786732013-02-04 07:21:18 +0000502
Daniel Jasper4e778092013-02-06 10:05:46 +0000503 unsigned BindingStrength;
504 unsigned LongestObjCSelectorName;
505 bool ColonIsForRangeExpr;
506 bool ColonIsObjCMethodExpr;
507 AnnotatedToken *FirstObjCSelectorName;
508 bool IsExpression;
509 bool LookForFunctionName;
510 };
511
512 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
513 /// of each instance.
514 struct ScopedContextCreator {
515 AnnotatingParser &P;
516
517 ScopedContextCreator(AnnotatingParser &P, unsigned Increase)
518 : P(P) {
519 P.Contexts.push_back(Context(
520 P.Contexts.back().BindingStrength + Increase,
521 P.Contexts.back().IsExpression));
522 }
523
524 ~ScopedContextCreator() { P.Contexts.pop_back(); }
525 };
Daniel Jasper01786732013-02-04 07:21:18 +0000526
527 void determineTokenType(AnnotatedToken &Current) {
528 if (getPrecedence(Current) == prec::Assignment) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000529 Contexts.back().IsExpression = true;
Daniel Jasper01786732013-02-04 07:21:18 +0000530 AnnotatedToken *Previous = Current.Parent;
Daniel Jasper6b5ba8b2013-02-06 10:57:42 +0000531 while (Previous != NULL && Previous->isNot(tok::comma)) {
Daniel Jasper01786732013-02-04 07:21:18 +0000532 if (Previous->Type == TT_BinaryOperator &&
533 (Previous->is(tok::star) || Previous->is(tok::amp))) {
534 Previous->Type = TT_PointerOrReference;
535 }
536 Previous = Previous->Parent;
537 }
538 }
539 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
540 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
541 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper4e778092013-02-06 10:05:46 +0000542 Contexts.back().IsExpression = true;
Daniel Jasper01786732013-02-04 07:21:18 +0000543
544 if (Current.Type == TT_Unknown) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000545 if (Contexts.back().LookForFunctionName && Current.is(tok::l_paren)) {
Daniel Jasper01786732013-02-04 07:21:18 +0000546 findFunctionName(&Current);
Daniel Jasper4e778092013-02-06 10:05:46 +0000547 Contexts.back().LookForFunctionName = false;
Daniel Jasper01786732013-02-04 07:21:18 +0000548 } else if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper4e778092013-02-06 10:05:46 +0000549 Current.Type =
550 determineStarAmpUsage(Current, Contexts.back().IsExpression);
Daniel Jasper01786732013-02-04 07:21:18 +0000551 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
552 Current.is(tok::caret)) {
553 Current.Type = determinePlusMinusCaretUsage(Current);
554 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
555 Current.Type = determineIncrementUsage(Current);
556 } else if (Current.is(tok::exclaim)) {
557 Current.Type = TT_UnaryOperator;
558 } else if (isBinaryOperator(Current)) {
559 Current.Type = TT_BinaryOperator;
560 } else if (Current.is(tok::comment)) {
561 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
562 Lex.getLangOpts()));
563 if (StringRef(Data).startswith("//"))
564 Current.Type = TT_LineComment;
565 else
566 Current.Type = TT_BlockComment;
567 } else if (Current.is(tok::r_paren) &&
568 (Current.Parent->Type == TT_PointerOrReference ||
569 Current.Parent->Type == TT_TemplateCloser) &&
570 (Current.Children.empty() ||
571 (Current.Children[0].isNot(tok::equal) &&
572 Current.Children[0].isNot(tok::semi) &&
573 Current.Children[0].isNot(tok::l_brace)))) {
574 // FIXME: We need to get smarter and understand more cases of casts.
575 Current.Type = TT_CastRParen;
576 } else if (Current.is(tok::at) && Current.Children.size()) {
577 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
578 case tok::objc_interface:
579 case tok::objc_implementation:
580 case tok::objc_protocol:
581 Current.Type = TT_ObjCDecl;
582 break;
583 case tok::objc_property:
584 Current.Type = TT_ObjCProperty;
585 break;
586 default:
587 break;
588 }
589 }
590 }
591 }
592
593 /// \brief Starting from \p Current, this searches backwards for an
594 /// identifier which could be the start of a function name and marks it.
595 void findFunctionName(AnnotatedToken *Current) {
596 AnnotatedToken *Parent = Current->Parent;
597 while (Parent != NULL && Parent->Parent != NULL) {
598 if (Parent->is(tok::identifier) &&
599 (Parent->Parent->is(tok::identifier) ||
600 Parent->Parent->Type == TT_PointerOrReference ||
601 Parent->Parent->Type == TT_TemplateCloser)) {
602 Parent->Type = TT_StartOfName;
603 break;
604 }
605 Parent = Parent->Parent;
606 }
607 }
608
609 /// \brief Return the type of the given token assuming it is * or &.
610 TokenType
611 determineStarAmpUsage(const AnnotatedToken &Tok, bool IsExpression) {
612 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
613 if (PrevToken == NULL)
614 return TT_UnaryOperator;
615
616 const AnnotatedToken *NextToken = getNextToken(Tok);
617 if (NextToken == NULL)
618 return TT_Unknown;
619
Daniel Jasper01786732013-02-04 07:21:18 +0000620 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
621 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
622 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
Nico Webere8a97982013-02-06 06:20:11 +0000623 PrevToken->is(tok::equal) || PrevToken->Type == TT_BinaryOperator ||
Daniel Jasper01786732013-02-04 07:21:18 +0000624 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
625 return TT_UnaryOperator;
626
Nico Webere8a97982013-02-06 06:20:11 +0000627 if (NextToken->is(tok::l_square))
628 return TT_PointerOrReference;
629
Daniel Jasper01786732013-02-04 07:21:18 +0000630 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
631 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
Nico Weberee0feec2013-02-05 16:21:00 +0000632 isUnaryOperator(*NextToken) || NextToken->is(tok::l_paren) ||
633 NextToken->is(tok::l_square))
Daniel Jasper01786732013-02-04 07:21:18 +0000634 return TT_BinaryOperator;
635
636 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
637 NextToken->is(tok::greater))
638 return TT_PointerOrReference;
639
640 // It is very unlikely that we are going to find a pointer or reference type
641 // definition on the RHS of an assignment.
642 if (IsExpression)
643 return TT_BinaryOperator;
644
645 return TT_PointerOrReference;
646 }
647
648 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
649 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
650 if (PrevToken == NULL)
651 return TT_UnaryOperator;
652
653 // Use heuristics to recognize unary operators.
654 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
655 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
656 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
657 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
658 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
659 return TT_UnaryOperator;
660
Nico Weberee0feec2013-02-05 16:21:00 +0000661 // There can't be two consecutive binary operators.
Daniel Jasper01786732013-02-04 07:21:18 +0000662 if (PrevToken->Type == TT_BinaryOperator)
663 return TT_UnaryOperator;
664
665 // Fall back to marking the token as binary operator.
666 return TT_BinaryOperator;
667 }
668
669 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
670 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
671 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
672 if (PrevToken == NULL)
673 return TT_UnaryOperator;
674 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
675 PrevToken->is(tok::identifier))
676 return TT_TrailingUnaryOperator;
677
678 return TT_UnaryOperator;
679 }
Daniel Jasper4e778092013-02-06 10:05:46 +0000680
681 SmallVector<Context, 8> Contexts;
682
683 SourceManager &SourceMgr;
684 Lexer &Lex;
685 AnnotatedLine &Line;
686 AnnotatedToken *CurrentToken;
687 bool KeywordVirtualFound;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000688};
689
Daniel Jasper29f123b2013-02-08 15:28:42 +0000690/// \brief Parses binary expressions by inserting fake parenthesis based on
691/// operator precedence.
692class ExpressionParser {
693public:
694 ExpressionParser(AnnotatedLine &Line) : Current(&Line.First) {}
695
696 /// \brief Parse expressions with the given operatore precedence.
697 void parse(unsigned Precedence = prec::Unknown) {
698 if (Precedence > prec::PointerToMember || Current == NULL)
699 return;
700
701 // Skip over "return" until we can properly parse it.
702 if (Current->is(tok::kw_return))
703 next();
704
705 // Eagerly consume trailing comments.
706 while (isTrailingComment(Current)) {
707 next();
708 }
709
710 AnnotatedToken *Start = Current;
711 bool OperatorFound = false;
712
713 while (Current != NULL) {
714 // Consume operators with higher precedence.
715 parse(Precedence + 1);
716
717 // At the end of the line or when an operator with higher precedence is
718 // found, insert fake parenthesis and return.
719 if (Current == NULL || Current->is(tok::semi) || closesScope(*Current) ||
720 ((Current->Type == TT_BinaryOperator || Current->is(tok::comma)) &&
721 getPrecedence(*Current) < Precedence)) {
722 if (OperatorFound) {
723 ++Start->FakeLParens;
724 if (Current != NULL)
Daniel Jasper087387a2013-02-08 16:49:27 +0000725 ++Current->Parent->FakeRParens;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000726 }
727 return;
728 }
729
730 // Consume scopes: (), [], <> and {}
731 if (opensScope(*Current)) {
732 while (Current != NULL && !closesScope(*Current)) {
733 next();
734 parse();
735 }
736 next();
737 } else {
738 // Operator found.
739 if (getPrecedence(*Current) == Precedence)
740 OperatorFound = true;
741
742 next();
743 }
744 }
745 }
746
747private:
748 void next() {
749 if (Current != NULL)
750 Current = Current->Children.empty() ? NULL : &Current->Children[0];
751 }
752
753 bool closesScope(const AnnotatedToken &Tok) {
754 return Current->is(tok::r_paren) || Current->Type == TT_TemplateCloser ||
755 Current->is(tok::r_brace) || Current->is(tok::r_square);
756 }
757
758 bool opensScope(const AnnotatedToken &Tok) {
759 return Current->is(tok::l_paren) || Current->Type == TT_TemplateOpener ||
760 Current->is(tok::l_brace) || Current->is(tok::l_square);
761 }
762
763 AnnotatedToken *Current;
764};
765
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000766void TokenAnnotator::annotate(AnnotatedLine &Line) {
Daniel Jasper01786732013-02-04 07:21:18 +0000767 AnnotatingParser Parser(SourceMgr, Lex, Line);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000768 Line.Type = Parser.parseLine();
769 if (Line.Type == LT_Invalid)
770 return;
771
Daniel Jasper29f123b2013-02-08 15:28:42 +0000772 ExpressionParser ExprParser(Line);
773 ExprParser.parse();
774
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000775 if (Line.First.Type == TT_ObjCMethodSpecifier)
776 Line.Type = LT_ObjCMethodDecl;
777 else if (Line.First.Type == TT_ObjCDecl)
778 Line.Type = LT_ObjCDecl;
779 else if (Line.First.Type == TT_ObjCProperty)
780 Line.Type = LT_ObjCProperty;
781
782 Line.First.SpaceRequiredBefore = true;
783 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
784 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
785
786 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000787}
788
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000789void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
790 if (Line.First.Children.empty())
791 return;
792 AnnotatedToken *Current = &Line.First.Children[0];
793 while (Current != NULL) {
794 Current->SpaceRequiredBefore = spaceRequiredBefore(Line, *Current);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000795
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000796 if (Current->FormatTok.MustBreakBefore) {
797 Current->MustBreakBefore = true;
798 } else if (Current->Type == TT_LineComment) {
799 Current->MustBreakBefore = Current->FormatTok.NewlinesBefore > 0;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000800 } else if (isTrailingComment(Current->Parent) ||
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000801 (Current->is(tok::string_literal) &&
802 Current->Parent->is(tok::string_literal))) {
803 Current->MustBreakBefore = true;
804 } else if (Current->is(tok::lessless) && !Current->Children.empty() &&
805 Current->Parent->is(tok::string_literal) &&
806 Current->Children[0].is(tok::string_literal)) {
807 Current->MustBreakBefore = true;
808 } else {
809 Current->MustBreakBefore = false;
810 }
811 Current->CanBreakBefore =
812 Current->MustBreakBefore || canBreakBefore(Line, *Current);
813 if (Current->MustBreakBefore)
814 Current->TotalLength = Current->Parent->TotalLength + Style.ColumnLimit;
815 else
816 Current->TotalLength =
817 Current->Parent->TotalLength + Current->FormatTok.TokenLength +
818 (Current->SpaceRequiredBefore ? 1 : 0);
819 // FIXME: Only calculate this if CanBreakBefore is true once static
820 // initializers etc. are sorted out.
821 // FIXME: Move magic numbers to a better place.
822 Current->SplitPenalty =
823 20 * Current->BindingStrength + splitPenalty(Line, *Current);
824
825 Current = Current->Children.empty() ? NULL : &Current->Children[0];
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000826 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000827}
828
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000829unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
830 const AnnotatedToken &Tok) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000831 const AnnotatedToken &Left = *Tok.Parent;
832 const AnnotatedToken &Right = Tok;
833
834 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
835 return 50;
836 if (Left.is(tok::equal) && Right.is(tok::l_brace))
837 return 150;
838 if (Left.is(tok::coloncolon))
839 return 500;
840
841 if (Left.Type == TT_RangeBasedForLoopColon)
842 return 5;
843
844 if (Right.is(tok::arrow) || Right.is(tok::period)) {
845 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
846 return 5; // Should be smaller than breaking at a nested comma.
847 return 150;
848 }
849
850 // In for-loops, prefer breaking at ',' and ';'.
851 if (Line.First.is(tok::kw_for) &&
852 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
853 return 20;
854
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000855 if (Left.is(tok::semi))
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000856 return 0;
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000857 if (Left.is(tok::comma))
858 return 1;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000859
860 // In Objective-C method expressions, prefer breaking before "param:" over
861 // breaking after it.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000862 if (Right.Type == TT_ObjCSelectorName)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000863 return 0;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000864 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000865 return 20;
866
Daniel Jasper01786732013-02-04 07:21:18 +0000867 if (Left.is(tok::l_paren) || Left.is(tok::l_square) ||
868 Left.Type == TT_TemplateOpener)
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000869 return 20;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000870
Daniel Jasper4e8a7b42013-02-06 21:04:05 +0000871 if (Right.is(tok::lessless)) {
872 if (Left.is(tok::string_literal)) {
873 char LastChar =
874 StringRef(Left.FormatTok.Tok.getLiteralData(),
875 Left.FormatTok.TokenLength).drop_back(1).rtrim().back();
876 if (LastChar == ':' || LastChar == '=')
877 return 100;
878 }
Daniel Jasper01786732013-02-04 07:21:18 +0000879 return prec::Shift;
Daniel Jasper4e8a7b42013-02-06 21:04:05 +0000880 }
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000881 if (Left.Type == TT_ConditionalExpr)
882 return prec::Assignment;
883 prec::Level Level = getPrecedence(Left);
884
885 if (Level != prec::Unknown)
886 return Level;
887
888 return 3;
889}
890
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000891bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
892 const AnnotatedToken &Left,
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000893 const AnnotatedToken &Right) {
894 if (Right.is(tok::hashhash))
895 return Left.is(tok::hash);
896 if (Left.is(tok::hashhash) || Left.is(tok::hash))
897 return Right.is(tok::hash);
898 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
899 return false;
900 if (Right.is(tok::less) &&
901 (Left.is(tok::kw_template) ||
902 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
903 return true;
904 if (Left.is(tok::arrow) || Right.is(tok::arrow))
905 return false;
906 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
907 return false;
908 if (Left.is(tok::at) &&
909 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
910 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
911 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
912 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
913 return false;
914 if (Left.is(tok::coloncolon))
915 return false;
916 if (Right.is(tok::coloncolon))
Daniel Jasperdaf1a152013-02-07 21:08:36 +0000917 return Left.isNot(tok::identifier) && Left.isNot(tok::greater) &&
918 Left.isNot(tok::l_paren);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000919 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
920 return false;
921 if (Right.is(tok::amp) || Right.is(tok::star))
922 return Left.FormatTok.Tok.isLiteral() ||
923 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000924 !Style.PointerBindsToType);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000925 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000926 return Right.FormatTok.Tok.isLiteral() || Style.PointerBindsToType;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000927 if (Right.is(tok::star) && Left.is(tok::l_paren))
928 return false;
929 if (Left.is(tok::l_square) || Right.is(tok::r_square))
930 return false;
931 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
932 return false;
933 if (Left.is(tok::period) || Right.is(tok::period))
934 return false;
935 if (Left.is(tok::colon))
936 return Left.Type != TT_ObjCMethodExpr;
937 if (Right.is(tok::colon))
938 return Right.Type != TT_ObjCMethodExpr;
939 if (Left.is(tok::l_paren))
940 return false;
941 if (Right.is(tok::l_paren)) {
942 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
943 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
944 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
945 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
946 Left.is(tok::kw_delete);
947 }
948 if (Left.is(tok::at) &&
949 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
950 return false;
951 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
952 return false;
953 return true;
954}
955
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000956bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
957 const AnnotatedToken &Tok) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000958 if (Line.Type == LT_ObjCMethodDecl) {
959 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
960 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
961 return true;
962 if (Tok.is(tok::colon))
963 return false;
964 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
965 return true;
966 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
967 // Don't space between ')' and <id>
968 return false;
969 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
970 // Don't space between ':' and '('
971 return false;
972 }
973 if (Line.Type == LT_ObjCProperty &&
974 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
975 return false;
976
977 if (Tok.Parent->is(tok::comma))
978 return true;
979 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
980 return true;
981 if (Tok.Type == TT_OverloadedOperator)
982 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
983 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
984 if (Tok.Parent->Type == TT_OverloadedOperator)
985 return false;
986 if (Tok.is(tok::colon))
987 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
988 Tok.Type != TT_ObjCMethodExpr;
989 if (Tok.Parent->Type == TT_UnaryOperator || Tok.Parent->Type == TT_CastRParen)
990 return false;
991 if (Tok.Type == TT_UnaryOperator)
992 return Tok.Parent->isNot(tok::l_paren) &&
993 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
994 (Tok.Parent->isNot(tok::colon) ||
995 Tok.Parent->Type != TT_ObjCMethodExpr);
996 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000997 return Tok.Type == TT_TemplateCloser &&
998 Tok.Parent->Type == TT_TemplateCloser &&
999 Style.Standard != FormatStyle::LS_Cpp11;
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001000 }
1001 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
1002 return true;
1003 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
1004 return false;
1005 if (Tok.is(tok::less) && Line.First.is(tok::hash))
1006 return true;
1007 if (Tok.Type == TT_TrailingUnaryOperator)
1008 return false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001009 return spaceRequiredBetween(Line, *Tok.Parent, Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001010}
1011
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001012bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
1013 const AnnotatedToken &Right) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001014 const AnnotatedToken &Left = *Right.Parent;
1015 if (Line.Type == LT_ObjCMethodDecl) {
1016 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1017 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
1018 return true;
1019 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1020 Left.Parent->is(tok::colon))
1021 // Don't break this identifier as ':' or identifier
1022 // before it will break.
1023 return false;
1024 if (Right.is(tok::colon) && Left.is(tok::identifier) && Left.CanBreakBefore)
1025 // Don't break at ':' if identifier before it can beak.
1026 return false;
1027 }
1028 if (Right.Type == TT_StartOfName && Style.AllowReturnTypeOnItsOwnLine)
1029 return true;
1030 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1031 return false;
1032 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1033 return true;
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001034 if (Right.Type == TT_ObjCSelectorName)
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001035 return true;
1036 if (Left.ClosesTemplateDeclaration)
1037 return true;
1038 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1039 return true;
1040 if (Left.Type == TT_RangeBasedForLoopColon)
1041 return true;
1042 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
1043 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1044 Left.is(tok::question))
1045 return false;
1046 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
1047 return false;
1048
1049 if (Right.Type == TT_LineComment)
1050 // We rely on MustBreakBefore being set correctly here as we should not
1051 // change the "binding" behavior of a comment.
1052 return false;
1053
1054 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1055 // unless it is follow by ';', '{' or '='.
1056 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1057 Left.Parent->is(tok::r_paren))
1058 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1059 Right.isNot(tok::equal);
1060
1061 // We only break before r_brace if there was a corresponding break before
1062 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1063 if (Right.is(tok::r_brace))
1064 return false;
1065
1066 if (Right.is(tok::r_paren) || Right.is(tok::greater))
1067 return false;
1068 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1069 Left.is(tok::comma) || Right.is(tok::lessless) ||
1070 Right.is(tok::arrow) || Right.is(tok::period) ||
1071 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1072 Left.is(tok::semi) || Left.is(tok::l_brace) ||
1073 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1074 Right.is(tok::identifier)) ||
1075 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1076 (Left.is(tok::l_square) && !Right.is(tok::r_square));
1077}
1078
1079} // namespace format
1080} // namespace clang