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