1 //===--- 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 "llvm/Support/Debug.h"
19 
20 namespace clang {
21 namespace format {
22 
23 namespace {
24 
25 /// \brief A parser that gathers additional information about tokens.
26 ///
27 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
28 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
29 /// into template parameter lists.
30 class AnnotatingParser {
31 public:
32   AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
33                    IdentifierInfo &Ident_in)
34       : Style(Style), Line(Line), CurrentToken(Line.First),
35         KeywordVirtualFound(false), AutoFound(false), Ident_in(Ident_in) {
36     Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
37     resetTokenMetadata(CurrentToken);
38   }
39 
40 private:
41   bool parseAngle() {
42     if (CurrentToken == NULL)
43       return false;
44     ScopedContextCreator ContextCreator(*this, tok::less, 10);
45     FormatToken *Left = CurrentToken->Previous;
46     Contexts.back().IsExpression = false;
47     // If there's a template keyword before the opening angle bracket, this is a
48     // template parameter, not an argument.
49     Contexts.back().InTemplateArgument =
50         Left->Previous != NULL && Left->Previous->Tok.isNot(tok::kw_template);
51 
52     while (CurrentToken != NULL) {
53       if (CurrentToken->is(tok::greater)) {
54         Left->MatchingParen = CurrentToken;
55         CurrentToken->MatchingParen = Left;
56         CurrentToken->Type = TT_TemplateCloser;
57         next();
58         return true;
59       }
60       if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace,
61                                 tok::question, tok::colon))
62         return false;
63       // If a && or || is found and interpreted as a binary operator, this set
64       // of angles is likely part of something like "a < b && c > d". If the
65       // angles are inside an expression, the ||/&& might also be a binary
66       // operator that was misinterpreted because we are parsing template
67       // parameters.
68       // FIXME: This is getting out of hand, write a decent parser.
69       if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
70           (CurrentToken->Previous->Type == TT_BinaryOperator ||
71            Contexts[Contexts.size() - 2].IsExpression) &&
72           Line.First->isNot(tok::kw_template))
73         return false;
74       updateParameterCount(Left, CurrentToken);
75       if (!consumeToken())
76         return false;
77     }
78     return false;
79   }
80 
81   bool parseParens(bool LookForDecls = false) {
82     if (CurrentToken == NULL)
83       return false;
84     ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
85 
86     // FIXME: This is a bit of a hack. Do better.
87     Contexts.back().ColonIsForRangeExpr =
88         Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
89 
90     bool StartsObjCMethodExpr = false;
91     FormatToken *Left = CurrentToken->Previous;
92     if (CurrentToken->is(tok::caret)) {
93       // (^ can start a block type.
94       Left->Type = TT_ObjCBlockLParen;
95     } else if (FormatToken *MaybeSel = Left->Previous) {
96       // @selector( starts a selector.
97       if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
98           MaybeSel->Previous->is(tok::at)) {
99         StartsObjCMethodExpr = true;
100       }
101     }
102 
103     if (Left->Previous &&
104         (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_if,
105                                  tok::kw_while, tok::l_paren, tok::comma) ||
106          Left->Previous->Type == TT_BinaryOperator)) {
107       // static_assert, if and while usually contain expressions.
108       Contexts.back().IsExpression = true;
109     } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
110                Left->Previous->MatchingParen &&
111                Left->Previous->MatchingParen->Type == TT_LambdaLSquare) {
112       // This is a parameter list of a lambda expression.
113       Contexts.back().IsExpression = false;
114     } else if (Contexts[Contexts.size() - 2].CaretFound) {
115       // This is the parameter list of an ObjC block.
116       Contexts.back().IsExpression = false;
117     } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
118       Left->Type = TT_AttributeParen;
119     }
120 
121     if (StartsObjCMethodExpr) {
122       Contexts.back().ColonIsObjCMethodExpr = true;
123       Left->Type = TT_ObjCMethodExpr;
124     }
125 
126     bool MightBeFunctionType = CurrentToken->is(tok::star);
127     bool HasMultipleLines = false;
128     bool HasMultipleParametersOnALine = false;
129     while (CurrentToken != NULL) {
130       // LookForDecls is set when "if (" has been seen. Check for
131       // 'identifier' '*' 'identifier' followed by not '=' -- this
132       // '*' has to be a binary operator but determineStarAmpUsage() will
133       // categorize it as an unary operator, so set the right type here.
134       if (LookForDecls && CurrentToken->Next) {
135         FormatToken *Prev = CurrentToken->getPreviousNonComment();
136         if (Prev) {
137           FormatToken *PrevPrev = Prev->getPreviousNonComment();
138           FormatToken *Next = CurrentToken->Next;
139           if (PrevPrev && PrevPrev->is(tok::identifier) &&
140               Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
141               CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
142             Prev->Type = TT_BinaryOperator;
143             LookForDecls = false;
144           }
145         }
146       }
147 
148       if (CurrentToken->Previous->Type == TT_PointerOrReference &&
149           CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
150                                                     tok::coloncolon))
151         MightBeFunctionType = true;
152       if (CurrentToken->is(tok::r_paren)) {
153         if (MightBeFunctionType && CurrentToken->Next &&
154             (CurrentToken->Next->is(tok::l_paren) ||
155              (CurrentToken->Next->is(tok::l_square) &&
156               !Contexts.back().IsExpression)))
157           Left->Type = TT_FunctionTypeLParen;
158         Left->MatchingParen = CurrentToken;
159         CurrentToken->MatchingParen = Left;
160 
161         if (StartsObjCMethodExpr) {
162           CurrentToken->Type = TT_ObjCMethodExpr;
163           if (Contexts.back().FirstObjCSelectorName != NULL) {
164             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
165                 Contexts.back().LongestObjCSelectorName;
166           }
167         }
168 
169         if (Left->Type == TT_AttributeParen)
170           CurrentToken->Type = TT_AttributeParen;
171 
172         if (!HasMultipleLines)
173           Left->PackingKind = PPK_Inconclusive;
174         else if (HasMultipleParametersOnALine)
175           Left->PackingKind = PPK_BinPacked;
176         else
177           Left->PackingKind = PPK_OnePerLine;
178 
179         next();
180         return true;
181       }
182       if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
183         return false;
184       else if (CurrentToken->is(tok::l_brace))
185         Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
186       updateParameterCount(Left, CurrentToken);
187       if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
188           !CurrentToken->Next->HasUnescapedNewline &&
189           !CurrentToken->Next->isTrailingComment())
190         HasMultipleParametersOnALine = true;
191       if (CurrentToken->is(tok::kw_const) ||
192           CurrentToken->isSimpleTypeSpecifier())
193         Contexts.back().IsExpression = false;
194       if (!consumeToken())
195         return false;
196       if (CurrentToken && CurrentToken->HasUnescapedNewline)
197         HasMultipleLines = true;
198     }
199     return false;
200   }
201 
202   bool parseSquare() {
203     if (!CurrentToken)
204       return false;
205 
206     // A '[' could be an index subscript (after an identifier or after
207     // ')' or ']'), it could be the start of an Objective-C method
208     // expression, or it could the the start of an Objective-C array literal.
209     FormatToken *Left = CurrentToken->Previous;
210     FormatToken *Parent = Left->getPreviousNonComment();
211     bool StartsObjCMethodExpr =
212         Contexts.back().CanBeExpression && Left->Type != TT_LambdaLSquare &&
213         (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
214                                     tok::kw_return, tok::kw_throw) ||
215          Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
216          Parent->Type == TT_CastRParen ||
217          getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
218     ScopedContextCreator ContextCreator(*this, tok::l_square, 10);
219     Contexts.back().IsExpression = true;
220     bool ColonFound = false;
221 
222     if (StartsObjCMethodExpr) {
223       Contexts.back().ColonIsObjCMethodExpr = true;
224       Left->Type = TT_ObjCMethodExpr;
225     } else if (Parent && Parent->is(tok::at)) {
226       Left->Type = TT_ArrayInitializerLSquare;
227     } else if (Left->Type == TT_Unknown) {
228       Left->Type = TT_ArraySubscriptLSquare;
229     }
230 
231     while (CurrentToken != NULL) {
232       if (CurrentToken->is(tok::r_square)) {
233         if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
234             Left->Type == TT_ObjCMethodExpr) {
235           // An ObjC method call is rarely followed by an open parenthesis.
236           // FIXME: Do we incorrectly label ":" with this?
237           StartsObjCMethodExpr = false;
238           Left->Type = TT_Unknown;
239         }
240         if (StartsObjCMethodExpr) {
241           CurrentToken->Type = TT_ObjCMethodExpr;
242           // determineStarAmpUsage() thinks that '*' '[' is allocating an
243           // array of pointers, but if '[' starts a selector then '*' is a
244           // binary operator.
245           if (Parent != NULL && Parent->Type == TT_PointerOrReference)
246             Parent->Type = TT_BinaryOperator;
247         }
248         Left->MatchingParen = CurrentToken;
249         CurrentToken->MatchingParen = Left;
250         if (Contexts.back().FirstObjCSelectorName != NULL) {
251           Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
252               Contexts.back().LongestObjCSelectorName;
253           if (Contexts.back().NumBlockParameters > 1)
254             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
255         }
256         next();
257         return true;
258       }
259       if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
260         return false;
261       if (CurrentToken->is(tok::colon))
262         ColonFound = true;
263       if (CurrentToken->is(tok::comma) &&
264           Style.Language != FormatStyle::LK_Proto &&
265           (Left->Type == TT_ArraySubscriptLSquare ||
266            (Left->Type == TT_ObjCMethodExpr && !ColonFound)))
267         Left->Type = TT_ArrayInitializerLSquare;
268       updateParameterCount(Left, CurrentToken);
269       if (!consumeToken())
270         return false;
271     }
272     return false;
273   }
274 
275   bool parseBrace() {
276     if (CurrentToken != NULL) {
277       FormatToken *Left = CurrentToken->Previous;
278 
279       if (Contexts.back().CaretFound)
280         Left->Type = TT_ObjCBlockLBrace;
281       Contexts.back().CaretFound = false;
282 
283       ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
284       Contexts.back().ColonIsDictLiteral = true;
285 
286       while (CurrentToken != NULL) {
287         if (CurrentToken->is(tok::r_brace)) {
288           Left->MatchingParen = CurrentToken;
289           CurrentToken->MatchingParen = Left;
290           next();
291           return true;
292         }
293         if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
294           return false;
295         updateParameterCount(Left, CurrentToken);
296         if (CurrentToken->is(tok::colon) &&
297             Style.Language != FormatStyle::LK_Proto)
298           Left->Type = TT_DictLiteral;
299         if (!consumeToken())
300           return false;
301       }
302     }
303     // No closing "}" found, this probably starts a definition.
304     Line.StartsDefinition = true;
305     return true;
306   }
307 
308   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
309     if (Current->is(tok::comma)) {
310       ++Left->ParameterCount;
311       if (!Left->Role)
312         Left->Role.reset(new CommaSeparatedList(Style));
313       Left->Role->CommaFound(Current);
314     } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
315       Left->ParameterCount = 1;
316     }
317   }
318 
319   bool parseConditional() {
320     while (CurrentToken != NULL) {
321       if (CurrentToken->is(tok::colon)) {
322         CurrentToken->Type = TT_ConditionalExpr;
323         next();
324         return true;
325       }
326       if (!consumeToken())
327         return false;
328     }
329     return false;
330   }
331 
332   bool parseTemplateDeclaration() {
333     if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
334       CurrentToken->Type = TT_TemplateOpener;
335       next();
336       if (!parseAngle())
337         return false;
338       if (CurrentToken != NULL)
339         CurrentToken->Previous->ClosesTemplateDeclaration = true;
340       return true;
341     }
342     return false;
343   }
344 
345   bool consumeToken() {
346     FormatToken *Tok = CurrentToken;
347     next();
348     switch (Tok->Tok.getKind()) {
349     case tok::plus:
350     case tok::minus:
351       if (Tok->Previous == NULL && Line.MustBeDeclaration)
352         Tok->Type = TT_ObjCMethodSpecifier;
353       break;
354     case tok::colon:
355       if (Tok->Previous == NULL)
356         return false;
357       // Colons from ?: are handled in parseConditional().
358       if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1) {
359         Tok->Type = TT_CtorInitializerColon;
360       } else if (Contexts.back().ColonIsDictLiteral) {
361         Tok->Type = TT_DictLiteral;
362       } else if (Contexts.back().ColonIsObjCMethodExpr ||
363                  Line.First->Type == TT_ObjCMethodSpecifier) {
364         Tok->Type = TT_ObjCMethodExpr;
365         Tok->Previous->Type = TT_ObjCSelectorName;
366         if (Tok->Previous->ColumnWidth >
367             Contexts.back().LongestObjCSelectorName) {
368           Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
369         }
370         if (Contexts.back().FirstObjCSelectorName == NULL)
371           Contexts.back().FirstObjCSelectorName = Tok->Previous;
372       } else if (Contexts.back().ColonIsForRangeExpr) {
373         Tok->Type = TT_RangeBasedForLoopColon;
374       } else if (CurrentToken != NULL &&
375                  CurrentToken->is(tok::numeric_constant)) {
376         Tok->Type = TT_BitFieldColon;
377       } else if (Contexts.size() == 1 && Line.First->isNot(tok::kw_enum)) {
378         Tok->Type = TT_InheritanceColon;
379       } else if (Contexts.back().ContextKind == tok::l_paren) {
380         Tok->Type = TT_InlineASMColon;
381       }
382       break;
383     case tok::kw_if:
384     case tok::kw_while:
385       if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
386         next();
387         if (!parseParens(/*LookForDecls=*/true))
388           return false;
389       }
390       break;
391     case tok::kw_for:
392       Contexts.back().ColonIsForRangeExpr = true;
393       next();
394       if (!parseParens())
395         return false;
396       break;
397     case tok::l_paren:
398       if (!parseParens())
399         return false;
400       if (Line.MustBeDeclaration && Contexts.size() == 1 &&
401           !Contexts.back().IsExpression && Line.First->Type != TT_ObjCProperty)
402         Line.MightBeFunctionDecl = true;
403       break;
404     case tok::l_square:
405       if (!parseSquare())
406         return false;
407       break;
408     case tok::l_brace:
409       if (!parseBrace())
410         return false;
411       break;
412     case tok::less:
413       if (Tok->Previous && !Tok->Previous->Tok.isLiteral() && parseAngle())
414         Tok->Type = TT_TemplateOpener;
415       else {
416         Tok->Type = TT_BinaryOperator;
417         CurrentToken = Tok;
418         next();
419       }
420       break;
421     case tok::r_paren:
422     case tok::r_square:
423       return false;
424     case tok::r_brace:
425       // Lines can start with '}'.
426       if (Tok->Previous != NULL)
427         return false;
428       break;
429     case tok::greater:
430       Tok->Type = TT_BinaryOperator;
431       break;
432     case tok::kw_operator:
433       while (CurrentToken &&
434              !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
435         if (CurrentToken->isOneOf(tok::star, tok::amp))
436           CurrentToken->Type = TT_PointerOrReference;
437         consumeToken();
438         if (CurrentToken && CurrentToken->Previous->Type == TT_BinaryOperator)
439           CurrentToken->Previous->Type = TT_OverloadedOperator;
440       }
441       if (CurrentToken) {
442         CurrentToken->Type = TT_OverloadedOperatorLParen;
443         if (CurrentToken->Previous->Type == TT_BinaryOperator)
444           CurrentToken->Previous->Type = TT_OverloadedOperator;
445       }
446       break;
447     case tok::question:
448       parseConditional();
449       break;
450     case tok::kw_template:
451       parseTemplateDeclaration();
452       break;
453     case tok::identifier:
454       if (Line.First->is(tok::kw_for) &&
455           Tok->Tok.getIdentifierInfo() == &Ident_in)
456         Tok->Type = TT_ObjCForIn;
457       break;
458     case tok::comma:
459       if (Contexts.back().FirstStartOfName)
460         Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
461       if (Contexts.back().InCtorInitializer)
462         Tok->Type = TT_CtorInitializerComma;
463       break;
464     default:
465       break;
466     }
467     return true;
468   }
469 
470   void parseIncludeDirective() {
471     next();
472     if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
473       next();
474       while (CurrentToken != NULL) {
475         if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
476           CurrentToken->Type = TT_ImplicitStringLiteral;
477         next();
478       }
479     } else {
480       while (CurrentToken != NULL) {
481         if (CurrentToken->is(tok::string_literal))
482           // Mark these string literals as "implicit" literals, too, so that
483           // they are not split or line-wrapped.
484           CurrentToken->Type = TT_ImplicitStringLiteral;
485         next();
486       }
487     }
488   }
489 
490   void parseWarningOrError() {
491     next();
492     // We still want to format the whitespace left of the first token of the
493     // warning or error.
494     next();
495     while (CurrentToken != NULL) {
496       CurrentToken->Type = TT_ImplicitStringLiteral;
497       next();
498     }
499   }
500 
501   void parsePragma() {
502     next(); // Consume "pragma".
503     if (CurrentToken && CurrentToken->TokenText == "mark") {
504       next(); // Consume "mark".
505       next(); // Consume first token (so we fix leading whitespace).
506       while (CurrentToken != NULL) {
507         CurrentToken->Type = TT_ImplicitStringLiteral;
508         next();
509       }
510     }
511   }
512 
513   void parsePreprocessorDirective() {
514     next();
515     if (CurrentToken == NULL)
516       return;
517     if (CurrentToken->Tok.is(tok::numeric_constant)) {
518       CurrentToken->SpacesRequiredBefore = 1;
519       return;
520     }
521     // Hashes in the middle of a line can lead to any strange token
522     // sequence.
523     if (CurrentToken->Tok.getIdentifierInfo() == NULL)
524       return;
525     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
526     case tok::pp_include:
527     case tok::pp_import:
528       parseIncludeDirective();
529       break;
530     case tok::pp_error:
531     case tok::pp_warning:
532       parseWarningOrError();
533       break;
534     case tok::pp_pragma:
535       parsePragma();
536       break;
537     case tok::pp_if:
538     case tok::pp_elif:
539       Contexts.back().IsExpression = true;
540       parseLine();
541       break;
542     default:
543       break;
544     }
545     while (CurrentToken != NULL)
546       next();
547   }
548 
549 public:
550   LineType parseLine() {
551     if (CurrentToken->is(tok::hash)) {
552       parsePreprocessorDirective();
553       return LT_PreprocessorDirective;
554     }
555 
556     // Directly allow to 'import <string-literal>' to support protocol buffer
557     // definitions (code.google.com/p/protobuf) or missing "#" (either way we
558     // should not break the line).
559     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
560     if (Info && Info->getPPKeywordID() == tok::pp_import &&
561         CurrentToken->Next && CurrentToken->Next->is(tok::string_literal))
562       parseIncludeDirective();
563 
564     while (CurrentToken != NULL) {
565       if (CurrentToken->is(tok::kw_virtual))
566         KeywordVirtualFound = true;
567       if (!consumeToken())
568         return LT_Invalid;
569     }
570     if (KeywordVirtualFound)
571       return LT_VirtualFunctionDecl;
572 
573     if (Line.First->Type == TT_ObjCMethodSpecifier) {
574       if (Contexts.back().FirstObjCSelectorName != NULL)
575         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
576             Contexts.back().LongestObjCSelectorName;
577       return LT_ObjCMethodDecl;
578     }
579 
580     return LT_Other;
581   }
582 
583 private:
584   void resetTokenMetadata(FormatToken *Token) {
585     if (Token == nullptr) return;
586 
587     // Reset token type in case we have already looked at it and then
588     // recovered from an error (e.g. failure to find the matching >).
589     if (CurrentToken->Type != TT_LambdaLSquare &&
590         CurrentToken->Type != TT_FunctionLBrace &&
591         CurrentToken->Type != TT_ImplicitStringLiteral &&
592         CurrentToken->Type != TT_TrailingReturnArrow)
593       CurrentToken->Type = TT_Unknown;
594     if (CurrentToken->Role)
595       CurrentToken->Role.reset(NULL);
596     CurrentToken->FakeLParens.clear();
597     CurrentToken->FakeRParens = 0;
598   }
599 
600   void next() {
601     if (CurrentToken != NULL) {
602       determineTokenType(*CurrentToken);
603       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
604       CurrentToken->NestingLevel = Contexts.size() - 1;
605     }
606 
607     if (CurrentToken != NULL)
608       CurrentToken = CurrentToken->Next;
609 
610     resetTokenMetadata(CurrentToken);
611   }
612 
613   /// \brief A struct to hold information valid in a specific context, e.g.
614   /// a pair of parenthesis.
615   struct Context {
616     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
617             bool IsExpression)
618         : ContextKind(ContextKind), BindingStrength(BindingStrength),
619           LongestObjCSelectorName(0), NumBlockParameters(0),
620           ColonIsForRangeExpr(false), ColonIsDictLiteral(false),
621           ColonIsObjCMethodExpr(false), FirstObjCSelectorName(NULL),
622           FirstStartOfName(NULL), IsExpression(IsExpression),
623           CanBeExpression(true), InTemplateArgument(false),
624           InCtorInitializer(false), CaretFound(false) {}
625 
626     tok::TokenKind ContextKind;
627     unsigned BindingStrength;
628     unsigned LongestObjCSelectorName;
629     unsigned NumBlockParameters;
630     bool ColonIsForRangeExpr;
631     bool ColonIsDictLiteral;
632     bool ColonIsObjCMethodExpr;
633     FormatToken *FirstObjCSelectorName;
634     FormatToken *FirstStartOfName;
635     bool IsExpression;
636     bool CanBeExpression;
637     bool InTemplateArgument;
638     bool InCtorInitializer;
639     bool CaretFound;
640   };
641 
642   /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
643   /// of each instance.
644   struct ScopedContextCreator {
645     AnnotatingParser &P;
646 
647     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
648                          unsigned Increase)
649         : P(P) {
650       P.Contexts.push_back(Context(ContextKind,
651                                    P.Contexts.back().BindingStrength + Increase,
652                                    P.Contexts.back().IsExpression));
653     }
654 
655     ~ScopedContextCreator() { P.Contexts.pop_back(); }
656   };
657 
658   void determineTokenType(FormatToken &Current) {
659     if (Current.getPrecedence() == prec::Assignment &&
660         !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
661         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
662       Contexts.back().IsExpression = true;
663       for (FormatToken *Previous = Current.Previous;
664            Previous && !Previous->isOneOf(tok::comma, tok::semi);
665            Previous = Previous->Previous) {
666         if (Previous->is(tok::r_square))
667           Previous = Previous->MatchingParen;
668         if (Previous->Type == TT_BinaryOperator &&
669             Previous->isOneOf(tok::star, tok::amp)) {
670           Previous->Type = TT_PointerOrReference;
671         }
672       }
673     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
674       Contexts.back().IsExpression = true;
675     } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
676                !Line.InPPDirective) {
677       bool ParametersOfFunctionType =
678           Current.Previous && Current.Previous->is(tok::r_paren) &&
679           Current.Previous->MatchingParen &&
680           Current.Previous->MatchingParen->Type == TT_FunctionTypeLParen;
681       bool IsForOrCatch = Current.Previous &&
682                           Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
683       Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
684     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
685       for (FormatToken *Previous = Current.Previous;
686            Previous && Previous->isOneOf(tok::star, tok::amp);
687            Previous = Previous->Previous)
688         Previous->Type = TT_PointerOrReference;
689     } else if (Current.Previous &&
690                Current.Previous->Type == TT_CtorInitializerColon) {
691       Contexts.back().IsExpression = true;
692       Contexts.back().InCtorInitializer = true;
693     } else if (Current.is(tok::kw_new)) {
694       Contexts.back().CanBeExpression = false;
695     } else if (Current.is(tok::semi) || Current.is(tok::exclaim)) {
696       // This should be the condition or increment in a for-loop.
697       Contexts.back().IsExpression = true;
698     }
699 
700     if (Current.Type == TT_Unknown) {
701       // Line.MightBeFunctionDecl can only be true after the parentheses of a
702       // function declaration have been found. In this case, 'Current' is a
703       // trailing token of this declaration and thus cannot be a name.
704       if (isStartOfName(Current) && !Line.MightBeFunctionDecl) {
705         Contexts.back().FirstStartOfName = &Current;
706         Current.Type = TT_StartOfName;
707       } else if (Current.is(tok::kw_auto)) {
708         AutoFound = true;
709       } else if (Current.is(tok::arrow) && AutoFound &&
710                  Line.MustBeDeclaration) {
711         Current.Type = TT_TrailingReturnArrow;
712       } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
713         Current.Type =
714             determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
715                                                Contexts.back().IsExpression,
716                                   Contexts.back().InTemplateArgument);
717       } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
718         Current.Type = determinePlusMinusCaretUsage(Current);
719         if (Current.Type == TT_UnaryOperator) {
720           ++Contexts.back().NumBlockParameters;
721           if (Current.is(tok::caret))
722             Contexts.back().CaretFound = true;
723         }
724       } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
725         Current.Type = determineIncrementUsage(Current);
726       } else if (Current.is(tok::exclaim)) {
727         Current.Type = TT_UnaryOperator;
728       } else if (Current.isBinaryOperator() &&
729                  (!Current.Previous ||
730                   Current.Previous->isNot(tok::l_square))) {
731         Current.Type = TT_BinaryOperator;
732       } else if (Current.is(tok::comment)) {
733         if (Current.TokenText.startswith("//"))
734           Current.Type = TT_LineComment;
735         else
736           Current.Type = TT_BlockComment;
737       } else if (Current.is(tok::r_paren)) {
738         FormatToken *LeftOfParens = NULL;
739         if (Current.MatchingParen)
740           LeftOfParens = Current.MatchingParen->getPreviousNonComment();
741         bool IsCast = false;
742         bool ParensAreEmpty = Current.Previous == Current.MatchingParen;
743         bool ParensAreType = !Current.Previous ||
744                              Current.Previous->Type == TT_PointerOrReference ||
745                              Current.Previous->Type == TT_TemplateCloser ||
746                              Current.Previous->isSimpleTypeSpecifier();
747         bool ParensCouldEndDecl =
748             Current.Next &&
749             Current.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
750         bool IsSizeOfOrAlignOf =
751             LeftOfParens &&
752             LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
753         if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
754             ((Contexts.size() > 1 &&
755               Contexts[Contexts.size() - 2].IsExpression) ||
756              (Current.Next && Current.Next->isBinaryOperator())))
757           IsCast = true;
758         if (Current.Next && Current.Next->isNot(tok::string_literal) &&
759             (Current.Next->Tok.isLiteral() ||
760              Current.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
761           IsCast = true;
762         // If there is an identifier after the (), it is likely a cast, unless
763         // there is also an identifier before the ().
764         if (LeftOfParens && (LeftOfParens->Tok.getIdentifierInfo() == NULL ||
765                              LeftOfParens->is(tok::kw_return)) &&
766             LeftOfParens->Type != TT_OverloadedOperator &&
767             LeftOfParens->isNot(tok::at) &&
768             LeftOfParens->Type != TT_TemplateCloser && Current.Next &&
769             Current.Next->is(tok::identifier))
770           IsCast = true;
771         if (IsCast && !ParensAreEmpty)
772           Current.Type = TT_CastRParen;
773       } else if (Current.is(tok::at) && Current.Next) {
774         switch (Current.Next->Tok.getObjCKeywordID()) {
775         case tok::objc_interface:
776         case tok::objc_implementation:
777         case tok::objc_protocol:
778           Current.Type = TT_ObjCDecl;
779           break;
780         case tok::objc_property:
781           Current.Type = TT_ObjCProperty;
782           break;
783         default:
784           break;
785         }
786       } else if (Current.is(tok::period)) {
787         FormatToken *PreviousNoComment = Current.getPreviousNonComment();
788         if (PreviousNoComment &&
789             PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
790           Current.Type = TT_DesignatedInitializerPeriod;
791       } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
792                  Line.MightBeFunctionDecl && Contexts.size() == 1) {
793         // Line.MightBeFunctionDecl can only be true after the parentheses of a
794         // function declaration have been found.
795         Current.Type = TT_TrailingAnnotation;
796       }
797     }
798   }
799 
800   /// \brief Take a guess at whether \p Tok starts a name of a function or
801   /// variable declaration.
802   ///
803   /// This is a heuristic based on whether \p Tok is an identifier following
804   /// something that is likely a type.
805   bool isStartOfName(const FormatToken &Tok) {
806     if (Tok.isNot(tok::identifier) || Tok.Previous == NULL)
807       return false;
808 
809     // Skip "const" as it does not have an influence on whether this is a name.
810     FormatToken *PreviousNotConst = Tok.Previous;
811     while (PreviousNotConst != NULL && PreviousNotConst->is(tok::kw_const))
812       PreviousNotConst = PreviousNotConst->Previous;
813 
814     if (PreviousNotConst == NULL)
815       return false;
816 
817     bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
818                        PreviousNotConst->Previous &&
819                        PreviousNotConst->Previous->is(tok::hash);
820 
821     if (PreviousNotConst->Type == TT_TemplateCloser)
822       return PreviousNotConst && PreviousNotConst->MatchingParen &&
823              PreviousNotConst->MatchingParen->Previous &&
824              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
825 
826     return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
827            PreviousNotConst->Type == TT_PointerOrReference ||
828            PreviousNotConst->isSimpleTypeSpecifier();
829   }
830 
831   /// \brief Return the type of the given token assuming it is * or &.
832   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
833                                   bool InTemplateArgument) {
834     const FormatToken *PrevToken = Tok.getPreviousNonComment();
835     if (PrevToken == NULL)
836       return TT_UnaryOperator;
837 
838     const FormatToken *NextToken = Tok.getNextNonComment();
839     if (NextToken == NULL)
840       return TT_Unknown;
841 
842     if (PrevToken->is(tok::coloncolon) ||
843         (PrevToken->is(tok::l_paren) && !IsExpression))
844       return TT_PointerOrReference;
845 
846     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
847                            tok::comma, tok::semi, tok::kw_return, tok::colon,
848                            tok::equal, tok::kw_delete, tok::kw_sizeof) ||
849         PrevToken->Type == TT_BinaryOperator ||
850         PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
851       return TT_UnaryOperator;
852 
853     if (NextToken->is(tok::l_square))
854       return TT_PointerOrReference;
855 
856     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
857         PrevToken->MatchingParen->Previous &&
858         PrevToken->MatchingParen->Previous->is(tok::kw_typeof))
859       return TT_PointerOrReference;
860 
861     if (PrevToken->Tok.isLiteral() ||
862         PrevToken->isOneOf(tok::r_paren, tok::r_square) ||
863         NextToken->Tok.isLiteral() || NextToken->isUnaryOperator() ||
864         // If we know we're in a template argument, there are no named
865         // declarations. Thus, having an identifier on the right-hand side
866         // indicates a binary operator.
867         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
868       return TT_BinaryOperator;
869 
870     // It is very unlikely that we are going to find a pointer or reference type
871     // definition on the RHS of an assignment.
872     if (IsExpression)
873       return TT_BinaryOperator;
874 
875     return TT_PointerOrReference;
876   }
877 
878   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
879     const FormatToken *PrevToken = Tok.getPreviousNonComment();
880     if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
881       return TT_UnaryOperator;
882 
883     // Use heuristics to recognize unary operators.
884     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
885                            tok::question, tok::colon, tok::kw_return,
886                            tok::kw_case, tok::at, tok::l_brace))
887       return TT_UnaryOperator;
888 
889     // There can't be two consecutive binary operators.
890     if (PrevToken->Type == TT_BinaryOperator)
891       return TT_UnaryOperator;
892 
893     // Fall back to marking the token as binary operator.
894     return TT_BinaryOperator;
895   }
896 
897   /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
898   TokenType determineIncrementUsage(const FormatToken &Tok) {
899     const FormatToken *PrevToken = Tok.getPreviousNonComment();
900     if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
901       return TT_UnaryOperator;
902     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
903       return TT_TrailingUnaryOperator;
904 
905     return TT_UnaryOperator;
906   }
907 
908 
909   SmallVector<Context, 8> Contexts;
910 
911   const FormatStyle &Style;
912   AnnotatedLine &Line;
913   FormatToken *CurrentToken;
914   bool KeywordVirtualFound;
915   bool AutoFound;
916   IdentifierInfo &Ident_in;
917 };
918 
919 static int PrecedenceUnaryOperator = prec::PointerToMember + 1;
920 static int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
921 
922 /// \brief Parses binary expressions by inserting fake parenthesis based on
923 /// operator precedence.
924 class ExpressionParser {
925 public:
926   ExpressionParser(AnnotatedLine &Line) : Current(Line.First) {
927     // Skip leading "}", e.g. in "} else if (...) {".
928     if (Current->is(tok::r_brace))
929       next();
930   }
931 
932   /// \brief Parse expressions with the given operatore precedence.
933   void parse(int Precedence = 0) {
934     // Skip 'return' and ObjC selector colons as they are not part of a binary
935     // expression.
936     while (Current &&
937            (Current->is(tok::kw_return) ||
938             (Current->is(tok::colon) && Current->Type == TT_ObjCMethodExpr)))
939       next();
940 
941     if (Current == NULL || Precedence > PrecedenceArrowAndPeriod)
942       return;
943 
944     // Conditional expressions need to be parsed separately for proper nesting.
945     if (Precedence == prec::Conditional) {
946       parseConditionalExpr();
947       return;
948     }
949 
950     // Parse unary operators, which all have a higher precedence than binary
951     // operators.
952     if (Precedence == PrecedenceUnaryOperator) {
953       parseUnaryOperator();
954       return;
955     }
956 
957     FormatToken *Start = Current;
958     FormatToken *LatestOperator = NULL;
959 
960     while (Current) {
961       // Consume operators with higher precedence.
962       parse(Precedence + 1);
963 
964       int CurrentPrecedence = getCurrentPrecedence();
965 
966       if (Current && Current->Type == TT_ObjCSelectorName &&
967           Precedence == CurrentPrecedence) {
968         if (LatestOperator)
969           addFakeParenthesis(Start, prec::Level(Precedence));
970         Start = Current;
971       }
972 
973       // At the end of the line or when an operator with higher precedence is
974       // found, insert fake parenthesis and return.
975       if (Current == NULL || Current->closesScope() ||
976           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence)) {
977         if (LatestOperator) {
978           if (Precedence == PrecedenceArrowAndPeriod) {
979             LatestOperator->LastInChainOfCalls = true;
980             // Call expressions don't have a binary operator precedence.
981             addFakeParenthesis(Start, prec::Unknown);
982           } else {
983             addFakeParenthesis(Start, prec::Level(Precedence));
984           }
985         }
986         return;
987       }
988 
989       // Consume scopes: (), [], <> and {}
990       if (Current->opensScope()) {
991         while (Current && !Current->closesScope()) {
992           next();
993           parse();
994         }
995         next();
996       } else {
997         // Operator found.
998         if (CurrentPrecedence == Precedence)
999           LatestOperator = Current;
1000 
1001         next();
1002       }
1003     }
1004   }
1005 
1006 private:
1007   /// \brief Gets the precedence (+1) of the given token for binary operators
1008   /// and other tokens that we treat like binary operators.
1009   int getCurrentPrecedence() {
1010     if (Current) {
1011       if (Current->Type == TT_ConditionalExpr)
1012         return prec::Conditional;
1013       else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
1014                Current->Type == TT_ObjCSelectorName)
1015         return 0;
1016       else if (Current->Type == TT_RangeBasedForLoopColon)
1017         return prec::Comma;
1018       else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
1019         return Current->getPrecedence();
1020       else if (Current->isOneOf(tok::period, tok::arrow))
1021         return PrecedenceArrowAndPeriod;
1022     }
1023     return -1;
1024   }
1025 
1026   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1027     Start->FakeLParens.push_back(Precedence);
1028     if (Precedence > prec::Unknown)
1029       Start->StartsBinaryExpression = true;
1030     if (Current) {
1031       ++Current->Previous->FakeRParens;
1032       if (Precedence > prec::Unknown)
1033         Current->Previous->EndsBinaryExpression = true;
1034     }
1035   }
1036 
1037   /// \brief Parse unary operator expressions and surround them with fake
1038   /// parentheses if appropriate.
1039   void parseUnaryOperator() {
1040     if (Current == NULL || Current->Type != TT_UnaryOperator) {
1041       parse(PrecedenceArrowAndPeriod);
1042       return;
1043     }
1044 
1045     FormatToken *Start = Current;
1046     next();
1047     parseUnaryOperator();
1048 
1049     // The actual precedence doesn't matter.
1050     addFakeParenthesis(Start, prec::Unknown);
1051   }
1052 
1053   void parseConditionalExpr() {
1054     FormatToken *Start = Current;
1055     parse(prec::LogicalOr);
1056     if (!Current || !Current->is(tok::question))
1057       return;
1058     next();
1059     parse(prec::LogicalOr);
1060     if (!Current || Current->Type != TT_ConditionalExpr)
1061       return;
1062     next();
1063     parseConditionalExpr();
1064     addFakeParenthesis(Start, prec::Conditional);
1065   }
1066 
1067   void next() {
1068     if (Current)
1069       Current = Current->Next;
1070     while (Current && Current->isTrailingComment())
1071       Current = Current->Next;
1072   }
1073 
1074   FormatToken *Current;
1075 };
1076 
1077 } // end anonymous namespace
1078 
1079 void
1080 TokenAnnotator::setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) {
1081   const AnnotatedLine *NextNonCommentLine = NULL;
1082   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1083                                                           E = Lines.rend();
1084        I != E; ++I) {
1085     if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1086         (*I)->First->Next == NULL)
1087       (*I)->Level = NextNonCommentLine->Level;
1088     else
1089       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : NULL;
1090 
1091     setCommentLineLevels((*I)->Children);
1092   }
1093 }
1094 
1095 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1096   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1097                                                   E = Line.Children.end();
1098        I != E; ++I) {
1099     annotate(**I);
1100   }
1101   AnnotatingParser Parser(Style, Line, Ident_in);
1102   Line.Type = Parser.parseLine();
1103   if (Line.Type == LT_Invalid)
1104     return;
1105 
1106   ExpressionParser ExprParser(Line);
1107   ExprParser.parse();
1108 
1109   if (Line.First->Type == TT_ObjCMethodSpecifier)
1110     Line.Type = LT_ObjCMethodDecl;
1111   else if (Line.First->Type == TT_ObjCDecl)
1112     Line.Type = LT_ObjCDecl;
1113   else if (Line.First->Type == TT_ObjCProperty)
1114     Line.Type = LT_ObjCProperty;
1115 
1116   Line.First->SpacesRequiredBefore = 1;
1117   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1118 }
1119 
1120 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1121   Line.First->TotalLength =
1122       Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1123   if (!Line.First->Next)
1124     return;
1125   FormatToken *Current = Line.First->Next;
1126   bool InFunctionDecl = Line.MightBeFunctionDecl;
1127   while (Current != NULL) {
1128     if (Current->Type == TT_LineComment) {
1129       if (Current->Previous->BlockKind == BK_BracedInit &&
1130           Current->Previous->opensScope())
1131         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1132       else
1133         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1134 
1135       // If we find a trailing comment, iterate backwards to determine whether
1136       // it seems to relate to a specific parameter. If so, break before that
1137       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1138       // to the previous line in:
1139       //   SomeFunction(a,
1140       //                b, // comment
1141       //                c);
1142       if (!Current->HasUnescapedNewline) {
1143         for (FormatToken *Parameter = Current->Previous; Parameter;
1144              Parameter = Parameter->Previous) {
1145           if (Parameter->isOneOf(tok::comment, tok::r_brace))
1146             break;
1147           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1148             if (Parameter->Previous->Type != TT_CtorInitializerComma &&
1149                 Parameter->HasUnescapedNewline)
1150               Parameter->MustBreakBefore = true;
1151             break;
1152           }
1153         }
1154       }
1155     } else if (Current->SpacesRequiredBefore == 0 &&
1156              spaceRequiredBefore(Line, *Current)) {
1157       Current->SpacesRequiredBefore = 1;
1158     }
1159 
1160     Current->MustBreakBefore =
1161         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1162 
1163     Current->CanBreakBefore =
1164         Current->MustBreakBefore || canBreakBefore(Line, *Current);
1165     if (Current->MustBreakBefore || !Current->Children.empty() ||
1166         Current->IsMultiline)
1167       Current->TotalLength = Current->Previous->TotalLength + Style.ColumnLimit;
1168     else
1169       Current->TotalLength = Current->Previous->TotalLength +
1170                              Current->ColumnWidth +
1171                              Current->SpacesRequiredBefore;
1172 
1173     if (Current->Type == TT_CtorInitializerColon)
1174       InFunctionDecl = false;
1175 
1176     // FIXME: Only calculate this if CanBreakBefore is true once static
1177     // initializers etc. are sorted out.
1178     // FIXME: Move magic numbers to a better place.
1179     Current->SplitPenalty = 20 * Current->BindingStrength +
1180                             splitPenalty(Line, *Current, InFunctionDecl);
1181 
1182     Current = Current->Next;
1183   }
1184 
1185   calculateUnbreakableTailLengths(Line);
1186   for (Current = Line.First; Current != NULL; Current = Current->Next) {
1187     if (Current->Role)
1188       Current->Role->precomputeFormattingInfos(Current);
1189   }
1190 
1191   DEBUG({ printDebugInfo(Line); });
1192 
1193   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1194                                                   E = Line.Children.end();
1195        I != E; ++I) {
1196     calculateFormattingInformation(**I);
1197   }
1198 }
1199 
1200 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1201   unsigned UnbreakableTailLength = 0;
1202   FormatToken *Current = Line.Last;
1203   while (Current != NULL) {
1204     Current->UnbreakableTailLength = UnbreakableTailLength;
1205     if (Current->CanBreakBefore ||
1206         Current->isOneOf(tok::comment, tok::string_literal)) {
1207       UnbreakableTailLength = 0;
1208     } else {
1209       UnbreakableTailLength +=
1210           Current->ColumnWidth + Current->SpacesRequiredBefore;
1211     }
1212     Current = Current->Previous;
1213   }
1214 }
1215 
1216 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1217                                       const FormatToken &Tok,
1218                                       bool InFunctionDecl) {
1219   const FormatToken &Left = *Tok.Previous;
1220   const FormatToken &Right = Tok;
1221 
1222   if (Left.is(tok::semi))
1223     return 0;
1224   if (Left.is(tok::comma))
1225     return 1;
1226   if (Right.is(tok::l_square)) {
1227     if (Style.Language == FormatStyle::LK_Proto)
1228       return 1;
1229     if (Right.Type != TT_ObjCMethodExpr)
1230       return 250;
1231   }
1232   if (Right.Type == TT_StartOfName || Right.is(tok::kw_operator)) {
1233     if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1234       return 3;
1235     if (Left.Type == TT_StartOfName)
1236       return 20;
1237     if (InFunctionDecl && Right.NestingLevel == 0)
1238       return Style.PenaltyReturnTypeOnItsOwnLine;
1239     return 200;
1240   }
1241   if (Left.is(tok::equal) && Right.is(tok::l_brace))
1242     return 150;
1243   if (Left.Type == TT_CastRParen)
1244     return 100;
1245   if (Left.is(tok::coloncolon) ||
1246       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1247     return 500;
1248   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1249     return 5000;
1250 
1251   if (Left.Type == TT_RangeBasedForLoopColon ||
1252       Left.Type == TT_InheritanceColon)
1253     return 2;
1254 
1255   if (Right.isMemberAccess()) {
1256     if (Left.is(tok::r_paren) && Left.MatchingParen &&
1257         Left.MatchingParen->ParameterCount > 0)
1258       return 20; // Should be smaller than breaking at a nested comma.
1259     return 150;
1260   }
1261 
1262   if (Right.Type == TT_TrailingAnnotation && Right.Next &&
1263       Right.Next->isNot(tok::l_paren)) {
1264     // Generally, breaking before a trailing annotation is bad unless it is
1265     // function-like. It seems to be especially preferable to keep standard
1266     // annotations (i.e. "const", "final" and "override") on the same line.
1267     // Use a slightly higher penalty after ")" so that annotations like
1268     // "const override" are kept together.
1269     bool is_standard_annotation = Right.is(tok::kw_const) ||
1270                                   Right.TokenText == "override" ||
1271                                   Right.TokenText == "final";
1272     return (Left.is(tok::r_paren) ? 100 : 120) +
1273            (is_standard_annotation ? 50 : 0);
1274   }
1275 
1276   // In for-loops, prefer breaking at ',' and ';'.
1277   if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
1278     return 4;
1279 
1280   // In Objective-C method expressions, prefer breaking before "param:" over
1281   // breaking after it.
1282   if (Right.Type == TT_ObjCSelectorName)
1283     return 0;
1284   if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1285     return Line.MightBeFunctionDecl ? 50 : 500;
1286 
1287   if (Left.is(tok::l_paren) && InFunctionDecl)
1288     return 100;
1289   if (Left.is(tok::equal) && InFunctionDecl)
1290     return 110;
1291   if (Left.opensScope())
1292     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1293                                    : 19;
1294 
1295   if (Right.is(tok::lessless)) {
1296     if (Left.is(tok::string_literal)) {
1297       StringRef Content = Left.TokenText;
1298       if (Content.startswith("\""))
1299         Content = Content.drop_front(1);
1300       if (Content.endswith("\""))
1301         Content = Content.drop_back(1);
1302       Content = Content.trim();
1303       if (Content.size() > 1 &&
1304           (Content.back() == ':' || Content.back() == '='))
1305         return 25;
1306     }
1307     return 1; // Breaking at a << is really cheap.
1308   }
1309   if (Left.Type == TT_ConditionalExpr)
1310     return prec::Conditional;
1311   prec::Level Level = Left.getPrecedence();
1312 
1313   if (Level != prec::Unknown)
1314     return Level;
1315 
1316   return 3;
1317 }
1318 
1319 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1320                                           const FormatToken &Left,
1321                                           const FormatToken &Right) {
1322   if (Style.Language == FormatStyle::LK_Proto) {
1323     if (Right.is(tok::l_paren) &&
1324         (Left.TokenText == "returns" || Left.TokenText == "option"))
1325       return true;
1326   }
1327   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1328       Left.Tok.getObjCKeywordID() == tok::objc_property)
1329     return true;
1330   if (Right.is(tok::hashhash))
1331     return Left.is(tok::hash);
1332   if (Left.isOneOf(tok::hashhash, tok::hash))
1333     return Right.is(tok::hash);
1334   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1335     return Style.SpaceInEmptyParentheses;
1336   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1337     return (Right.Type == TT_CastRParen ||
1338             (Left.MatchingParen && Left.MatchingParen->Type == TT_CastRParen))
1339                ? Style.SpacesInCStyleCastParentheses
1340                : Style.SpacesInParentheses;
1341   if (Style.SpacesInAngles &&
1342       ((Left.Type == TT_TemplateOpener) != (Right.Type == TT_TemplateCloser)))
1343     return true;
1344   if (Right.isOneOf(tok::semi, tok::comma))
1345     return false;
1346   if (Right.is(tok::less) &&
1347       (Left.is(tok::kw_template) ||
1348        (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1349     return true;
1350   if (Left.is(tok::arrow) || Right.is(tok::arrow))
1351     return false;
1352   if (Left.isOneOf(tok::exclaim, tok::tilde))
1353     return false;
1354   if (Left.is(tok::at) &&
1355       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1356                     tok::numeric_constant, tok::l_paren, tok::l_brace,
1357                     tok::kw_true, tok::kw_false))
1358     return false;
1359   if (Left.is(tok::coloncolon))
1360     return false;
1361   if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
1362     return (Left.is(tok::less) && Style.Standard == FormatStyle::LS_Cpp03) ||
1363            !Left.isOneOf(tok::identifier, tok::greater, tok::l_paren,
1364                          tok::r_paren, tok::less);
1365   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1366     return false;
1367   if (Right.is(tok::ellipsis))
1368     return Left.Tok.isLiteral();
1369   if (Left.is(tok::l_square) && Right.is(tok::amp))
1370     return false;
1371   if (Right.Type == TT_PointerOrReference)
1372     return Left.Tok.isLiteral() ||
1373            ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
1374             !Style.PointerBindsToType);
1375   if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
1376       (Left.Type != TT_PointerOrReference || Style.PointerBindsToType))
1377     return true;
1378   if (Left.Type == TT_PointerOrReference)
1379     return Right.Tok.isLiteral() || Right.Type == TT_BlockComment ||
1380            ((Right.Type != TT_PointerOrReference) &&
1381             Right.isNot(tok::l_paren) && Style.PointerBindsToType &&
1382             Left.Previous &&
1383             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1384   if (Right.is(tok::star) && Left.is(tok::l_paren))
1385     return false;
1386   if (Left.is(tok::l_square))
1387     return Left.Type == TT_ArrayInitializerLSquare &&
1388            Style.SpacesInContainerLiterals && Right.isNot(tok::r_square);
1389   if (Right.is(tok::r_square))
1390     return Right.MatchingParen && Style.SpacesInContainerLiterals &&
1391            Right.MatchingParen->Type == TT_ArrayInitializerLSquare;
1392   if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr &&
1393       Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant))
1394     return false;
1395   if (Left.is(tok::colon))
1396     return Left.Type != TT_ObjCMethodExpr;
1397   if (Right.is(tok::l_paren)) {
1398     if (Left.is(tok::r_paren) && Left.Type == TT_AttributeParen)
1399       return true;
1400     return Line.Type == LT_ObjCDecl ||
1401            Left.isOneOf(tok::kw_return, tok::kw_new, tok::kw_delete,
1402                         tok::semi) ||
1403            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1404             Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
1405                          tok::kw_catch)) ||
1406            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1407             Left.isOneOf(tok::identifier, tok::kw___attribute) &&
1408             Line.Type != LT_PreprocessorDirective);
1409   }
1410   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1411     return false;
1412   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1413     return !Left.Children.empty(); // No spaces in "{}".
1414   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1415       (Right.is(tok::r_brace) && Right.MatchingParen &&
1416        Right.MatchingParen->BlockKind != BK_Block))
1417     return !Style.Cpp11BracedListStyle;
1418   if (Left.Type == TT_BlockComment && Left.TokenText.endswith("=*/"))
1419     return false;
1420   if (Right.Type == TT_UnaryOperator)
1421     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1422            (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
1423   if (Left.isOneOf(tok::identifier, tok::greater, tok::r_square) &&
1424       Right.is(tok::l_brace) && Right.getNextNonComment() &&
1425       Right.BlockKind != BK_Block)
1426     return false;
1427   if (Left.is(tok::period) || Right.is(tok::period))
1428     return false;
1429   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1430     return false;
1431   return true;
1432 }
1433 
1434 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1435                                          const FormatToken &Tok) {
1436   if (Tok.Tok.getIdentifierInfo() && Tok.Previous->Tok.getIdentifierInfo())
1437     return true; // Never ever merge two identifiers.
1438   if (Tok.Previous->Type == TT_ImplicitStringLiteral)
1439     return Tok.WhitespaceRange.getBegin() != Tok.WhitespaceRange.getEnd();
1440   if (Line.Type == LT_ObjCMethodDecl) {
1441     if (Tok.Previous->Type == TT_ObjCMethodSpecifier)
1442       return true;
1443     if (Tok.Previous->is(tok::r_paren) && Tok.is(tok::identifier))
1444       // Don't space between ')' and <id>
1445       return false;
1446   }
1447   if (Line.Type == LT_ObjCProperty &&
1448       (Tok.is(tok::equal) || Tok.Previous->is(tok::equal)))
1449     return false;
1450 
1451   if (Tok.Type == TT_TrailingReturnArrow ||
1452       Tok.Previous->Type == TT_TrailingReturnArrow)
1453     return true;
1454   if (Tok.Previous->is(tok::comma))
1455     return true;
1456   if (Tok.is(tok::comma))
1457     return false;
1458   if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
1459     return true;
1460   if (Tok.Previous->Tok.is(tok::kw_operator))
1461     return Tok.is(tok::coloncolon);
1462   if (Tok.Type == TT_OverloadedOperatorLParen)
1463     return false;
1464   if (Tok.is(tok::colon))
1465     return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
1466            Tok.getNextNonComment() != NULL && Tok.Type != TT_ObjCMethodExpr &&
1467            !Tok.Previous->is(tok::question) &&
1468            (Tok.Type != TT_DictLiteral || Style.SpacesInContainerLiterals);
1469   if (Tok.Previous->Type == TT_UnaryOperator ||
1470       Tok.Previous->Type == TT_CastRParen)
1471     return Tok.Type == TT_BinaryOperator;
1472   if (Tok.Previous->is(tok::greater) && Tok.is(tok::greater)) {
1473     return Tok.Type == TT_TemplateCloser &&
1474            Tok.Previous->Type == TT_TemplateCloser &&
1475            (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
1476   }
1477   if (Tok.isOneOf(tok::arrowstar, tok::periodstar) ||
1478       Tok.Previous->isOneOf(tok::arrowstar, tok::periodstar))
1479     return false;
1480   if (!Style.SpaceBeforeAssignmentOperators &&
1481       Tok.getPrecedence() == prec::Assignment)
1482     return false;
1483   if ((Tok.Type == TT_BinaryOperator && !Tok.Previous->is(tok::l_paren)) ||
1484       Tok.Previous->Type == TT_BinaryOperator)
1485     return true;
1486   if (Tok.Previous->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
1487     return false;
1488   if (Tok.is(tok::less) && Tok.Previous->isNot(tok::l_paren) &&
1489       Line.First->is(tok::hash))
1490     return true;
1491   if (Tok.Type == TT_TrailingUnaryOperator)
1492     return false;
1493   return spaceRequiredBetween(Line, *Tok.Previous, Tok);
1494 }
1495 
1496 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
1497                                      const FormatToken &Right) {
1498   const FormatToken &Left = *Right.Previous;
1499   if (Right.is(tok::comment)) {
1500     return Right.Previous->BlockKind != BK_BracedInit &&
1501            Right.Previous->Type != TT_CtorInitializerColon &&
1502            Right.NewlinesBefore > 0;
1503   } else if (Right.Previous->isTrailingComment() ||
1504              (Right.isStringLiteral() && Right.Previous->isStringLiteral())) {
1505     return true;
1506   } else if (Right.Previous->IsUnterminatedLiteral) {
1507     return true;
1508   } else if (Right.is(tok::lessless) && Right.Next &&
1509              Right.Previous->is(tok::string_literal) &&
1510              Right.Next->is(tok::string_literal)) {
1511     return true;
1512   } else if (Right.Previous->ClosesTemplateDeclaration &&
1513              Right.Previous->MatchingParen &&
1514              Right.Previous->MatchingParen->NestingLevel == 0 &&
1515              Style.AlwaysBreakTemplateDeclarations) {
1516     return true;
1517   } else if ((Right.Type == TT_CtorInitializerComma ||
1518               Right.Type == TT_CtorInitializerColon) &&
1519              Style.BreakConstructorInitializersBeforeComma &&
1520              !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
1521     return true;
1522   } else if (Right.is(tok::l_brace) && (Right.BlockKind == BK_Block)) {
1523     return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1524            Style.BreakBeforeBraces == FormatStyle::BS_GNU;
1525   } else if (Right.is(tok::string_literal) &&
1526              Right.TokenText.startswith("R\"")) {
1527     // Raw string literals are special wrt. line breaks. The author has made a
1528     // deliberate choice and might have aligned the contents of the string
1529     // literal accordingly. Thus, we try keep existing line breaks.
1530     return Right.NewlinesBefore > 0;
1531   } else if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
1532              Style.Language == FormatStyle::LK_Proto) {
1533     // Don't enums onto single lines in protocol buffers.
1534     return true;
1535   } else if ((Left.is(tok::l_brace) && Left.MatchingParen &&
1536               Left.MatchingParen->Previous &&
1537               Left.MatchingParen->Previous->is(tok::comma)) ||
1538              (Right.is(tok::r_brace) && Left.is(tok::comma))) {
1539     // If the last token before a '}' is a comma, the intention is to insert a
1540     // line break after it in order to make shuffling around entries easier.
1541     return true;
1542   }
1543   return false;
1544 }
1545 
1546 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
1547                                     const FormatToken &Right) {
1548   const FormatToken &Left = *Right.Previous;
1549   if (Left.is(tok::at))
1550     return false;
1551   if (Right.Type == TT_StartOfName || Right.is(tok::kw_operator))
1552     return true;
1553   if (Right.isTrailingComment())
1554     // We rely on MustBreakBefore being set correctly here as we should not
1555     // change the "binding" behavior of a comment.
1556     // The first comment in a braced lists is always interpreted as belonging to
1557     // the first list element. Otherwise, it should be placed outside of the
1558     // list.
1559     return Left.BlockKind == BK_BracedInit;
1560   if (Left.is(tok::question) && Right.is(tok::colon))
1561     return false;
1562   if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1563     return Style.BreakBeforeTernaryOperators;
1564   if (Left.Type == TT_ConditionalExpr || Left.is(tok::question))
1565     return !Style.BreakBeforeTernaryOperators;
1566   if (Right.is(tok::colon) &&
1567       (Right.Type == TT_DictLiteral || Right.Type == TT_ObjCMethodExpr))
1568     return false;
1569   if (Right.Type == TT_InheritanceColon)
1570     return true;
1571   if (Left.is(tok::colon) &&
1572       (Left.Type == TT_DictLiteral || Left.Type == TT_ObjCMethodExpr))
1573     return true;
1574   if (Right.Type == TT_ObjCSelectorName)
1575     return true;
1576   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
1577     return true;
1578   if (Left.ClosesTemplateDeclaration)
1579     return true;
1580   if (Right.Type == TT_RangeBasedForLoopColon ||
1581       Right.Type == TT_OverloadedOperatorLParen ||
1582       Right.Type == TT_OverloadedOperator)
1583     return false;
1584   if (Left.Type == TT_RangeBasedForLoopColon)
1585     return true;
1586   if (Right.Type == TT_RangeBasedForLoopColon)
1587     return false;
1588   if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
1589       Left.Type == TT_UnaryOperator || Left.is(tok::kw_operator))
1590     return false;
1591   if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
1592     return false;
1593   if (Left.is(tok::l_paren) && Left.Type == TT_AttributeParen)
1594     return false;
1595   if (Left.is(tok::l_paren) && Left.Previous &&
1596       (Left.Previous->Type == TT_BinaryOperator ||
1597        Left.Previous->Type == TT_CastRParen))
1598     return false;
1599   if (Right.Type == TT_ImplicitStringLiteral)
1600     return false;
1601 
1602   if (Right.is(tok::r_paren) || Right.Type == TT_TemplateCloser)
1603     return false;
1604 
1605   // We only break before r_brace if there was a corresponding break before
1606   // the l_brace, which is tracked by BreakBeforeClosingBrace.
1607   if (Right.is(tok::r_brace))
1608     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
1609 
1610   // Allow breaking after a trailing 'const', e.g. after a method declaration,
1611   // unless it is follow by ';', '{' or '='.
1612   if (Left.is(tok::kw_const) && Left.Previous != NULL &&
1613       Left.Previous->is(tok::r_paren))
1614     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal);
1615 
1616   if (Right.is(tok::kw___attribute))
1617     return true;
1618 
1619   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
1620     return true;
1621 
1622   if (Left.Type == TT_CtorInitializerComma &&
1623       Style.BreakConstructorInitializersBeforeComma)
1624     return false;
1625   if (Right.Type == TT_CtorInitializerComma &&
1626       Style.BreakConstructorInitializersBeforeComma)
1627     return true;
1628   if (Right.Type == TT_BinaryOperator && Style.BreakBeforeBinaryOperators)
1629     return true;
1630   if (Left.is(tok::greater) && Right.is(tok::greater) &&
1631       Left.Type != TT_TemplateCloser)
1632     return false;
1633   if (Left.Type == TT_ArrayInitializerLSquare)
1634     return true;
1635   return (Left.isBinaryOperator() && Left.isNot(tok::lessless) &&
1636           !Style.BreakBeforeBinaryOperators) ||
1637          Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
1638                       tok::kw_class, tok::kw_struct) ||
1639          Right.isOneOf(tok::lessless, tok::arrow, tok::period, tok::colon,
1640                        tok::l_square, tok::at) ||
1641          (Left.is(tok::r_paren) &&
1642           Right.isOneOf(tok::identifier, tok::kw_const)) ||
1643          (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
1644 }
1645 
1646 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
1647   llvm::errs() << "AnnotatedTokens:\n";
1648   const FormatToken *Tok = Line.First;
1649   while (Tok) {
1650     llvm::errs() << " M=" << Tok->MustBreakBefore
1651                  << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
1652                  << " S=" << Tok->SpacesRequiredBefore
1653                  << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
1654                  << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
1655                  << " FakeLParens=";
1656     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
1657       llvm::errs() << Tok->FakeLParens[i] << "/";
1658     llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
1659     if (Tok->Next == NULL)
1660       assert(Tok == Line.Last);
1661     Tok = Tok->Next;
1662   }
1663   llvm::errs() << "----\n";
1664 }
1665 
1666 } // namespace format
1667 } // namespace clang
1668