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     if (Style.Language == FormatStyle::LK_JavaScript && Tok.Next &&
872         Tok.Next->TokenText == "in")
873       return false;
874     bool ParensCouldEndDecl =
875         Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
876     bool IsSizeOfOrAlignOf =
877         LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
878     if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
879         ((Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression) ||
880          (Tok.Next && Tok.Next->isBinaryOperator())))
881       IsCast = true;
882     else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
883              (Tok.Next->Tok.isLiteral() ||
884               Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
885       IsCast = true;
886     // If there is an identifier after the (), it is likely a cast, unless
887     // there is also an identifier before the ().
888     else if (LeftOfParens &&
889              (LeftOfParens->Tok.getIdentifierInfo() == nullptr ||
890               LeftOfParens->is(tok::kw_return)) &&
891              LeftOfParens->Type != TT_OverloadedOperator &&
892              LeftOfParens->isNot(tok::at) &&
893              LeftOfParens->Type != TT_TemplateCloser && Tok.Next) {
894       if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
895         IsCast = true;
896       } else {
897         // Use heuristics to recognize c style casting.
898         FormatToken *Prev = Tok.Previous;
899         if (Prev && Prev->isOneOf(tok::amp, tok::star))
900           Prev = Prev->Previous;
901 
902         if (Prev && Tok.Next && Tok.Next->Next) {
903           bool NextIsUnary = Tok.Next->isUnaryOperator() ||
904                              Tok.Next->isOneOf(tok::amp, tok::star);
905           IsCast =
906               NextIsUnary && !Tok.Next->is(tok::plus) &&
907               Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant);
908         }
909 
910         for (; Prev != Tok.MatchingParen; Prev = Prev->Previous) {
911           if (!Prev || !Prev->isOneOf(tok::kw_const, tok::identifier)) {
912             IsCast = false;
913             break;
914           }
915         }
916       }
917     }
918     return IsCast && !ParensAreEmpty;
919   }
920 
921   /// \brief Return the type of the given token assuming it is * or &.
922   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
923                                   bool InTemplateArgument) {
924     if (Style.Language == FormatStyle::LK_JavaScript)
925       return TT_BinaryOperator;
926 
927     const FormatToken *PrevToken = Tok.getPreviousNonComment();
928     if (!PrevToken)
929       return TT_UnaryOperator;
930 
931     const FormatToken *NextToken = Tok.getNextNonComment();
932     if (!NextToken || NextToken->is(tok::l_brace))
933       return TT_Unknown;
934 
935     if (PrevToken->is(tok::coloncolon))
936       return TT_PointerOrReference;
937 
938     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
939                            tok::comma, tok::semi, tok::kw_return, tok::colon,
940                            tok::equal, tok::kw_delete, tok::kw_sizeof) ||
941         PrevToken->Type == TT_BinaryOperator ||
942         PrevToken->Type == TT_ConditionalExpr ||
943         PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
944       return TT_UnaryOperator;
945 
946     if (NextToken->is(tok::l_square) && NextToken->Type != TT_LambdaLSquare)
947       return TT_PointerOrReference;
948     if (NextToken->isOneOf(tok::kw_operator, tok::comma))
949       return TT_PointerOrReference;
950 
951     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
952         PrevToken->MatchingParen->Previous &&
953         PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
954                                                     tok::kw_decltype))
955       return TT_PointerOrReference;
956 
957     if (PrevToken->Tok.isLiteral() ||
958         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
959                            tok::kw_false) ||
960         NextToken->Tok.isLiteral() ||
961         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
962         NextToken->isUnaryOperator() ||
963         // If we know we're in a template argument, there are no named
964         // declarations. Thus, having an identifier on the right-hand side
965         // indicates a binary operator.
966         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
967       return TT_BinaryOperator;
968 
969     // This catches some cases where evaluation order is used as control flow:
970     //   aaa && aaa->f();
971     const FormatToken *NextNextToken = NextToken->getNextNonComment();
972     if (NextNextToken && NextNextToken->is(tok::arrow))
973       return TT_BinaryOperator;
974 
975     // It is very unlikely that we are going to find a pointer or reference type
976     // definition on the RHS of an assignment.
977     if (IsExpression)
978       return TT_BinaryOperator;
979 
980     return TT_PointerOrReference;
981   }
982 
983   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
984     const FormatToken *PrevToken = Tok.getPreviousNonComment();
985     if (!PrevToken || PrevToken->Type == TT_CastRParen)
986       return TT_UnaryOperator;
987 
988     // Use heuristics to recognize unary operators.
989     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
990                            tok::question, tok::colon, tok::kw_return,
991                            tok::kw_case, tok::at, tok::l_brace))
992       return TT_UnaryOperator;
993 
994     // There can't be two consecutive binary operators.
995     if (PrevToken->Type == TT_BinaryOperator)
996       return TT_UnaryOperator;
997 
998     // Fall back to marking the token as binary operator.
999     return TT_BinaryOperator;
1000   }
1001 
1002   /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1003   TokenType determineIncrementUsage(const FormatToken &Tok) {
1004     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1005     if (!PrevToken || PrevToken->Type == TT_CastRParen)
1006       return TT_UnaryOperator;
1007     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1008       return TT_TrailingUnaryOperator;
1009 
1010     return TT_UnaryOperator;
1011   }
1012 
1013   SmallVector<Context, 8> Contexts;
1014 
1015   const FormatStyle &Style;
1016   AnnotatedLine &Line;
1017   FormatToken *CurrentToken;
1018   bool KeywordVirtualFound;
1019   bool AutoFound;
1020   IdentifierInfo &Ident_in;
1021 };
1022 
1023 static int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1024 static int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1025 
1026 /// \brief Parses binary expressions by inserting fake parenthesis based on
1027 /// operator precedence.
1028 class ExpressionParser {
1029 public:
1030   ExpressionParser(AnnotatedLine &Line) : Current(Line.First) {
1031     // Skip leading "}", e.g. in "} else if (...) {".
1032     if (Current->is(tok::r_brace))
1033       next();
1034   }
1035 
1036   /// \brief Parse expressions with the given operatore precedence.
1037   void parse(int Precedence = 0) {
1038     // Skip 'return' and ObjC selector colons as they are not part of a binary
1039     // expression.
1040     while (Current &&
1041            (Current->is(tok::kw_return) ||
1042             (Current->is(tok::colon) && (Current->Type == TT_ObjCMethodExpr ||
1043                                          Current->Type == TT_DictLiteral))))
1044       next();
1045 
1046     if (!Current || Precedence > PrecedenceArrowAndPeriod)
1047       return;
1048 
1049     // Conditional expressions need to be parsed separately for proper nesting.
1050     if (Precedence == prec::Conditional) {
1051       parseConditionalExpr();
1052       return;
1053     }
1054 
1055     // Parse unary operators, which all have a higher precedence than binary
1056     // operators.
1057     if (Precedence == PrecedenceUnaryOperator) {
1058       parseUnaryOperator();
1059       return;
1060     }
1061 
1062     FormatToken *Start = Current;
1063     FormatToken *LatestOperator = nullptr;
1064     unsigned OperatorIndex = 0;
1065 
1066     while (Current) {
1067       // Consume operators with higher precedence.
1068       parse(Precedence + 1);
1069 
1070       int CurrentPrecedence = getCurrentPrecedence();
1071 
1072       if (Current && Current->Type == TT_SelectorName &&
1073           Precedence == CurrentPrecedence) {
1074         if (LatestOperator)
1075           addFakeParenthesis(Start, prec::Level(Precedence));
1076         Start = Current;
1077       }
1078 
1079       // At the end of the line or when an operator with higher precedence is
1080       // found, insert fake parenthesis and return.
1081       if (!Current || Current->closesScope() ||
1082           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence)) {
1083         if (LatestOperator) {
1084           LatestOperator->LastOperator = true;
1085           if (Precedence == PrecedenceArrowAndPeriod) {
1086             // Call expressions don't have a binary operator precedence.
1087             addFakeParenthesis(Start, prec::Unknown);
1088           } else {
1089             addFakeParenthesis(Start, prec::Level(Precedence));
1090           }
1091         }
1092         return;
1093       }
1094 
1095       // Consume scopes: (), [], <> and {}
1096       if (Current->opensScope()) {
1097         while (Current && !Current->closesScope()) {
1098           next();
1099           parse();
1100         }
1101         next();
1102       } else {
1103         // Operator found.
1104         if (CurrentPrecedence == Precedence) {
1105           LatestOperator = Current;
1106           Current->OperatorIndex = OperatorIndex;
1107           ++OperatorIndex;
1108         }
1109 
1110         next(/*SkipPastLeadingComments=*/false);
1111       }
1112     }
1113   }
1114 
1115 private:
1116   /// \brief Gets the precedence (+1) of the given token for binary operators
1117   /// and other tokens that we treat like binary operators.
1118   int getCurrentPrecedence() {
1119     if (Current) {
1120       const FormatToken *NextNonComment = Current->getNextNonComment();
1121       if (Current->Type == TT_ConditionalExpr)
1122         return prec::Conditional;
1123       else if (NextNonComment && NextNonComment->is(tok::colon) &&
1124                NextNonComment->Type == TT_DictLiteral)
1125         return prec::Comma;
1126       else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
1127                Current->Type == TT_SelectorName ||
1128                (Current->is(tok::comment) && NextNonComment &&
1129                 NextNonComment->Type == TT_SelectorName))
1130         return 0;
1131       else if (Current->Type == TT_RangeBasedForLoopColon)
1132         return prec::Comma;
1133       else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
1134         return Current->getPrecedence();
1135       else if (Current->isOneOf(tok::period, tok::arrow))
1136         return PrecedenceArrowAndPeriod;
1137     }
1138     return -1;
1139   }
1140 
1141   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1142     Start->FakeLParens.push_back(Precedence);
1143     if (Precedence > prec::Unknown)
1144       Start->StartsBinaryExpression = true;
1145     if (Current) {
1146       ++Current->Previous->FakeRParens;
1147       if (Precedence > prec::Unknown)
1148         Current->Previous->EndsBinaryExpression = true;
1149     }
1150   }
1151 
1152   /// \brief Parse unary operator expressions and surround them with fake
1153   /// parentheses if appropriate.
1154   void parseUnaryOperator() {
1155     if (!Current || Current->Type != TT_UnaryOperator) {
1156       parse(PrecedenceArrowAndPeriod);
1157       return;
1158     }
1159 
1160     FormatToken *Start = Current;
1161     next();
1162     parseUnaryOperator();
1163 
1164     // The actual precedence doesn't matter.
1165     addFakeParenthesis(Start, prec::Unknown);
1166   }
1167 
1168   void parseConditionalExpr() {
1169     FormatToken *Start = Current;
1170     parse(prec::LogicalOr);
1171     if (!Current || !Current->is(tok::question))
1172       return;
1173     next();
1174     parseConditionalExpr();
1175     if (!Current || Current->Type != TT_ConditionalExpr)
1176       return;
1177     next();
1178     parseConditionalExpr();
1179     addFakeParenthesis(Start, prec::Conditional);
1180   }
1181 
1182   void next(bool SkipPastLeadingComments = true) {
1183     if (Current)
1184       Current = Current->Next;
1185     while (Current &&
1186            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1187            Current->isTrailingComment())
1188       Current = Current->Next;
1189   }
1190 
1191   FormatToken *Current;
1192 };
1193 
1194 } // end anonymous namespace
1195 
1196 void
1197 TokenAnnotator::setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) {
1198   const AnnotatedLine *NextNonCommentLine = nullptr;
1199   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1200                                                           E = Lines.rend();
1201        I != E; ++I) {
1202     if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1203         (*I)->First->Next == nullptr)
1204       (*I)->Level = NextNonCommentLine->Level;
1205     else
1206       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1207 
1208     setCommentLineLevels((*I)->Children);
1209   }
1210 }
1211 
1212 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1213   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1214                                                   E = Line.Children.end();
1215        I != E; ++I) {
1216     annotate(**I);
1217   }
1218   AnnotatingParser Parser(Style, Line, Ident_in);
1219   Line.Type = Parser.parseLine();
1220   if (Line.Type == LT_Invalid)
1221     return;
1222 
1223   ExpressionParser ExprParser(Line);
1224   ExprParser.parse();
1225 
1226   if (Line.First->Type == TT_ObjCMethodSpecifier)
1227     Line.Type = LT_ObjCMethodDecl;
1228   else if (Line.First->Type == TT_ObjCDecl)
1229     Line.Type = LT_ObjCDecl;
1230   else if (Line.First->Type == TT_ObjCProperty)
1231     Line.Type = LT_ObjCProperty;
1232 
1233   Line.First->SpacesRequiredBefore = 1;
1234   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1235 }
1236 
1237 // This function heuristically determines whether 'Current' starts the name of a
1238 // function declaration.
1239 static bool isFunctionDeclarationName(const FormatToken &Current) {
1240   if (Current.Type != TT_StartOfName ||
1241       Current.NestingLevel != 0 ||
1242       Current.Previous->Type == TT_StartOfName)
1243     return false;
1244   const FormatToken *Next = Current.Next;
1245   for (; Next; Next = Next->Next) {
1246     if (Next->Type == TT_TemplateOpener) {
1247       Next = Next->MatchingParen;
1248     } else if (Next->is(tok::coloncolon)) {
1249       Next = Next->Next;
1250       if (!Next || !Next->is(tok::identifier))
1251         return false;
1252     } else if (Next->is(tok::l_paren)) {
1253       break;
1254     } else {
1255       return false;
1256     }
1257   }
1258   if (!Next)
1259     return false;
1260   assert(Next->is(tok::l_paren));
1261   if (Next->Next == Next->MatchingParen)
1262     return true;
1263   for (const FormatToken *Tok = Next->Next; Tok != Next->MatchingParen;
1264        Tok = Tok->Next) {
1265     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1266         Tok->Type == TT_PointerOrReference || Tok->Type == TT_StartOfName)
1267       return true;
1268     if (Tok->isOneOf(tok::l_brace, tok::string_literal) || Tok->Tok.isLiteral())
1269       return false;
1270   }
1271   return false;
1272 }
1273 
1274 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1275   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1276                                                   E = Line.Children.end();
1277        I != E; ++I) {
1278     calculateFormattingInformation(**I);
1279   }
1280 
1281   Line.First->TotalLength =
1282       Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1283   if (!Line.First->Next)
1284     return;
1285   FormatToken *Current = Line.First->Next;
1286   bool InFunctionDecl = Line.MightBeFunctionDecl;
1287   while (Current) {
1288     if (isFunctionDeclarationName(*Current))
1289       Current->Type = TT_FunctionDeclarationName;
1290     if (Current->Type == TT_LineComment) {
1291       if (Current->Previous->BlockKind == BK_BracedInit &&
1292           Current->Previous->opensScope())
1293         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1294       else
1295         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1296 
1297       // If we find a trailing comment, iterate backwards to determine whether
1298       // it seems to relate to a specific parameter. If so, break before that
1299       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1300       // to the previous line in:
1301       //   SomeFunction(a,
1302       //                b, // comment
1303       //                c);
1304       if (!Current->HasUnescapedNewline) {
1305         for (FormatToken *Parameter = Current->Previous; Parameter;
1306              Parameter = Parameter->Previous) {
1307           if (Parameter->isOneOf(tok::comment, tok::r_brace))
1308             break;
1309           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1310             if (Parameter->Previous->Type != TT_CtorInitializerComma &&
1311                 Parameter->HasUnescapedNewline)
1312               Parameter->MustBreakBefore = true;
1313             break;
1314           }
1315         }
1316       }
1317     } else if (Current->SpacesRequiredBefore == 0 &&
1318                spaceRequiredBefore(Line, *Current)) {
1319       Current->SpacesRequiredBefore = 1;
1320     }
1321 
1322     Current->MustBreakBefore =
1323         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1324 
1325     if (Style.AlwaysBreakAfterDefinitionReturnType &&
1326         InFunctionDecl && Current->Type == TT_FunctionDeclarationName &&
1327         !Line.Last->isOneOf(tok::semi, tok::comment))  // Only for definitions.
1328       // FIXME: Line.Last points to other characters than tok::semi
1329       // and tok::lbrace.
1330       Current->MustBreakBefore = true;
1331 
1332     Current->CanBreakBefore =
1333         Current->MustBreakBefore || canBreakBefore(Line, *Current);
1334     unsigned ChildSize = 0;
1335     if (Current->Previous->Children.size() == 1) {
1336       FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1337       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1338                                                   : LastOfChild.TotalLength + 1;
1339     }
1340     if (Current->MustBreakBefore || Current->Previous->Children.size() > 1 ||
1341         Current->IsMultiline)
1342       Current->TotalLength = Current->Previous->TotalLength + Style.ColumnLimit;
1343     else
1344       Current->TotalLength = Current->Previous->TotalLength +
1345                              Current->ColumnWidth + ChildSize +
1346                              Current->SpacesRequiredBefore;
1347 
1348     if (Current->Type == TT_CtorInitializerColon)
1349       InFunctionDecl = false;
1350 
1351     // FIXME: Only calculate this if CanBreakBefore is true once static
1352     // initializers etc. are sorted out.
1353     // FIXME: Move magic numbers to a better place.
1354     Current->SplitPenalty = 20 * Current->BindingStrength +
1355                             splitPenalty(Line, *Current, InFunctionDecl);
1356 
1357     Current = Current->Next;
1358   }
1359 
1360   calculateUnbreakableTailLengths(Line);
1361   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1362     if (Current->Role)
1363       Current->Role->precomputeFormattingInfos(Current);
1364   }
1365 
1366   DEBUG({ printDebugInfo(Line); });
1367 }
1368 
1369 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1370   unsigned UnbreakableTailLength = 0;
1371   FormatToken *Current = Line.Last;
1372   while (Current) {
1373     Current->UnbreakableTailLength = UnbreakableTailLength;
1374     if (Current->CanBreakBefore ||
1375         Current->isOneOf(tok::comment, tok::string_literal)) {
1376       UnbreakableTailLength = 0;
1377     } else {
1378       UnbreakableTailLength +=
1379           Current->ColumnWidth + Current->SpacesRequiredBefore;
1380     }
1381     Current = Current->Previous;
1382   }
1383 }
1384 
1385 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1386                                       const FormatToken &Tok,
1387                                       bool InFunctionDecl) {
1388   const FormatToken &Left = *Tok.Previous;
1389   const FormatToken &Right = Tok;
1390 
1391   if (Left.is(tok::semi))
1392     return 0;
1393   if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1394                               Right.Next->Type == TT_DictLiteral))
1395     return 1;
1396   if (Right.is(tok::l_square)) {
1397     if (Style.Language == FormatStyle::LK_Proto)
1398       return 1;
1399     if (Right.Type != TT_ObjCMethodExpr && Right.Type != TT_LambdaLSquare)
1400       return 500;
1401   }
1402   if (Right.Type == TT_StartOfName ||
1403       Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator)) {
1404     if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1405       return 3;
1406     if (Left.Type == TT_StartOfName)
1407       return 20;
1408     if (InFunctionDecl && Right.NestingLevel == 0)
1409       return Style.PenaltyReturnTypeOnItsOwnLine;
1410     return 200;
1411   }
1412   if (Left.is(tok::equal) && Right.is(tok::l_brace))
1413     return 150;
1414   if (Left.Type == TT_CastRParen)
1415     return 100;
1416   if (Left.is(tok::coloncolon) ||
1417       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1418     return 500;
1419   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1420     return 5000;
1421 
1422   if (Left.Type == TT_RangeBasedForLoopColon ||
1423       Left.Type == TT_InheritanceColon)
1424     return 2;
1425 
1426   if (Right.isMemberAccess()) {
1427     if (Left.is(tok::r_paren) && Left.MatchingParen &&
1428         Left.MatchingParen->ParameterCount > 0)
1429       return 20; // Should be smaller than breaking at a nested comma.
1430     return 150;
1431   }
1432 
1433   if (Right.Type == TT_TrailingAnnotation &&
1434       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1435     // Generally, breaking before a trailing annotation is bad unless it is
1436     // function-like. It seems to be especially preferable to keep standard
1437     // annotations (i.e. "const", "final" and "override") on the same line.
1438     // Use a slightly higher penalty after ")" so that annotations like
1439     // "const override" are kept together.
1440     bool is_short_annotation = Right.TokenText.size() < 10;
1441     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1442   }
1443 
1444   // In for-loops, prefer breaking at ',' and ';'.
1445   if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
1446     return 4;
1447 
1448   // In Objective-C method expressions, prefer breaking before "param:" over
1449   // breaking after it.
1450   if (Right.Type == TT_SelectorName)
1451     return 0;
1452   if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1453     return Line.MightBeFunctionDecl ? 50 : 500;
1454 
1455   if (Left.is(tok::l_paren) && InFunctionDecl)
1456     return 100;
1457   if (Left.is(tok::equal) && InFunctionDecl)
1458     return 110;
1459   if (Right.is(tok::r_brace))
1460     return 1;
1461   if (Left.Type == TT_TemplateOpener)
1462     return 100;
1463   if (Left.opensScope())
1464     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1465                                    : 19;
1466 
1467   if (Right.is(tok::lessless)) {
1468     if (Left.is(tok::string_literal)) {
1469       StringRef Content = Left.TokenText;
1470       if (Content.startswith("\""))
1471         Content = Content.drop_front(1);
1472       if (Content.endswith("\""))
1473         Content = Content.drop_back(1);
1474       Content = Content.trim();
1475       if (Content.size() > 1 &&
1476           (Content.back() == ':' || Content.back() == '='))
1477         return 25;
1478     }
1479     return 1; // Breaking at a << is really cheap.
1480   }
1481   if (Left.Type == TT_ConditionalExpr)
1482     return prec::Conditional;
1483   prec::Level Level = Left.getPrecedence();
1484 
1485   if (Level != prec::Unknown)
1486     return Level;
1487 
1488   return 3;
1489 }
1490 
1491 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1492                                           const FormatToken &Left,
1493                                           const FormatToken &Right) {
1494   if (Style.Language == FormatStyle::LK_Proto) {
1495     if (Right.is(tok::period) &&
1496         (Left.TokenText == "optional" || Left.TokenText == "required" ||
1497          Left.TokenText == "repeated"))
1498       return true;
1499     if (Right.is(tok::l_paren) &&
1500         (Left.TokenText == "returns" || Left.TokenText == "option"))
1501       return true;
1502   } else if (Style.Language == FormatStyle::LK_JavaScript) {
1503     if (Left.TokenText == "var")
1504       return true;
1505   }
1506   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1507     return true;
1508   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1509       Left.Tok.getObjCKeywordID() == tok::objc_property)
1510     return true;
1511   if (Right.is(tok::hashhash))
1512     return Left.is(tok::hash);
1513   if (Left.isOneOf(tok::hashhash, tok::hash))
1514     return Right.is(tok::hash);
1515   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1516     return Style.SpaceInEmptyParentheses;
1517   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1518     return (Right.Type == TT_CastRParen ||
1519             (Left.MatchingParen && Left.MatchingParen->Type == TT_CastRParen))
1520                ? Style.SpacesInCStyleCastParentheses
1521                : Style.SpacesInParentheses;
1522   if (Style.SpacesInAngles &&
1523       ((Left.Type == TT_TemplateOpener) != (Right.Type == TT_TemplateCloser)))
1524     return true;
1525   if (Right.isOneOf(tok::semi, tok::comma))
1526     return false;
1527   if (Right.is(tok::less) &&
1528       (Left.isOneOf(tok::kw_template, tok::r_paren) ||
1529        (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1530     return true;
1531   if (Left.is(tok::arrow) || Right.is(tok::arrow))
1532     return false;
1533   if (Left.isOneOf(tok::exclaim, tok::tilde))
1534     return false;
1535   if (Left.is(tok::at) &&
1536       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1537                     tok::numeric_constant, tok::l_paren, tok::l_brace,
1538                     tok::kw_true, tok::kw_false))
1539     return false;
1540   if (Left.is(tok::coloncolon))
1541     return false;
1542   if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
1543     return (Left.is(tok::less) && Style.Standard == FormatStyle::LS_Cpp03) ||
1544            !Left.isOneOf(tok::identifier, tok::greater, tok::l_paren,
1545                          tok::r_paren, tok::less);
1546   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1547     return false;
1548   if (Right.is(tok::ellipsis))
1549     return Left.Tok.isLiteral();
1550   if (Left.is(tok::l_square) && Right.is(tok::amp))
1551     return false;
1552   if (Right.Type == TT_PointerOrReference)
1553     return Left.Tok.isLiteral() ||
1554            ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
1555             Style.PointerAlignment != FormatStyle::PAS_Left);
1556   if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
1557       (Left.Type != TT_PointerOrReference ||
1558        Style.PointerAlignment != FormatStyle::PAS_Right))
1559     return true;
1560   if (Left.Type == TT_PointerOrReference)
1561     return Right.Tok.isLiteral() || Right.Type == TT_BlockComment ||
1562            ((Right.Type != TT_PointerOrReference) &&
1563             Right.isNot(tok::l_paren) &&
1564             Style.PointerAlignment != FormatStyle::PAS_Right && Left.Previous &&
1565             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1566   if (Right.is(tok::star) && Left.is(tok::l_paren))
1567     return false;
1568   if (Left.is(tok::l_square))
1569     return (Left.Type == TT_ArrayInitializerLSquare &&
1570             Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1571            (Left.Type == TT_ArraySubscriptLSquare &&
1572             Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
1573   if (Right.is(tok::r_square))
1574     return Right.MatchingParen &&
1575            ((Style.SpacesInContainerLiterals &&
1576              Right.MatchingParen->Type == TT_ArrayInitializerLSquare) ||
1577             (Style.SpacesInSquareBrackets &&
1578              Right.MatchingParen->Type == TT_ArraySubscriptLSquare));
1579   if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr &&
1580       Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant) &&
1581       Left.Type != TT_DictLiteral)
1582     return false;
1583   if (Left.is(tok::colon))
1584     return Left.Type != TT_ObjCMethodExpr;
1585   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1586     return !Left.Children.empty(); // No spaces in "{}".
1587   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1588       (Right.is(tok::r_brace) && Right.MatchingParen &&
1589        Right.MatchingParen->BlockKind != BK_Block))
1590     return !Style.Cpp11BracedListStyle;
1591   if (Left.Type == TT_BlockComment)
1592     return !Left.TokenText.endswith("=*/");
1593   if (Right.is(tok::l_paren)) {
1594     if (Left.is(tok::r_paren) && Left.Type == TT_AttributeParen)
1595       return true;
1596     return Line.Type == LT_ObjCDecl ||
1597            Left.isOneOf(tok::kw_new, tok::kw_delete, tok::semi) ||
1598            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1599             (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
1600                           tok::kw_switch, tok::kw_case) ||
1601              (Left.is(tok::kw_catch) &&
1602               (!Left.Previous || Left.Previous->isNot(tok::period))) ||
1603              Left.IsForEachMacro)) ||
1604            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1605             (Left.is(tok::identifier) || Left.isFunctionLikeKeyword()) &&
1606             Line.Type != LT_PreprocessorDirective);
1607   }
1608   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1609     return false;
1610   if (Right.Type == TT_UnaryOperator)
1611     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1612            (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
1613   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1614                     tok::r_paren) ||
1615        Left.isSimpleTypeSpecifier()) &&
1616       Right.is(tok::l_brace) && Right.getNextNonComment() &&
1617       Right.BlockKind != BK_Block)
1618     return false;
1619   if (Left.is(tok::period) || Right.is(tok::period))
1620     return false;
1621   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1622     return false;
1623   return true;
1624 }
1625 
1626 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1627                                          const FormatToken &Tok) {
1628   if (Tok.Tok.getIdentifierInfo() && Tok.Previous->Tok.getIdentifierInfo())
1629     return true; // Never ever merge two identifiers.
1630   if (Tok.Previous->Type == TT_ImplicitStringLiteral)
1631     return Tok.WhitespaceRange.getBegin() != Tok.WhitespaceRange.getEnd();
1632   if (Line.Type == LT_ObjCMethodDecl) {
1633     if (Tok.Previous->Type == TT_ObjCMethodSpecifier)
1634       return true;
1635     if (Tok.Previous->is(tok::r_paren) && Tok.is(tok::identifier))
1636       // Don't space between ')' and <id>
1637       return false;
1638   }
1639   if (Line.Type == LT_ObjCProperty &&
1640       (Tok.is(tok::equal) || Tok.Previous->is(tok::equal)))
1641     return false;
1642 
1643   if (Tok.Type == TT_TrailingReturnArrow ||
1644       Tok.Previous->Type == TT_TrailingReturnArrow)
1645     return true;
1646   if (Tok.Previous->is(tok::comma))
1647     return true;
1648   if (Tok.is(tok::comma))
1649     return false;
1650   if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
1651     return true;
1652   if (Tok.Previous->Tok.is(tok::kw_operator))
1653     return Tok.is(tok::coloncolon);
1654   if (Tok.Type == TT_OverloadedOperatorLParen)
1655     return false;
1656   if (Tok.is(tok::colon))
1657     return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
1658            Tok.getNextNonComment() && Tok.Type != TT_ObjCMethodExpr &&
1659            !Tok.Previous->is(tok::question) &&
1660            !(Tok.Type == TT_InlineASMColon &&
1661              Tok.Previous->is(tok::coloncolon)) &&
1662            (Tok.Type != TT_DictLiteral || Style.SpacesInContainerLiterals);
1663   if (Tok.Previous->Type == TT_UnaryOperator)
1664     return Tok.Type == TT_BinaryOperator;
1665   if (Tok.Previous->Type == TT_CastRParen)
1666     return Style.SpaceAfterCStyleCast || Tok.Type == TT_BinaryOperator;
1667   if (Tok.Previous->is(tok::greater) && Tok.is(tok::greater)) {
1668     return Tok.Type == TT_TemplateCloser &&
1669            Tok.Previous->Type == TT_TemplateCloser &&
1670            (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
1671   }
1672   if (Tok.isOneOf(tok::arrowstar, tok::periodstar) ||
1673       Tok.Previous->isOneOf(tok::arrowstar, tok::periodstar))
1674     return false;
1675   if (!Style.SpaceBeforeAssignmentOperators &&
1676       Tok.getPrecedence() == prec::Assignment)
1677     return false;
1678   if ((Tok.Type == TT_BinaryOperator && !Tok.Previous->is(tok::l_paren)) ||
1679       Tok.Previous->Type == TT_BinaryOperator ||
1680       Tok.Previous->Type == TT_ConditionalExpr)
1681     return true;
1682   if (Tok.Previous->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
1683     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
1684   if (Tok.is(tok::less) && Tok.Previous->isNot(tok::l_paren) &&
1685       Line.First->is(tok::hash))
1686     return true;
1687   if (Tok.Type == TT_TrailingUnaryOperator)
1688     return false;
1689   if (Tok.Previous->Type == TT_RegexLiteral)
1690     return false;
1691   return spaceRequiredBetween(Line, *Tok.Previous, Tok);
1692 }
1693 
1694 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
1695 static bool isAllmanBrace(const FormatToken &Tok) {
1696   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
1697          Tok.Type != TT_ObjCBlockLBrace && Tok.Type != TT_DictLiteral;
1698 }
1699 
1700 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
1701                                      const FormatToken &Right) {
1702   const FormatToken &Left = *Right.Previous;
1703   if (Right.NewlinesBefore > 1)
1704     return true;
1705   if (Right.is(tok::comment)) {
1706     return Right.Previous->BlockKind != BK_BracedInit &&
1707            Right.Previous->Type != TT_CtorInitializerColon &&
1708            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
1709   } else if (Right.Previous->isTrailingComment() ||
1710              (Right.isStringLiteral() && Right.Previous->isStringLiteral())) {
1711     return true;
1712   } else if (Right.Previous->IsUnterminatedLiteral) {
1713     return true;
1714   } else if (Right.is(tok::lessless) && Right.Next &&
1715              Right.Previous->is(tok::string_literal) &&
1716              Right.Next->is(tok::string_literal)) {
1717     return true;
1718   } else if (Right.Previous->ClosesTemplateDeclaration &&
1719              Right.Previous->MatchingParen &&
1720              Right.Previous->MatchingParen->NestingLevel == 0 &&
1721              Style.AlwaysBreakTemplateDeclarations) {
1722     return true;
1723   } else if ((Right.Type == TT_CtorInitializerComma ||
1724               Right.Type == TT_CtorInitializerColon) &&
1725              Style.BreakConstructorInitializersBeforeComma &&
1726              !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
1727     return true;
1728   } else if (Right.is(tok::string_literal) &&
1729              Right.TokenText.startswith("R\"")) {
1730     // Raw string literals are special wrt. line breaks. The author has made a
1731     // deliberate choice and might have aligned the contents of the string
1732     // literal accordingly. Thus, we try keep existing line breaks.
1733     return Right.NewlinesBefore > 0;
1734   } else if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
1735              Style.Language == FormatStyle::LK_Proto) {
1736     // Don't enums onto single lines in protocol buffers.
1737     return true;
1738   } else if (Style.Language == FormatStyle::LK_JavaScript &&
1739              Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
1740              !Left.Children.empty()) {
1741     // Support AllowShortFunctionsOnASingleLine for JavaScript.
1742     return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
1743            (Left.NestingLevel == 0 && Line.Level == 0 &&
1744             Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline);
1745   } else if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
1746     return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1747            Style.BreakBeforeBraces == FormatStyle::BS_GNU;
1748   } else if (Style.Language == FormatStyle::LK_Proto &&
1749              Left.isNot(tok::l_brace) && Right.Type == TT_SelectorName) {
1750     return true;
1751   }
1752 
1753   // If the last token before a '}' is a comma or a trailing comment, the
1754   // intention is to insert a line break after it in order to make shuffling
1755   // around entries easier.
1756   const FormatToken *BeforeClosingBrace = nullptr;
1757   if (Left.is(tok::l_brace) && Left.MatchingParen)
1758     BeforeClosingBrace = Left.MatchingParen->Previous;
1759   else if (Right.is(tok::r_brace))
1760     BeforeClosingBrace = Right.Previous;
1761   if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
1762                              BeforeClosingBrace->isTrailingComment()))
1763     return true;
1764 
1765   if (Style.Language == FormatStyle::LK_JavaScript) {
1766     // FIXME: This might apply to other languages and token kinds.
1767     if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
1768         Left.Previous->is(tok::char_constant))
1769       return true;
1770   }
1771 
1772   return false;
1773 }
1774 
1775 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
1776                                     const FormatToken &Right) {
1777   const FormatToken &Left = *Right.Previous;
1778   if (Left.is(tok::at))
1779     return false;
1780   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
1781     return false;
1782   if (Right.Type == TT_StartOfName ||
1783       Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator))
1784     return true;
1785   if (Right.isTrailingComment())
1786     // We rely on MustBreakBefore being set correctly here as we should not
1787     // change the "binding" behavior of a comment.
1788     // The first comment in a braced lists is always interpreted as belonging to
1789     // the first list element. Otherwise, it should be placed outside of the
1790     // list.
1791     return Left.BlockKind == BK_BracedInit;
1792   if (Left.is(tok::question) && Right.is(tok::colon))
1793     return false;
1794   if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1795     return Style.BreakBeforeTernaryOperators;
1796   if (Left.Type == TT_ConditionalExpr || Left.is(tok::question))
1797     return !Style.BreakBeforeTernaryOperators;
1798   if (Right.Type == TT_InheritanceColon)
1799     return true;
1800   if (Right.is(tok::colon) && (Right.Type != TT_CtorInitializerColon &&
1801                                Right.Type != TT_InlineASMColon))
1802     return false;
1803   if (Left.is(tok::colon) &&
1804       (Left.Type == TT_DictLiteral || Left.Type == TT_ObjCMethodExpr))
1805     return true;
1806   if (Right.Type == TT_SelectorName)
1807     return true;
1808   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
1809     return true;
1810   if (Left.ClosesTemplateDeclaration)
1811     return true;
1812   if (Right.Type == TT_RangeBasedForLoopColon ||
1813       Right.Type == TT_OverloadedOperatorLParen ||
1814       Right.Type == TT_OverloadedOperator)
1815     return false;
1816   if (Left.Type == TT_RangeBasedForLoopColon)
1817     return true;
1818   if (Right.Type == TT_RangeBasedForLoopColon)
1819     return false;
1820   if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
1821       Left.Type == TT_UnaryOperator || Left.is(tok::kw_operator))
1822     return false;
1823   if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
1824     return false;
1825   if (Left.is(tok::l_paren) && Left.Type == TT_AttributeParen)
1826     return false;
1827   if (Left.is(tok::l_paren) && Left.Previous &&
1828       (Left.Previous->Type == TT_BinaryOperator ||
1829        Left.Previous->Type == TT_CastRParen || Left.Previous->is(tok::kw_if)))
1830     return false;
1831   if (Right.Type == TT_ImplicitStringLiteral)
1832     return false;
1833 
1834   if (Right.is(tok::r_paren) || Right.Type == TT_TemplateCloser)
1835     return false;
1836 
1837   // We only break before r_brace if there was a corresponding break before
1838   // the l_brace, which is tracked by BreakBeforeClosingBrace.
1839   if (Right.is(tok::r_brace))
1840     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
1841 
1842   // Allow breaking after a trailing annotation, e.g. after a method
1843   // declaration.
1844   if (Left.Type == TT_TrailingAnnotation)
1845     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
1846                           tok::less, tok::coloncolon);
1847 
1848   if (Right.is(tok::kw___attribute))
1849     return true;
1850 
1851   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
1852     return true;
1853 
1854   if (Right.is(tok::identifier) && Right.Next &&
1855       Right.Next->Type == TT_DictLiteral)
1856     return true;
1857 
1858   if (Left.Type == TT_CtorInitializerComma &&
1859       Style.BreakConstructorInitializersBeforeComma)
1860     return false;
1861   if (Right.Type == TT_CtorInitializerComma &&
1862       Style.BreakConstructorInitializersBeforeComma)
1863     return true;
1864   if (Left.is(tok::greater) && Right.is(tok::greater) &&
1865       Left.Type != TT_TemplateCloser)
1866     return false;
1867   if (Right.Type == TT_BinaryOperator &&
1868       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
1869       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
1870        Right.getPrecedence() != prec::Assignment))
1871     return true;
1872   if (Left.Type == TT_ArrayInitializerLSquare)
1873     return true;
1874   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
1875     return true;
1876   if (Left.isBinaryOperator() && !Left.isOneOf(tok::arrowstar, tok::lessless) &&
1877       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
1878       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
1879        Left.getPrecedence() == prec::Assignment))
1880     return true;
1881   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
1882                       tok::kw_class, tok::kw_struct) ||
1883          Right.isMemberAccess() ||
1884          Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at) ||
1885          (Left.is(tok::r_paren) &&
1886           Right.isOneOf(tok::identifier, tok::kw_const)) ||
1887          (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
1888 }
1889 
1890 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
1891   llvm::errs() << "AnnotatedTokens:\n";
1892   const FormatToken *Tok = Line.First;
1893   while (Tok) {
1894     llvm::errs() << " M=" << Tok->MustBreakBefore
1895                  << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
1896                  << " S=" << Tok->SpacesRequiredBefore
1897                  << " B=" << Tok->BlockParameterCount
1898                  << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
1899                  << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
1900                  << " FakeLParens=";
1901     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
1902       llvm::errs() << Tok->FakeLParens[i] << "/";
1903     llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
1904     if (!Tok->Next)
1905       assert(Tok == Line.Last);
1906     Tok = Tok->Next;
1907   }
1908   llvm::errs() << "----\n";
1909 }
1910 
1911 } // namespace format
1912 } // namespace clang
1913