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