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