1 //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements a token annotator, i.e. creates
11 /// \c AnnotatedTokens out of \c FormatTokens with required extra information.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "TokenAnnotator.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "llvm/ADT/SmallPtrSet.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 /// Returns \c true if the token can be used as an identifier in
28 /// an Objective-C \c @selector, \c false otherwise.
29 ///
30 /// Because getFormattingLangOpts() always lexes source code as
31 /// Objective-C++, C++ keywords like \c new and \c delete are
32 /// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
33 ///
34 /// For Objective-C and Objective-C++, both identifiers and keywords
35 /// are valid inside @selector(...) (or a macro which
36 /// invokes @selector(...)). So, we allow treat any identifier or
37 /// keyword as a potential Objective-C selector component.
38 static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
39   return Tok.Tok.getIdentifierInfo() != nullptr;
40 }
41 
42 /// A parser that gathers additional information about tokens.
43 ///
44 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
45 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
46 /// into template parameter lists.
47 class AnnotatingParser {
48 public:
49   AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
50                    const AdditionalKeywords &Keywords)
51       : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
52         Keywords(Keywords) {
53     Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
54     resetTokenMetadata(CurrentToken);
55   }
56 
57 private:
58   bool parseAngle() {
59     if (!CurrentToken || !CurrentToken->Previous)
60       return false;
61     if (NonTemplateLess.count(CurrentToken->Previous))
62       return false;
63 
64     const FormatToken &Previous = *CurrentToken->Previous;  // The '<'.
65     if (Previous.Previous) {
66       if (Previous.Previous->Tok.isLiteral())
67         return false;
68       if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
69           (!Previous.Previous->MatchingParen ||
70            !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
71         return false;
72     }
73 
74     FormatToken *Left = CurrentToken->Previous;
75     Left->ParentBracket = Contexts.back().ContextKind;
76     ScopedContextCreator ContextCreator(*this, tok::less, 12);
77 
78     // If this angle is in the context of an expression, we need to be more
79     // hesitant to detect it as opening template parameters.
80     bool InExprContext = Contexts.back().IsExpression;
81 
82     Contexts.back().IsExpression = false;
83     // If there's a template keyword before the opening angle bracket, this is a
84     // template parameter, not an argument.
85     Contexts.back().InTemplateArgument =
86         Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
87 
88     if (Style.Language == FormatStyle::LK_Java &&
89         CurrentToken->is(tok::question))
90       next();
91 
92     while (CurrentToken) {
93       if (CurrentToken->is(tok::greater)) {
94         Left->MatchingParen = CurrentToken;
95         CurrentToken->MatchingParen = Left;
96         // In TT_Proto, we must distignuish between:
97         //   map<key, value>
98         //   msg < item: data >
99         //   msg: < item: data >
100         // In TT_TextProto, map<key, value> does not occur.
101         if (Style.Language == FormatStyle::LK_TextProto ||
102             (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
103              Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
104           CurrentToken->Type = TT_DictLiteral;
105         else
106           CurrentToken->Type = TT_TemplateCloser;
107         next();
108         return true;
109       }
110       if (CurrentToken->is(tok::question) &&
111           Style.Language == FormatStyle::LK_Java) {
112         next();
113         continue;
114       }
115       if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
116           (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
117            Style.Language != FormatStyle::LK_Proto &&
118            Style.Language != FormatStyle::LK_TextProto))
119         return false;
120       // If a && or || is found and interpreted as a binary operator, this set
121       // of angles is likely part of something like "a < b && c > d". If the
122       // angles are inside an expression, the ||/&& might also be a binary
123       // operator that was misinterpreted because we are parsing template
124       // parameters.
125       // FIXME: This is getting out of hand, write a decent parser.
126       if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
127           CurrentToken->Previous->is(TT_BinaryOperator) &&
128           Contexts[Contexts.size() - 2].IsExpression &&
129           !Line.startsWith(tok::kw_template))
130         return false;
131       updateParameterCount(Left, CurrentToken);
132       if (Style.Language == FormatStyle::LK_Proto) {
133         if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
134           if (CurrentToken->is(tok::colon) ||
135               (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
136                Previous->isNot(tok::colon)))
137             Previous->Type = TT_SelectorName;
138         }
139       }
140       if (!consumeToken())
141         return false;
142     }
143     return false;
144   }
145 
146   bool parseParens(bool LookForDecls = false) {
147     if (!CurrentToken)
148       return false;
149     FormatToken *Left = CurrentToken->Previous;
150     Left->ParentBracket = Contexts.back().ContextKind;
151     ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
152 
153     // FIXME: This is a bit of a hack. Do better.
154     Contexts.back().ColonIsForRangeExpr =
155         Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
156 
157     bool StartsObjCMethodExpr = false;
158     if (FormatToken *MaybeSel = Left->Previous) {
159       // @selector( starts a selector.
160       if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
161           MaybeSel->Previous->is(tok::at)) {
162         StartsObjCMethodExpr = true;
163       }
164     }
165 
166     if (Left->is(TT_OverloadedOperatorLParen)) {
167       Contexts.back().IsExpression = false;
168     } else if (Style.Language == FormatStyle::LK_JavaScript &&
169                (Line.startsWith(Keywords.kw_type, tok::identifier) ||
170                 Line.startsWith(tok::kw_export, Keywords.kw_type,
171                                 tok::identifier))) {
172       // type X = (...);
173       // export type X = (...);
174       Contexts.back().IsExpression = false;
175     } else if (Left->Previous &&
176                (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
177                                         tok::kw_if, tok::kw_while, tok::l_paren,
178                                         tok::comma) ||
179                 Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
180                 Left->Previous->is(TT_BinaryOperator))) {
181       // static_assert, if and while usually contain expressions.
182       Contexts.back().IsExpression = true;
183     } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
184                (Left->Previous->is(Keywords.kw_function) ||
185                 (Left->Previous->endsSequence(tok::identifier,
186                                               Keywords.kw_function)))) {
187       // function(...) or function f(...)
188       Contexts.back().IsExpression = false;
189     } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
190                Left->Previous->is(TT_JsTypeColon)) {
191       // let x: (SomeType);
192       Contexts.back().IsExpression = false;
193     } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
194                Left->Previous->MatchingParen &&
195                Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
196       // This is a parameter list of a lambda expression.
197       Contexts.back().IsExpression = false;
198     } else if (Line.InPPDirective &&
199                (!Left->Previous || !Left->Previous->is(tok::identifier))) {
200       Contexts.back().IsExpression = true;
201     } else if (Contexts[Contexts.size() - 2].CaretFound) {
202       // This is the parameter list of an ObjC block.
203       Contexts.back().IsExpression = false;
204     } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
205       Left->Type = TT_AttributeParen;
206     } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
207       // The first argument to a foreach macro is a declaration.
208       Contexts.back().IsForEachMacro = true;
209       Contexts.back().IsExpression = false;
210     } else if (Left->Previous && Left->Previous->MatchingParen &&
211                Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
212       Contexts.back().IsExpression = false;
213     } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
214       bool IsForOrCatch =
215           Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
216       Contexts.back().IsExpression = !IsForOrCatch;
217     }
218 
219     if (StartsObjCMethodExpr) {
220       Contexts.back().ColonIsObjCMethodExpr = true;
221       Left->Type = TT_ObjCMethodExpr;
222     }
223 
224     // MightBeFunctionType and ProbablyFunctionType are used for
225     // function pointer and reference types as well as Objective-C
226     // block types:
227     //
228     // void (*FunctionPointer)(void);
229     // void (&FunctionReference)(void);
230     // void (^ObjCBlock)(void);
231     bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
232     bool ProbablyFunctionType =
233         CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
234     bool HasMultipleLines = false;
235     bool HasMultipleParametersOnALine = false;
236     bool MightBeObjCForRangeLoop =
237         Left->Previous && Left->Previous->is(tok::kw_for);
238     FormatToken *PossibleObjCForInToken = nullptr;
239     while (CurrentToken) {
240       // LookForDecls is set when "if (" has been seen. Check for
241       // 'identifier' '*' 'identifier' followed by not '=' -- this
242       // '*' has to be a binary operator but determineStarAmpUsage() will
243       // categorize it as an unary operator, so set the right type here.
244       if (LookForDecls && CurrentToken->Next) {
245         FormatToken *Prev = CurrentToken->getPreviousNonComment();
246         if (Prev) {
247           FormatToken *PrevPrev = Prev->getPreviousNonComment();
248           FormatToken *Next = CurrentToken->Next;
249           if (PrevPrev && PrevPrev->is(tok::identifier) &&
250               Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
251               CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
252             Prev->Type = TT_BinaryOperator;
253             LookForDecls = false;
254           }
255         }
256       }
257 
258       if (CurrentToken->Previous->is(TT_PointerOrReference) &&
259           CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
260                                                     tok::coloncolon))
261         ProbablyFunctionType = true;
262       if (CurrentToken->is(tok::comma))
263         MightBeFunctionType = false;
264       if (CurrentToken->Previous->is(TT_BinaryOperator))
265         Contexts.back().IsExpression = true;
266       if (CurrentToken->is(tok::r_paren)) {
267         if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
268             (CurrentToken->Next->is(tok::l_paren) ||
269              (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
270           Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
271                                                   : TT_FunctionTypeLParen;
272         Left->MatchingParen = CurrentToken;
273         CurrentToken->MatchingParen = Left;
274 
275         if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
276             Left->Previous && Left->Previous->is(tok::l_paren)) {
277           // Detect the case where macros are used to generate lambdas or
278           // function bodies, e.g.:
279           //   auto my_lambda = MARCO((Type *type, int i) { .. body .. });
280           for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
281             if (Tok->is(TT_BinaryOperator) &&
282                 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
283               Tok->Type = TT_PointerOrReference;
284           }
285         }
286 
287         if (StartsObjCMethodExpr) {
288           CurrentToken->Type = TT_ObjCMethodExpr;
289           if (Contexts.back().FirstObjCSelectorName) {
290             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
291                 Contexts.back().LongestObjCSelectorName;
292           }
293         }
294 
295         if (Left->is(TT_AttributeParen))
296           CurrentToken->Type = TT_AttributeParen;
297         if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
298           CurrentToken->Type = TT_JavaAnnotation;
299         if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
300           CurrentToken->Type = TT_LeadingJavaAnnotation;
301 
302         if (!HasMultipleLines)
303           Left->PackingKind = PPK_Inconclusive;
304         else if (HasMultipleParametersOnALine)
305           Left->PackingKind = PPK_BinPacked;
306         else
307           Left->PackingKind = PPK_OnePerLine;
308 
309         next();
310         return true;
311       }
312       if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
313         return false;
314 
315       if (CurrentToken->is(tok::l_brace))
316         Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
317       if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
318           !CurrentToken->Next->HasUnescapedNewline &&
319           !CurrentToken->Next->isTrailingComment())
320         HasMultipleParametersOnALine = true;
321       if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
322            CurrentToken->Previous->isSimpleTypeSpecifier()) &&
323           !CurrentToken->is(tok::l_brace))
324         Contexts.back().IsExpression = false;
325       if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
326         MightBeObjCForRangeLoop = false;
327         if (PossibleObjCForInToken) {
328           PossibleObjCForInToken->Type = TT_Unknown;
329           PossibleObjCForInToken = nullptr;
330         }
331       }
332       if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
333         PossibleObjCForInToken = CurrentToken;
334         PossibleObjCForInToken->Type = TT_ObjCForIn;
335       }
336       // When we discover a 'new', we set CanBeExpression to 'false' in order to
337       // parse the type correctly. Reset that after a comma.
338       if (CurrentToken->is(tok::comma))
339         Contexts.back().CanBeExpression = true;
340 
341       FormatToken *Tok = CurrentToken;
342       if (!consumeToken())
343         return false;
344       updateParameterCount(Left, Tok);
345       if (CurrentToken && CurrentToken->HasUnescapedNewline)
346         HasMultipleLines = true;
347     }
348     return false;
349   }
350 
351   bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
352     if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
353       return false;
354     const FormatToken *AttrTok = Tok.Next->Next;
355     if (!AttrTok)
356       return false;
357     // C++17 '[[using ns: foo, bar(baz, blech)]]'
358     // We assume nobody will name an ObjC variable 'using'.
359     if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
360       return true;
361     if (AttrTok->isNot(tok::identifier))
362       return false;
363     while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
364       // ObjC message send. We assume nobody will use : in a C++11 attribute
365       // specifier parameter, although this is technically valid:
366       // [[foo(:)]]
367       if (AttrTok->is(tok::colon) ||
368           AttrTok->startsSequence(tok::identifier, tok::identifier) ||
369           AttrTok->startsSequence(tok::r_paren, tok::identifier))
370         return false;
371       if (AttrTok->is(tok::ellipsis))
372         return true;
373       AttrTok = AttrTok->Next;
374     }
375     return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
376   }
377 
378   bool parseSquare() {
379     if (!CurrentToken)
380       return false;
381 
382     // A '[' could be an index subscript (after an identifier or after
383     // ')' or ']'), it could be the start of an Objective-C method
384     // expression, it could the start of an Objective-C array literal,
385     // or it could be a C++ attribute specifier [[foo::bar]].
386     FormatToken *Left = CurrentToken->Previous;
387     Left->ParentBracket = Contexts.back().ContextKind;
388     FormatToken *Parent = Left->getPreviousNonComment();
389 
390     // Cases where '>' is followed by '['.
391     // In C++, this can happen either in array of templates (foo<int>[10])
392     // or when array is a nested template type (unique_ptr<type1<type2>[]>).
393     bool CppArrayTemplates =
394         Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
395         (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
396          Contexts.back().InTemplateArgument);
397 
398     bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
399                                      Contexts.back().InCpp11AttributeSpecifier;
400 
401     bool InsideInlineASM = Line.startsWith(tok::kw_asm);
402     bool StartsObjCMethodExpr =
403         !InsideInlineASM && !CppArrayTemplates && Style.isCpp() &&
404         !IsCpp11AttributeSpecifier && Contexts.back().CanBeExpression &&
405         Left->isNot(TT_LambdaLSquare) &&
406         !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
407         (!Parent ||
408          Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
409                          tok::kw_return, tok::kw_throw) ||
410          Parent->isUnaryOperator() ||
411          // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
412          Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
413          getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
414     bool ColonFound = false;
415 
416     unsigned BindingIncrease = 1;
417     if (Left->isCppStructuredBinding(Style)) {
418       Left->Type = TT_StructuredBindingLSquare;
419     } else if (Left->is(TT_Unknown)) {
420       if (StartsObjCMethodExpr) {
421         Left->Type = TT_ObjCMethodExpr;
422       } else if (IsCpp11AttributeSpecifier) {
423         Left->Type = TT_AttributeSquare;
424       } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
425                  Contexts.back().ContextKind == tok::l_brace &&
426                  Parent->isOneOf(tok::l_brace, tok::comma)) {
427         Left->Type = TT_JsComputedPropertyName;
428       } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
429                  Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
430         Left->Type = TT_DesignatedInitializerLSquare;
431       } else if (CurrentToken->is(tok::r_square) && Parent &&
432                  Parent->is(TT_TemplateCloser)) {
433         Left->Type = TT_ArraySubscriptLSquare;
434       } else if (Style.Language == FormatStyle::LK_Proto ||
435                  Style.Language == FormatStyle::LK_TextProto) {
436         // Square braces in LK_Proto can either be message field attributes:
437         //
438         // optional Aaa aaa = 1 [
439         //   (aaa) = aaa
440         // ];
441         //
442         // extensions 123 [
443         //   (aaa) = aaa
444         // ];
445         //
446         // or text proto extensions (in options):
447         //
448         // option (Aaa.options) = {
449         //   [type.type/type] {
450         //     key: value
451         //   }
452         // }
453         //
454         // or repeated fields (in options):
455         //
456         // option (Aaa.options) = {
457         //   keys: [ 1, 2, 3 ]
458         // }
459         //
460         // In the first and the third case we want to spread the contents inside
461         // the square braces; in the second we want to keep them inline.
462         Left->Type = TT_ArrayInitializerLSquare;
463         if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
464                                 tok::equal) &&
465             !Left->endsSequence(tok::l_square, tok::numeric_constant,
466                                 tok::identifier) &&
467             !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
468           Left->Type = TT_ProtoExtensionLSquare;
469           BindingIncrease = 10;
470         }
471       } else if (!CppArrayTemplates && Parent &&
472                  Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
473                                  tok::comma, tok::l_paren, tok::l_square,
474                                  tok::question, tok::colon, tok::kw_return,
475                                  // Should only be relevant to JavaScript:
476                                  tok::kw_default)) {
477         Left->Type = TT_ArrayInitializerLSquare;
478       } else {
479         BindingIncrease = 10;
480         Left->Type = TT_ArraySubscriptLSquare;
481       }
482     }
483 
484     ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
485     Contexts.back().IsExpression = true;
486     if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
487         Parent->is(TT_JsTypeColon))
488       Contexts.back().IsExpression = false;
489 
490     Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
491     Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
492 
493     while (CurrentToken) {
494       if (CurrentToken->is(tok::r_square)) {
495         if (IsCpp11AttributeSpecifier)
496           CurrentToken->Type = TT_AttributeSquare;
497         else if (((CurrentToken->Next &&
498                    CurrentToken->Next->is(tok::l_paren)) ||
499                   (CurrentToken->Previous &&
500                    CurrentToken->Previous->Previous == Left)) &&
501                  Left->is(TT_ObjCMethodExpr)) {
502           // An ObjC method call is rarely followed by an open parenthesis. It
503           // also can't be composed of just one token, unless it's a macro that
504           // will be expanded to more tokens.
505           // FIXME: Do we incorrectly label ":" with this?
506           StartsObjCMethodExpr = false;
507           Left->Type = TT_Unknown;
508         }
509         if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
510           CurrentToken->Type = TT_ObjCMethodExpr;
511           // If we haven't seen a colon yet, make sure the last identifier
512           // before the r_square is tagged as a selector name component.
513           if (!ColonFound && CurrentToken->Previous &&
514               CurrentToken->Previous->is(TT_Unknown) &&
515               canBeObjCSelectorComponent(*CurrentToken->Previous))
516             CurrentToken->Previous->Type = TT_SelectorName;
517           // determineStarAmpUsage() thinks that '*' '[' is allocating an
518           // array of pointers, but if '[' starts a selector then '*' is a
519           // binary operator.
520           if (Parent && Parent->is(TT_PointerOrReference))
521             Parent->Type = TT_BinaryOperator;
522         }
523         // An arrow after an ObjC method expression is not a lambda arrow.
524         if (CurrentToken->Type == TT_ObjCMethodExpr && CurrentToken->Next &&
525             CurrentToken->Next->is(TT_LambdaArrow))
526           CurrentToken->Next->Type = TT_Unknown;
527         Left->MatchingParen = CurrentToken;
528         CurrentToken->MatchingParen = Left;
529         // FirstObjCSelectorName is set when a colon is found. This does
530         // not work, however, when the method has no parameters.
531         // Here, we set FirstObjCSelectorName when the end of the method call is
532         // reached, in case it was not set already.
533         if (!Contexts.back().FirstObjCSelectorName) {
534             FormatToken* Previous = CurrentToken->getPreviousNonComment();
535             if (Previous && Previous->is(TT_SelectorName)) {
536               Previous->ObjCSelectorNameParts = 1;
537               Contexts.back().FirstObjCSelectorName = Previous;
538             }
539         } else {
540           Left->ParameterCount =
541               Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
542         }
543         if (Contexts.back().FirstObjCSelectorName) {
544           Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
545               Contexts.back().LongestObjCSelectorName;
546           if (Left->BlockParameterCount > 1)
547             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
548         }
549         next();
550         return true;
551       }
552       if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
553         return false;
554       if (CurrentToken->is(tok::colon)) {
555         if (IsCpp11AttributeSpecifier &&
556             CurrentToken->endsSequence(tok::colon, tok::identifier,
557                                        tok::kw_using)) {
558           // Remember that this is a [[using ns: foo]] C++ attribute, so we
559           // don't add a space before the colon (unlike other colons).
560           CurrentToken->Type = TT_AttributeColon;
561         } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
562                                  TT_DesignatedInitializerLSquare)) {
563           Left->Type = TT_ObjCMethodExpr;
564           StartsObjCMethodExpr = true;
565           Contexts.back().ColonIsObjCMethodExpr = true;
566           if (Parent && Parent->is(tok::r_paren))
567             // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
568             Parent->Type = TT_CastRParen;
569         }
570         ColonFound = true;
571       }
572       if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
573           !ColonFound)
574         Left->Type = TT_ArrayInitializerLSquare;
575       FormatToken *Tok = CurrentToken;
576       if (!consumeToken())
577         return false;
578       updateParameterCount(Left, Tok);
579     }
580     return false;
581   }
582 
583   bool parseBrace() {
584     if (CurrentToken) {
585       FormatToken *Left = CurrentToken->Previous;
586       Left->ParentBracket = Contexts.back().ContextKind;
587 
588       if (Contexts.back().CaretFound)
589         Left->Type = TT_ObjCBlockLBrace;
590       Contexts.back().CaretFound = false;
591 
592       ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
593       Contexts.back().ColonIsDictLiteral = true;
594       if (Left->BlockKind == BK_BracedInit)
595         Contexts.back().IsExpression = true;
596       if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
597           Left->Previous->is(TT_JsTypeColon))
598         Contexts.back().IsExpression = false;
599 
600       while (CurrentToken) {
601         if (CurrentToken->is(tok::r_brace)) {
602           Left->MatchingParen = CurrentToken;
603           CurrentToken->MatchingParen = Left;
604           next();
605           return true;
606         }
607         if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
608           return false;
609         updateParameterCount(Left, CurrentToken);
610         if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
611           FormatToken *Previous = CurrentToken->getPreviousNonComment();
612           if (Previous->is(TT_JsTypeOptionalQuestion))
613             Previous = Previous->getPreviousNonComment();
614           if ((CurrentToken->is(tok::colon) &&
615                (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
616               Style.Language == FormatStyle::LK_Proto ||
617               Style.Language == FormatStyle::LK_TextProto) {
618             Left->Type = TT_DictLiteral;
619             if (Previous->Tok.getIdentifierInfo() ||
620                 Previous->is(tok::string_literal))
621               Previous->Type = TT_SelectorName;
622           }
623           if (CurrentToken->is(tok::colon) ||
624               Style.Language == FormatStyle::LK_JavaScript)
625             Left->Type = TT_DictLiteral;
626         }
627         if (CurrentToken->is(tok::comma) &&
628             Style.Language == FormatStyle::LK_JavaScript)
629           Left->Type = TT_DictLiteral;
630         if (!consumeToken())
631           return false;
632       }
633     }
634     return true;
635   }
636 
637   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
638     // For ObjC methods, the number of parameters is calculated differently as
639     // method declarations have a different structure (the parameters are not
640     // inside a bracket scope).
641     if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
642       ++Left->BlockParameterCount;
643     if (Current->is(tok::comma)) {
644       ++Left->ParameterCount;
645       if (!Left->Role)
646         Left->Role.reset(new CommaSeparatedList(Style));
647       Left->Role->CommaFound(Current);
648     } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
649       Left->ParameterCount = 1;
650     }
651   }
652 
653   bool parseConditional() {
654     while (CurrentToken) {
655       if (CurrentToken->is(tok::colon)) {
656         CurrentToken->Type = TT_ConditionalExpr;
657         next();
658         return true;
659       }
660       if (!consumeToken())
661         return false;
662     }
663     return false;
664   }
665 
666   bool parseTemplateDeclaration() {
667     if (CurrentToken && CurrentToken->is(tok::less)) {
668       CurrentToken->Type = TT_TemplateOpener;
669       next();
670       if (!parseAngle())
671         return false;
672       if (CurrentToken)
673         CurrentToken->Previous->ClosesTemplateDeclaration = true;
674       return true;
675     }
676     return false;
677   }
678 
679   bool consumeToken() {
680     FormatToken *Tok = CurrentToken;
681     next();
682     switch (Tok->Tok.getKind()) {
683     case tok::plus:
684     case tok::minus:
685       if (!Tok->Previous && Line.MustBeDeclaration)
686         Tok->Type = TT_ObjCMethodSpecifier;
687       break;
688     case tok::colon:
689       if (!Tok->Previous)
690         return false;
691       // Colons from ?: are handled in parseConditional().
692       if (Style.Language == FormatStyle::LK_JavaScript) {
693         if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
694             (Contexts.size() == 1 &&               // switch/case labels
695              !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
696             Contexts.back().ContextKind == tok::l_paren ||  // function params
697             Contexts.back().ContextKind == tok::l_square || // array type
698             (!Contexts.back().IsExpression &&
699              Contexts.back().ContextKind == tok::l_brace) || // object type
700             (Contexts.size() == 1 &&
701              Line.MustBeDeclaration)) { // method/property declaration
702           Contexts.back().IsExpression = false;
703           Tok->Type = TT_JsTypeColon;
704           break;
705         }
706       }
707       if (Contexts.back().ColonIsDictLiteral ||
708           Style.Language == FormatStyle::LK_Proto ||
709           Style.Language == FormatStyle::LK_TextProto) {
710         Tok->Type = TT_DictLiteral;
711         if (Style.Language == FormatStyle::LK_TextProto) {
712           if (FormatToken *Previous = Tok->getPreviousNonComment())
713             Previous->Type = TT_SelectorName;
714         }
715       } else if (Contexts.back().ColonIsObjCMethodExpr ||
716                  Line.startsWith(TT_ObjCMethodSpecifier)) {
717         Tok->Type = TT_ObjCMethodExpr;
718         const FormatToken *BeforePrevious = Tok->Previous->Previous;
719         // Ensure we tag all identifiers in method declarations as
720         // TT_SelectorName.
721         bool UnknownIdentifierInMethodDeclaration =
722             Line.startsWith(TT_ObjCMethodSpecifier) &&
723             Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
724         if (!BeforePrevious ||
725             // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
726             !(BeforePrevious->is(TT_CastRParen) ||
727               (BeforePrevious->is(TT_ObjCMethodExpr) &&
728                BeforePrevious->is(tok::colon))) ||
729             BeforePrevious->is(tok::r_square) ||
730             Contexts.back().LongestObjCSelectorName == 0 ||
731             UnknownIdentifierInMethodDeclaration) {
732           Tok->Previous->Type = TT_SelectorName;
733           if (!Contexts.back().FirstObjCSelectorName)
734             Contexts.back().FirstObjCSelectorName = Tok->Previous;
735           else if (Tok->Previous->ColumnWidth >
736                    Contexts.back().LongestObjCSelectorName)
737             Contexts.back().LongestObjCSelectorName =
738                 Tok->Previous->ColumnWidth;
739           Tok->Previous->ParameterIndex =
740               Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
741           ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
742         }
743       } else if (Contexts.back().ColonIsForRangeExpr) {
744         Tok->Type = TT_RangeBasedForLoopColon;
745       } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
746         Tok->Type = TT_BitFieldColon;
747       } else if (Contexts.size() == 1 &&
748                  !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
749         if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
750                                                   tok::kw_noexcept))
751           Tok->Type = TT_CtorInitializerColon;
752         else
753           Tok->Type = TT_InheritanceColon;
754       } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
755                  (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
756                   (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
757                    Tok->Next->Next->is(tok::colon)))) {
758         // This handles a special macro in ObjC code where selectors including
759         // the colon are passed as macro arguments.
760         Tok->Type = TT_ObjCMethodExpr;
761       } else if (Contexts.back().ContextKind == tok::l_paren) {
762         Tok->Type = TT_InlineASMColon;
763       }
764       break;
765     case tok::pipe:
766     case tok::amp:
767       // | and & in declarations/type expressions represent union and
768       // intersection types, respectively.
769       if (Style.Language == FormatStyle::LK_JavaScript &&
770           !Contexts.back().IsExpression)
771         Tok->Type = TT_JsTypeOperator;
772       break;
773     case tok::kw_if:
774     case tok::kw_while:
775       if (Tok->is(tok::kw_if) && CurrentToken &&
776           CurrentToken->is(tok::kw_constexpr))
777         next();
778       if (CurrentToken && CurrentToken->is(tok::l_paren)) {
779         next();
780         if (!parseParens(/*LookForDecls=*/true))
781           return false;
782       }
783       break;
784     case tok::kw_for:
785       if (Style.Language == FormatStyle::LK_JavaScript) {
786         // x.for and {for: ...}
787         if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
788             (Tok->Next && Tok->Next->is(tok::colon)))
789           break;
790         // JS' for await ( ...
791         if (CurrentToken && CurrentToken->is(Keywords.kw_await))
792           next();
793       }
794       Contexts.back().ColonIsForRangeExpr = true;
795       next();
796       if (!parseParens())
797         return false;
798       break;
799     case tok::l_paren:
800       // When faced with 'operator()()', the kw_operator handler incorrectly
801       // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
802       // the first two parens OverloadedOperators and the second l_paren an
803       // OverloadedOperatorLParen.
804       if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
805           Tok->Previous->MatchingParen &&
806           Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
807         Tok->Previous->Type = TT_OverloadedOperator;
808         Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
809         Tok->Type = TT_OverloadedOperatorLParen;
810       }
811 
812       if (!parseParens())
813         return false;
814       if (Line.MustBeDeclaration && Contexts.size() == 1 &&
815           !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
816           (!Tok->Previous ||
817            !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
818                                    TT_LeadingJavaAnnotation)))
819         Line.MightBeFunctionDecl = true;
820       break;
821     case tok::l_square:
822       if (!parseSquare())
823         return false;
824       break;
825     case tok::l_brace:
826       if (Style.Language == FormatStyle::LK_TextProto) {
827         FormatToken *Previous = Tok->getPreviousNonComment();
828         if (Previous && Previous->Type != TT_DictLiteral)
829           Previous->Type = TT_SelectorName;
830       }
831       if (!parseBrace())
832         return false;
833       break;
834     case tok::less:
835       if (parseAngle()) {
836         Tok->Type = TT_TemplateOpener;
837         // In TT_Proto, we must distignuish between:
838         //   map<key, value>
839         //   msg < item: data >
840         //   msg: < item: data >
841         // In TT_TextProto, map<key, value> does not occur.
842         if (Style.Language == FormatStyle::LK_TextProto ||
843             (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
844              Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
845           Tok->Type = TT_DictLiteral;
846           FormatToken *Previous = Tok->getPreviousNonComment();
847           if (Previous && Previous->Type != TT_DictLiteral)
848             Previous->Type = TT_SelectorName;
849         }
850       } else {
851         Tok->Type = TT_BinaryOperator;
852         NonTemplateLess.insert(Tok);
853         CurrentToken = Tok;
854         next();
855       }
856       break;
857     case tok::r_paren:
858     case tok::r_square:
859       return false;
860     case tok::r_brace:
861       // Lines can start with '}'.
862       if (Tok->Previous)
863         return false;
864       break;
865     case tok::greater:
866       if (Style.Language != FormatStyle::LK_TextProto)
867         Tok->Type = TT_BinaryOperator;
868       break;
869     case tok::kw_operator:
870       if (Style.Language == FormatStyle::LK_TextProto ||
871           Style.Language == FormatStyle::LK_Proto)
872         break;
873       while (CurrentToken &&
874              !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
875         if (CurrentToken->isOneOf(tok::star, tok::amp))
876           CurrentToken->Type = TT_PointerOrReference;
877         consumeToken();
878         if (CurrentToken &&
879             CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
880                                             tok::comma))
881           CurrentToken->Previous->Type = TT_OverloadedOperator;
882       }
883       if (CurrentToken) {
884         CurrentToken->Type = TT_OverloadedOperatorLParen;
885         if (CurrentToken->Previous->is(TT_BinaryOperator))
886           CurrentToken->Previous->Type = TT_OverloadedOperator;
887       }
888       break;
889     case tok::question:
890       if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
891           Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
892                              tok::r_brace)) {
893         // Question marks before semicolons, colons, etc. indicate optional
894         // types (fields, parameters), e.g.
895         //   function(x?: string, y?) {...}
896         //   class X { y?; }
897         Tok->Type = TT_JsTypeOptionalQuestion;
898         break;
899       }
900       // Declarations cannot be conditional expressions, this can only be part
901       // of a type declaration.
902       if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
903           Style.Language == FormatStyle::LK_JavaScript)
904         break;
905       parseConditional();
906       break;
907     case tok::kw_template:
908       parseTemplateDeclaration();
909       break;
910     case tok::comma:
911       if (Contexts.back().InCtorInitializer)
912         Tok->Type = TT_CtorInitializerComma;
913       else if (Contexts.back().InInheritanceList)
914         Tok->Type = TT_InheritanceComma;
915       else if (Contexts.back().FirstStartOfName &&
916                (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
917         Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
918         Line.IsMultiVariableDeclStmt = true;
919       }
920       if (Contexts.back().IsForEachMacro)
921         Contexts.back().IsExpression = true;
922       break;
923     case tok::identifier:
924       if (Tok->isOneOf(Keywords.kw___has_include,
925                        Keywords.kw___has_include_next)) {
926         parseHasInclude();
927       }
928       break;
929     default:
930       break;
931     }
932     return true;
933   }
934 
935   void parseIncludeDirective() {
936     if (CurrentToken && CurrentToken->is(tok::less)) {
937       next();
938       while (CurrentToken) {
939         // Mark tokens up to the trailing line comments as implicit string
940         // literals.
941         if (CurrentToken->isNot(tok::comment) &&
942             !CurrentToken->TokenText.startswith("//"))
943           CurrentToken->Type = TT_ImplicitStringLiteral;
944         next();
945       }
946     }
947   }
948 
949   void parseWarningOrError() {
950     next();
951     // We still want to format the whitespace left of the first token of the
952     // warning or error.
953     next();
954     while (CurrentToken) {
955       CurrentToken->Type = TT_ImplicitStringLiteral;
956       next();
957     }
958   }
959 
960   void parsePragma() {
961     next(); // Consume "pragma".
962     if (CurrentToken &&
963         CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
964       bool IsMark = CurrentToken->is(Keywords.kw_mark);
965       next(); // Consume "mark".
966       next(); // Consume first token (so we fix leading whitespace).
967       while (CurrentToken) {
968         if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
969           CurrentToken->Type = TT_ImplicitStringLiteral;
970         next();
971       }
972     }
973   }
974 
975   void parseHasInclude() {
976     if (!CurrentToken || !CurrentToken->is(tok::l_paren))
977       return;
978     next(); // '('
979     parseIncludeDirective();
980     next(); // ')'
981   }
982 
983   LineType parsePreprocessorDirective() {
984     bool IsFirstToken = CurrentToken->IsFirst;
985     LineType Type = LT_PreprocessorDirective;
986     next();
987     if (!CurrentToken)
988       return Type;
989 
990     if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
991       // JavaScript files can contain shebang lines of the form:
992       // #!/usr/bin/env node
993       // Treat these like C++ #include directives.
994       while (CurrentToken) {
995         // Tokens cannot be comments here.
996         CurrentToken->Type = TT_ImplicitStringLiteral;
997         next();
998       }
999       return LT_ImportStatement;
1000     }
1001 
1002     if (CurrentToken->Tok.is(tok::numeric_constant)) {
1003       CurrentToken->SpacesRequiredBefore = 1;
1004       return Type;
1005     }
1006     // Hashes in the middle of a line can lead to any strange token
1007     // sequence.
1008     if (!CurrentToken->Tok.getIdentifierInfo())
1009       return Type;
1010     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
1011     case tok::pp_include:
1012     case tok::pp_include_next:
1013     case tok::pp_import:
1014       next();
1015       parseIncludeDirective();
1016       Type = LT_ImportStatement;
1017       break;
1018     case tok::pp_error:
1019     case tok::pp_warning:
1020       parseWarningOrError();
1021       break;
1022     case tok::pp_pragma:
1023       parsePragma();
1024       break;
1025     case tok::pp_if:
1026     case tok::pp_elif:
1027       Contexts.back().IsExpression = true;
1028       parseLine();
1029       break;
1030     default:
1031       break;
1032     }
1033     while (CurrentToken) {
1034       FormatToken *Tok = CurrentToken;
1035       next();
1036       if (Tok->is(tok::l_paren))
1037         parseParens();
1038       else if (Tok->isOneOf(Keywords.kw___has_include,
1039                             Keywords.kw___has_include_next))
1040         parseHasInclude();
1041     }
1042     return Type;
1043   }
1044 
1045 public:
1046   LineType parseLine() {
1047     NonTemplateLess.clear();
1048     if (CurrentToken->is(tok::hash))
1049       return parsePreprocessorDirective();
1050 
1051     // Directly allow to 'import <string-literal>' to support protocol buffer
1052     // definitions (github.com/google/protobuf) or missing "#" (either way we
1053     // should not break the line).
1054     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
1055     if ((Style.Language == FormatStyle::LK_Java &&
1056          CurrentToken->is(Keywords.kw_package)) ||
1057         (Info && Info->getPPKeywordID() == tok::pp_import &&
1058          CurrentToken->Next &&
1059          CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
1060                                      tok::kw_static))) {
1061       next();
1062       parseIncludeDirective();
1063       return LT_ImportStatement;
1064     }
1065 
1066     // If this line starts and ends in '<' and '>', respectively, it is likely
1067     // part of "#define <a/b.h>".
1068     if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
1069       parseIncludeDirective();
1070       return LT_ImportStatement;
1071     }
1072 
1073     // In .proto files, top-level options are very similar to import statements
1074     // and should not be line-wrapped.
1075     if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
1076         CurrentToken->is(Keywords.kw_option)) {
1077       next();
1078       if (CurrentToken && CurrentToken->is(tok::identifier))
1079         return LT_ImportStatement;
1080     }
1081 
1082     bool KeywordVirtualFound = false;
1083     bool ImportStatement = false;
1084 
1085     // import {...} from '...';
1086     if (Style.Language == FormatStyle::LK_JavaScript &&
1087         CurrentToken->is(Keywords.kw_import))
1088       ImportStatement = true;
1089 
1090     while (CurrentToken) {
1091       if (CurrentToken->is(tok::kw_virtual))
1092         KeywordVirtualFound = true;
1093       if (Style.Language == FormatStyle::LK_JavaScript) {
1094         // export {...} from '...';
1095         // An export followed by "from 'some string';" is a re-export from
1096         // another module identified by a URI and is treated as a
1097         // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
1098         // Just "export {...};" or "export class ..." should not be treated as
1099         // an import in this sense.
1100         if (Line.First->is(tok::kw_export) &&
1101             CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
1102             CurrentToken->Next->isStringLiteral())
1103           ImportStatement = true;
1104         if (isClosureImportStatement(*CurrentToken))
1105           ImportStatement = true;
1106       }
1107       if (!consumeToken())
1108         return LT_Invalid;
1109     }
1110     if (KeywordVirtualFound)
1111       return LT_VirtualFunctionDecl;
1112     if (ImportStatement)
1113       return LT_ImportStatement;
1114 
1115     if (Line.startsWith(TT_ObjCMethodSpecifier)) {
1116       if (Contexts.back().FirstObjCSelectorName)
1117         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
1118             Contexts.back().LongestObjCSelectorName;
1119       return LT_ObjCMethodDecl;
1120     }
1121 
1122     return LT_Other;
1123   }
1124 
1125 private:
1126   bool isClosureImportStatement(const FormatToken &Tok) {
1127     // FIXME: Closure-library specific stuff should not be hard-coded but be
1128     // configurable.
1129     return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
1130            Tok.Next->Next &&
1131            (Tok.Next->Next->TokenText == "module" ||
1132             Tok.Next->Next->TokenText == "provide" ||
1133             Tok.Next->Next->TokenText == "require" ||
1134             Tok.Next->Next->TokenText == "requireType" ||
1135             Tok.Next->Next->TokenText == "forwardDeclare") &&
1136            Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
1137   }
1138 
1139   void resetTokenMetadata(FormatToken *Token) {
1140     if (!Token)
1141       return;
1142 
1143     // Reset token type in case we have already looked at it and then
1144     // recovered from an error (e.g. failure to find the matching >).
1145     if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
1146                                TT_FunctionLBrace, TT_ImplicitStringLiteral,
1147                                TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
1148                                TT_OverloadedOperator, TT_RegexLiteral,
1149                                TT_TemplateString, TT_ObjCStringLiteral))
1150       CurrentToken->Type = TT_Unknown;
1151     CurrentToken->Role.reset();
1152     CurrentToken->MatchingParen = nullptr;
1153     CurrentToken->FakeLParens.clear();
1154     CurrentToken->FakeRParens = 0;
1155   }
1156 
1157   void next() {
1158     if (CurrentToken) {
1159       CurrentToken->NestingLevel = Contexts.size() - 1;
1160       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
1161       modifyContext(*CurrentToken);
1162       determineTokenType(*CurrentToken);
1163       CurrentToken = CurrentToken->Next;
1164     }
1165 
1166     resetTokenMetadata(CurrentToken);
1167   }
1168 
1169   /// A struct to hold information valid in a specific context, e.g.
1170   /// a pair of parenthesis.
1171   struct Context {
1172     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
1173             bool IsExpression)
1174         : ContextKind(ContextKind), BindingStrength(BindingStrength),
1175           IsExpression(IsExpression) {}
1176 
1177     tok::TokenKind ContextKind;
1178     unsigned BindingStrength;
1179     bool IsExpression;
1180     unsigned LongestObjCSelectorName = 0;
1181     bool ColonIsForRangeExpr = false;
1182     bool ColonIsDictLiteral = false;
1183     bool ColonIsObjCMethodExpr = false;
1184     FormatToken *FirstObjCSelectorName = nullptr;
1185     FormatToken *FirstStartOfName = nullptr;
1186     bool CanBeExpression = true;
1187     bool InTemplateArgument = false;
1188     bool InCtorInitializer = false;
1189     bool InInheritanceList = false;
1190     bool CaretFound = false;
1191     bool IsForEachMacro = false;
1192     bool InCpp11AttributeSpecifier = false;
1193   };
1194 
1195   /// Puts a new \c Context onto the stack \c Contexts for the lifetime
1196   /// of each instance.
1197   struct ScopedContextCreator {
1198     AnnotatingParser &P;
1199 
1200     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1201                          unsigned Increase)
1202         : P(P) {
1203       P.Contexts.push_back(Context(ContextKind,
1204                                    P.Contexts.back().BindingStrength + Increase,
1205                                    P.Contexts.back().IsExpression));
1206     }
1207 
1208     ~ScopedContextCreator() { P.Contexts.pop_back(); }
1209   };
1210 
1211   void modifyContext(const FormatToken &Current) {
1212     if (Current.getPrecedence() == prec::Assignment &&
1213         !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1214         // Type aliases use `type X = ...;` in TypeScript and can be exported
1215         // using `export type ...`.
1216         !(Style.Language == FormatStyle::LK_JavaScript &&
1217           (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1218            Line.startsWith(tok::kw_export, Keywords.kw_type,
1219                            tok::identifier))) &&
1220         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1221       Contexts.back().IsExpression = true;
1222       if (!Line.startsWith(TT_UnaryOperator)) {
1223         for (FormatToken *Previous = Current.Previous;
1224              Previous && Previous->Previous &&
1225              !Previous->Previous->isOneOf(tok::comma, tok::semi);
1226              Previous = Previous->Previous) {
1227           if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1228             Previous = Previous->MatchingParen;
1229             if (!Previous)
1230               break;
1231           }
1232           if (Previous->opensScope())
1233             break;
1234           if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1235               Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1236               Previous->Previous && Previous->Previous->isNot(tok::equal))
1237             Previous->Type = TT_PointerOrReference;
1238         }
1239       }
1240     } else if (Current.is(tok::lessless) &&
1241                (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1242       Contexts.back().IsExpression = true;
1243     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1244       Contexts.back().IsExpression = true;
1245     } else if (Current.is(TT_TrailingReturnArrow)) {
1246       Contexts.back().IsExpression = false;
1247     } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1248       Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1249     } else if (Current.Previous &&
1250                Current.Previous->is(TT_CtorInitializerColon)) {
1251       Contexts.back().IsExpression = true;
1252       Contexts.back().InCtorInitializer = true;
1253     } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1254       Contexts.back().InInheritanceList = true;
1255     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1256       for (FormatToken *Previous = Current.Previous;
1257            Previous && Previous->isOneOf(tok::star, tok::amp);
1258            Previous = Previous->Previous)
1259         Previous->Type = TT_PointerOrReference;
1260       if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1261         Contexts.back().IsExpression = false;
1262     } else if (Current.is(tok::kw_new)) {
1263       Contexts.back().CanBeExpression = false;
1264     } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1265       // This should be the condition or increment in a for-loop.
1266       Contexts.back().IsExpression = true;
1267     }
1268   }
1269 
1270   void determineTokenType(FormatToken &Current) {
1271     if (!Current.is(TT_Unknown))
1272       // The token type is already known.
1273       return;
1274 
1275     if (Style.Language == FormatStyle::LK_JavaScript) {
1276       if (Current.is(tok::exclaim)) {
1277         if (Current.Previous &&
1278             (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1279                                        tok::r_paren, tok::r_square,
1280                                        tok::r_brace) ||
1281              Current.Previous->Tok.isLiteral())) {
1282           Current.Type = TT_JsNonNullAssertion;
1283           return;
1284         }
1285         if (Current.Next &&
1286             Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1287           Current.Type = TT_JsNonNullAssertion;
1288           return;
1289         }
1290       }
1291     }
1292 
1293     // Line.MightBeFunctionDecl can only be true after the parentheses of a
1294     // function declaration have been found. In this case, 'Current' is a
1295     // trailing token of this declaration and thus cannot be a name.
1296     if (Current.is(Keywords.kw_instanceof)) {
1297       Current.Type = TT_BinaryOperator;
1298     } else if (isStartOfName(Current) &&
1299                (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1300       Contexts.back().FirstStartOfName = &Current;
1301       Current.Type = TT_StartOfName;
1302     } else if (Current.is(tok::semi)) {
1303       // Reset FirstStartOfName after finding a semicolon so that a for loop
1304       // with multiple increment statements is not confused with a for loop
1305       // having multiple variable declarations.
1306       Contexts.back().FirstStartOfName = nullptr;
1307     } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1308       AutoFound = true;
1309     } else if (Current.is(tok::arrow) &&
1310                Style.Language == FormatStyle::LK_Java) {
1311       Current.Type = TT_LambdaArrow;
1312     } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1313                Current.NestingLevel == 0) {
1314       Current.Type = TT_TrailingReturnArrow;
1315     } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1316       Current.Type = determineStarAmpUsage(Current,
1317                                            Contexts.back().CanBeExpression &&
1318                                                Contexts.back().IsExpression,
1319                                            Contexts.back().InTemplateArgument);
1320     } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1321       Current.Type = determinePlusMinusCaretUsage(Current);
1322       if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1323         Contexts.back().CaretFound = true;
1324     } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1325       Current.Type = determineIncrementUsage(Current);
1326     } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1327       Current.Type = TT_UnaryOperator;
1328     } else if (Current.is(tok::question)) {
1329       if (Style.Language == FormatStyle::LK_JavaScript &&
1330           Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1331         // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1332         // on the interface, not a ternary expression.
1333         Current.Type = TT_JsTypeOptionalQuestion;
1334       } else {
1335         Current.Type = TT_ConditionalExpr;
1336       }
1337     } else if (Current.isBinaryOperator() &&
1338                (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
1339                (!Current.is(tok::greater) &&
1340                 Style.Language != FormatStyle::LK_TextProto)) {
1341       Current.Type = TT_BinaryOperator;
1342     } else if (Current.is(tok::comment)) {
1343       if (Current.TokenText.startswith("/*")) {
1344         if (Current.TokenText.endswith("*/"))
1345           Current.Type = TT_BlockComment;
1346         else
1347           // The lexer has for some reason determined a comment here. But we
1348           // cannot really handle it, if it isn't properly terminated.
1349           Current.Tok.setKind(tok::unknown);
1350       } else {
1351         Current.Type = TT_LineComment;
1352       }
1353     } else if (Current.is(tok::r_paren)) {
1354       if (rParenEndsCast(Current))
1355         Current.Type = TT_CastRParen;
1356       if (Current.MatchingParen && Current.Next &&
1357           !Current.Next->isBinaryOperator() &&
1358           !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1359                                  tok::comma, tok::period, tok::arrow,
1360                                  tok::coloncolon))
1361         if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1362           // Make sure this isn't the return type of an Obj-C block declaration
1363           if (AfterParen->Tok.isNot(tok::caret)) {
1364             if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1365               if (BeforeParen->is(tok::identifier) &&
1366                   BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1367                   (!BeforeParen->Previous ||
1368                    BeforeParen->Previous->ClosesTemplateDeclaration))
1369                 Current.Type = TT_FunctionAnnotationRParen;
1370           }
1371         }
1372     } else if (Current.is(tok::at) && Current.Next &&
1373                Style.Language != FormatStyle::LK_JavaScript &&
1374                Style.Language != FormatStyle::LK_Java) {
1375       // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1376       // marks declarations and properties that need special formatting.
1377       switch (Current.Next->Tok.getObjCKeywordID()) {
1378       case tok::objc_interface:
1379       case tok::objc_implementation:
1380       case tok::objc_protocol:
1381         Current.Type = TT_ObjCDecl;
1382         break;
1383       case tok::objc_property:
1384         Current.Type = TT_ObjCProperty;
1385         break;
1386       default:
1387         break;
1388       }
1389     } else if (Current.is(tok::period)) {
1390       FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1391       if (PreviousNoComment &&
1392           PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1393         Current.Type = TT_DesignatedInitializerPeriod;
1394       else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1395                Current.Previous->isOneOf(TT_JavaAnnotation,
1396                                          TT_LeadingJavaAnnotation)) {
1397         Current.Type = Current.Previous->Type;
1398       }
1399     } else if (canBeObjCSelectorComponent(Current) &&
1400                // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
1401                Current.Previous && Current.Previous->is(TT_CastRParen) &&
1402                Current.Previous->MatchingParen &&
1403                Current.Previous->MatchingParen->Previous &&
1404                Current.Previous->MatchingParen->Previous->is(
1405                    TT_ObjCMethodSpecifier)) {
1406       // This is the first part of an Objective-C selector name. (If there's no
1407       // colon after this, this is the only place which annotates the identifier
1408       // as a selector.)
1409       Current.Type = TT_SelectorName;
1410     } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1411                Current.Previous &&
1412                !Current.Previous->isOneOf(tok::equal, tok::at) &&
1413                Line.MightBeFunctionDecl && Contexts.size() == 1) {
1414       // Line.MightBeFunctionDecl can only be true after the parentheses of a
1415       // function declaration have been found.
1416       Current.Type = TT_TrailingAnnotation;
1417     } else if ((Style.Language == FormatStyle::LK_Java ||
1418                 Style.Language == FormatStyle::LK_JavaScript) &&
1419                Current.Previous) {
1420       if (Current.Previous->is(tok::at) &&
1421           Current.isNot(Keywords.kw_interface)) {
1422         const FormatToken &AtToken = *Current.Previous;
1423         const FormatToken *Previous = AtToken.getPreviousNonComment();
1424         if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1425           Current.Type = TT_LeadingJavaAnnotation;
1426         else
1427           Current.Type = TT_JavaAnnotation;
1428       } else if (Current.Previous->is(tok::period) &&
1429                  Current.Previous->isOneOf(TT_JavaAnnotation,
1430                                            TT_LeadingJavaAnnotation)) {
1431         Current.Type = Current.Previous->Type;
1432       }
1433     }
1434   }
1435 
1436   /// Take a guess at whether \p Tok starts a name of a function or
1437   /// variable declaration.
1438   ///
1439   /// This is a heuristic based on whether \p Tok is an identifier following
1440   /// something that is likely a type.
1441   bool isStartOfName(const FormatToken &Tok) {
1442     if (Tok.isNot(tok::identifier) || !Tok.Previous)
1443       return false;
1444 
1445     if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1446                               Keywords.kw_as))
1447       return false;
1448     if (Style.Language == FormatStyle::LK_JavaScript &&
1449         Tok.Previous->is(Keywords.kw_in))
1450       return false;
1451 
1452     // Skip "const" as it does not have an influence on whether this is a name.
1453     FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1454     while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1455       PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1456 
1457     if (!PreviousNotConst)
1458       return false;
1459 
1460     bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1461                        PreviousNotConst->Previous &&
1462                        PreviousNotConst->Previous->is(tok::hash);
1463 
1464     if (PreviousNotConst->is(TT_TemplateCloser))
1465       return PreviousNotConst && PreviousNotConst->MatchingParen &&
1466              PreviousNotConst->MatchingParen->Previous &&
1467              PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1468              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1469 
1470     if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1471         PreviousNotConst->MatchingParen->Previous &&
1472         PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1473       return true;
1474 
1475     return (!IsPPKeyword &&
1476             PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1477            PreviousNotConst->is(TT_PointerOrReference) ||
1478            PreviousNotConst->isSimpleTypeSpecifier();
1479   }
1480 
1481   /// Determine whether ')' is ending a cast.
1482   bool rParenEndsCast(const FormatToken &Tok) {
1483     // C-style casts are only used in C++ and Java.
1484     if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1485       return false;
1486 
1487     // Empty parens aren't casts and there are no casts at the end of the line.
1488     if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1489       return false;
1490 
1491     FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1492     if (LeftOfParens) {
1493       // If there is a closing parenthesis left of the current parentheses,
1494       // look past it as these might be chained casts.
1495       if (LeftOfParens->is(tok::r_paren)) {
1496         if (!LeftOfParens->MatchingParen ||
1497             !LeftOfParens->MatchingParen->Previous)
1498           return false;
1499         LeftOfParens = LeftOfParens->MatchingParen->Previous;
1500       }
1501 
1502       // If there is an identifier (or with a few exceptions a keyword) right
1503       // before the parentheses, this is unlikely to be a cast.
1504       if (LeftOfParens->Tok.getIdentifierInfo() &&
1505           !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1506                                  tok::kw_delete))
1507         return false;
1508 
1509       // Certain other tokens right before the parentheses are also signals that
1510       // this cannot be a cast.
1511       if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1512                                 TT_TemplateCloser, tok::ellipsis))
1513         return false;
1514     }
1515 
1516     if (Tok.Next->is(tok::question))
1517       return false;
1518 
1519     // As Java has no function types, a "(" after the ")" likely means that this
1520     // is a cast.
1521     if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1522       return true;
1523 
1524     // If a (non-string) literal follows, this is likely a cast.
1525     if (Tok.Next->isNot(tok::string_literal) &&
1526         (Tok.Next->Tok.isLiteral() ||
1527          Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1528       return true;
1529 
1530     // Heuristically try to determine whether the parentheses contain a type.
1531     bool ParensAreType =
1532         !Tok.Previous ||
1533         Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1534         Tok.Previous->isSimpleTypeSpecifier();
1535     bool ParensCouldEndDecl =
1536         Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1537     if (ParensAreType && !ParensCouldEndDecl)
1538       return true;
1539 
1540     // At this point, we heuristically assume that there are no casts at the
1541     // start of the line. We assume that we have found most cases where there
1542     // are by the logic above, e.g. "(void)x;".
1543     if (!LeftOfParens)
1544       return false;
1545 
1546     // Certain token types inside the parentheses mean that this can't be a
1547     // cast.
1548     for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1549          Token = Token->Next)
1550       if (Token->is(TT_BinaryOperator))
1551         return false;
1552 
1553     // If the following token is an identifier or 'this', this is a cast. All
1554     // cases where this can be something else are handled above.
1555     if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1556       return true;
1557 
1558     if (!Tok.Next->Next)
1559       return false;
1560 
1561     // If the next token after the parenthesis is a unary operator, assume
1562     // that this is cast, unless there are unexpected tokens inside the
1563     // parenthesis.
1564     bool NextIsUnary =
1565         Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1566     if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1567         !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1568       return false;
1569     // Search for unexpected tokens.
1570     for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1571          Prev = Prev->Previous) {
1572       if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1573         return false;
1574     }
1575     return true;
1576   }
1577 
1578   /// Return the type of the given token assuming it is * or &.
1579   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1580                                   bool InTemplateArgument) {
1581     if (Style.Language == FormatStyle::LK_JavaScript)
1582       return TT_BinaryOperator;
1583 
1584     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1585     if (!PrevToken)
1586       return TT_UnaryOperator;
1587 
1588     const FormatToken *NextToken = Tok.getNextNonComment();
1589     if (!NextToken ||
1590         NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1591         (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1592       return TT_PointerOrReference;
1593 
1594     if (PrevToken->is(tok::coloncolon))
1595       return TT_PointerOrReference;
1596 
1597     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1598                            tok::comma, tok::semi, tok::kw_return, tok::colon,
1599                            tok::equal, tok::kw_delete, tok::kw_sizeof,
1600                            tok::kw_throw) ||
1601         PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1602                            TT_UnaryOperator, TT_CastRParen))
1603       return TT_UnaryOperator;
1604 
1605     if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1606       return TT_PointerOrReference;
1607     if (NextToken->is(tok::kw_operator) && !IsExpression)
1608       return TT_PointerOrReference;
1609     if (NextToken->isOneOf(tok::comma, tok::semi))
1610       return TT_PointerOrReference;
1611 
1612     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1613       FormatToken *TokenBeforeMatchingParen =
1614           PrevToken->MatchingParen->getPreviousNonComment();
1615       if (TokenBeforeMatchingParen &&
1616           TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
1617         return TT_PointerOrReference;
1618     }
1619 
1620     if (PrevToken->Tok.isLiteral() ||
1621         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1622                            tok::kw_false, tok::r_brace) ||
1623         NextToken->Tok.isLiteral() ||
1624         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1625         NextToken->isUnaryOperator() ||
1626         // If we know we're in a template argument, there are no named
1627         // declarations. Thus, having an identifier on the right-hand side
1628         // indicates a binary operator.
1629         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1630       return TT_BinaryOperator;
1631 
1632     // "&&(" is quite unlikely to be two successive unary "&".
1633     if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1634       return TT_BinaryOperator;
1635 
1636     // This catches some cases where evaluation order is used as control flow:
1637     //   aaa && aaa->f();
1638     const FormatToken *NextNextToken = NextToken->getNextNonComment();
1639     if (NextNextToken && NextNextToken->is(tok::arrow))
1640       return TT_BinaryOperator;
1641 
1642     // It is very unlikely that we are going to find a pointer or reference type
1643     // definition on the RHS of an assignment.
1644     if (IsExpression && !Contexts.back().CaretFound)
1645       return TT_BinaryOperator;
1646 
1647     return TT_PointerOrReference;
1648   }
1649 
1650   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1651     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1652     if (!PrevToken)
1653       return TT_UnaryOperator;
1654 
1655     if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
1656       // This must be a sequence of leading unary operators.
1657       return TT_UnaryOperator;
1658 
1659     // Use heuristics to recognize unary operators.
1660     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1661                            tok::question, tok::colon, tok::kw_return,
1662                            tok::kw_case, tok::at, tok::l_brace))
1663       return TT_UnaryOperator;
1664 
1665     // There can't be two consecutive binary operators.
1666     if (PrevToken->is(TT_BinaryOperator))
1667       return TT_UnaryOperator;
1668 
1669     // Fall back to marking the token as binary operator.
1670     return TT_BinaryOperator;
1671   }
1672 
1673   /// Determine whether ++/-- are pre- or post-increments/-decrements.
1674   TokenType determineIncrementUsage(const FormatToken &Tok) {
1675     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1676     if (!PrevToken || PrevToken->is(TT_CastRParen))
1677       return TT_UnaryOperator;
1678     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1679       return TT_TrailingUnaryOperator;
1680 
1681     return TT_UnaryOperator;
1682   }
1683 
1684   SmallVector<Context, 8> Contexts;
1685 
1686   const FormatStyle &Style;
1687   AnnotatedLine &Line;
1688   FormatToken *CurrentToken;
1689   bool AutoFound;
1690   const AdditionalKeywords &Keywords;
1691 
1692   // Set of "<" tokens that do not open a template parameter list. If parseAngle
1693   // determines that a specific token can't be a template opener, it will make
1694   // same decision irrespective of the decisions for tokens leading up to it.
1695   // Store this information to prevent this from causing exponential runtime.
1696   llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1697 };
1698 
1699 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1700 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1701 
1702 /// Parses binary expressions by inserting fake parenthesis based on
1703 /// operator precedence.
1704 class ExpressionParser {
1705 public:
1706   ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1707                    AnnotatedLine &Line)
1708       : Style(Style), Keywords(Keywords), Current(Line.First) {}
1709 
1710   /// Parse expressions with the given operator precedence.
1711   void parse(int Precedence = 0) {
1712     // Skip 'return' and ObjC selector colons as they are not part of a binary
1713     // expression.
1714     while (Current && (Current->is(tok::kw_return) ||
1715                        (Current->is(tok::colon) &&
1716                         Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1717       next();
1718 
1719     if (!Current || Precedence > PrecedenceArrowAndPeriod)
1720       return;
1721 
1722     // Conditional expressions need to be parsed separately for proper nesting.
1723     if (Precedence == prec::Conditional) {
1724       parseConditionalExpr();
1725       return;
1726     }
1727 
1728     // Parse unary operators, which all have a higher precedence than binary
1729     // operators.
1730     if (Precedence == PrecedenceUnaryOperator) {
1731       parseUnaryOperator();
1732       return;
1733     }
1734 
1735     FormatToken *Start = Current;
1736     FormatToken *LatestOperator = nullptr;
1737     unsigned OperatorIndex = 0;
1738 
1739     while (Current) {
1740       // Consume operators with higher precedence.
1741       parse(Precedence + 1);
1742 
1743       int CurrentPrecedence = getCurrentPrecedence();
1744 
1745       if (Current && Current->is(TT_SelectorName) &&
1746           Precedence == CurrentPrecedence) {
1747         if (LatestOperator)
1748           addFakeParenthesis(Start, prec::Level(Precedence));
1749         Start = Current;
1750       }
1751 
1752       // At the end of the line or when an operator with higher precedence is
1753       // found, insert fake parenthesis and return.
1754       if (!Current ||
1755           (Current->closesScope() &&
1756            (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1757           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1758           (CurrentPrecedence == prec::Conditional &&
1759            Precedence == prec::Assignment && Current->is(tok::colon))) {
1760         break;
1761       }
1762 
1763       // Consume scopes: (), [], <> and {}
1764       if (Current->opensScope()) {
1765         // In fragment of a JavaScript template string can look like '}..${' and
1766         // thus close a scope and open a new one at the same time.
1767         while (Current && (!Current->closesScope() || Current->opensScope())) {
1768           next();
1769           parse();
1770         }
1771         next();
1772       } else {
1773         // Operator found.
1774         if (CurrentPrecedence == Precedence) {
1775           if (LatestOperator)
1776             LatestOperator->NextOperator = Current;
1777           LatestOperator = Current;
1778           Current->OperatorIndex = OperatorIndex;
1779           ++OperatorIndex;
1780         }
1781         next(/*SkipPastLeadingComments=*/Precedence > 0);
1782       }
1783     }
1784 
1785     if (LatestOperator && (Current || Precedence > 0)) {
1786       // LatestOperator->LastOperator = true;
1787       if (Precedence == PrecedenceArrowAndPeriod) {
1788         // Call expressions don't have a binary operator precedence.
1789         addFakeParenthesis(Start, prec::Unknown);
1790       } else {
1791         addFakeParenthesis(Start, prec::Level(Precedence));
1792       }
1793     }
1794   }
1795 
1796 private:
1797   /// Gets the precedence (+1) of the given token for binary operators
1798   /// and other tokens that we treat like binary operators.
1799   int getCurrentPrecedence() {
1800     if (Current) {
1801       const FormatToken *NextNonComment = Current->getNextNonComment();
1802       if (Current->is(TT_ConditionalExpr))
1803         return prec::Conditional;
1804       if (NextNonComment && Current->is(TT_SelectorName) &&
1805           (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
1806            ((Style.Language == FormatStyle::LK_Proto ||
1807              Style.Language == FormatStyle::LK_TextProto) &&
1808             NextNonComment->is(tok::less))))
1809         return prec::Assignment;
1810       if (Current->is(TT_JsComputedPropertyName))
1811         return prec::Assignment;
1812       if (Current->is(TT_LambdaArrow))
1813         return prec::Comma;
1814       if (Current->is(TT_JsFatArrow))
1815         return prec::Assignment;
1816       if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1817           (Current->is(tok::comment) && NextNonComment &&
1818            NextNonComment->is(TT_SelectorName)))
1819         return 0;
1820       if (Current->is(TT_RangeBasedForLoopColon))
1821         return prec::Comma;
1822       if ((Style.Language == FormatStyle::LK_Java ||
1823            Style.Language == FormatStyle::LK_JavaScript) &&
1824           Current->is(Keywords.kw_instanceof))
1825         return prec::Relational;
1826       if (Style.Language == FormatStyle::LK_JavaScript &&
1827           Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1828         return prec::Relational;
1829       if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1830         return Current->getPrecedence();
1831       if (Current->isOneOf(tok::period, tok::arrow))
1832         return PrecedenceArrowAndPeriod;
1833       if ((Style.Language == FormatStyle::LK_Java ||
1834            Style.Language == FormatStyle::LK_JavaScript) &&
1835           Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1836                            Keywords.kw_throws))
1837         return 0;
1838     }
1839     return -1;
1840   }
1841 
1842   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1843     Start->FakeLParens.push_back(Precedence);
1844     if (Precedence > prec::Unknown)
1845       Start->StartsBinaryExpression = true;
1846     if (Current) {
1847       FormatToken *Previous = Current->Previous;
1848       while (Previous->is(tok::comment) && Previous->Previous)
1849         Previous = Previous->Previous;
1850       ++Previous->FakeRParens;
1851       if (Precedence > prec::Unknown)
1852         Previous->EndsBinaryExpression = true;
1853     }
1854   }
1855 
1856   /// Parse unary operator expressions and surround them with fake
1857   /// parentheses if appropriate.
1858   void parseUnaryOperator() {
1859     llvm::SmallVector<FormatToken *, 2> Tokens;
1860     while (Current && Current->is(TT_UnaryOperator)) {
1861       Tokens.push_back(Current);
1862       next();
1863     }
1864     parse(PrecedenceArrowAndPeriod);
1865     for (FormatToken *Token : llvm::reverse(Tokens))
1866       // The actual precedence doesn't matter.
1867       addFakeParenthesis(Token, prec::Unknown);
1868   }
1869 
1870   void parseConditionalExpr() {
1871     while (Current && Current->isTrailingComment()) {
1872       next();
1873     }
1874     FormatToken *Start = Current;
1875     parse(prec::LogicalOr);
1876     if (!Current || !Current->is(tok::question))
1877       return;
1878     next();
1879     parse(prec::Assignment);
1880     if (!Current || Current->isNot(TT_ConditionalExpr))
1881       return;
1882     next();
1883     parse(prec::Assignment);
1884     addFakeParenthesis(Start, prec::Conditional);
1885   }
1886 
1887   void next(bool SkipPastLeadingComments = true) {
1888     if (Current)
1889       Current = Current->Next;
1890     while (Current &&
1891            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1892            Current->isTrailingComment())
1893       Current = Current->Next;
1894   }
1895 
1896   const FormatStyle &Style;
1897   const AdditionalKeywords &Keywords;
1898   FormatToken *Current;
1899 };
1900 
1901 } // end anonymous namespace
1902 
1903 void TokenAnnotator::setCommentLineLevels(
1904     SmallVectorImpl<AnnotatedLine *> &Lines) {
1905   const AnnotatedLine *NextNonCommentLine = nullptr;
1906   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1907                                                           E = Lines.rend();
1908        I != E; ++I) {
1909     bool CommentLine = true;
1910     for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1911       if (!Tok->is(tok::comment)) {
1912         CommentLine = false;
1913         break;
1914       }
1915     }
1916 
1917     // If the comment is currently aligned with the line immediately following
1918     // it, that's probably intentional and we should keep it.
1919     if (NextNonCommentLine && CommentLine &&
1920         NextNonCommentLine->First->NewlinesBefore <= 1 &&
1921         NextNonCommentLine->First->OriginalColumn ==
1922             (*I)->First->OriginalColumn) {
1923       // Align comments for preprocessor lines with the # in column 0.
1924       // Otherwise, align with the next line.
1925       (*I)->Level = (NextNonCommentLine->Type == LT_PreprocessorDirective ||
1926                      NextNonCommentLine->Type == LT_ImportStatement)
1927                         ? 0
1928                         : NextNonCommentLine->Level;
1929     } else {
1930       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1931     }
1932 
1933     setCommentLineLevels((*I)->Children);
1934   }
1935 }
1936 
1937 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1938   unsigned Result = 0;
1939   for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1940     Result = std::max(Result, Tok->NestingLevel);
1941   return Result;
1942 }
1943 
1944 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1945   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1946                                                   E = Line.Children.end();
1947        I != E; ++I) {
1948     annotate(**I);
1949   }
1950   AnnotatingParser Parser(Style, Line, Keywords);
1951   Line.Type = Parser.parseLine();
1952 
1953   // With very deep nesting, ExpressionParser uses lots of stack and the
1954   // formatting algorithm is very slow. We're not going to do a good job here
1955   // anyway - it's probably generated code being formatted by mistake.
1956   // Just skip the whole line.
1957   if (maxNestingDepth(Line) > 50)
1958     Line.Type = LT_Invalid;
1959 
1960   if (Line.Type == LT_Invalid)
1961     return;
1962 
1963   ExpressionParser ExprParser(Style, Keywords, Line);
1964   ExprParser.parse();
1965 
1966   if (Line.startsWith(TT_ObjCMethodSpecifier))
1967     Line.Type = LT_ObjCMethodDecl;
1968   else if (Line.startsWith(TT_ObjCDecl))
1969     Line.Type = LT_ObjCDecl;
1970   else if (Line.startsWith(TT_ObjCProperty))
1971     Line.Type = LT_ObjCProperty;
1972 
1973   Line.First->SpacesRequiredBefore = 1;
1974   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1975 }
1976 
1977 // This function heuristically determines whether 'Current' starts the name of a
1978 // function declaration.
1979 static bool isFunctionDeclarationName(const FormatToken &Current,
1980                                       const AnnotatedLine &Line) {
1981   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
1982     for (; Next; Next = Next->Next) {
1983       if (Next->is(TT_OverloadedOperatorLParen))
1984         return Next;
1985       if (Next->is(TT_OverloadedOperator))
1986         continue;
1987       if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1988         // For 'new[]' and 'delete[]'.
1989         if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
1990             Next->Next->Next->is(tok::r_square))
1991           Next = Next->Next->Next;
1992         continue;
1993       }
1994 
1995       break;
1996     }
1997     return nullptr;
1998   };
1999 
2000   // Find parentheses of parameter list.
2001   const FormatToken *Next = Current.Next;
2002   if (Current.is(tok::kw_operator)) {
2003     if (Current.Previous && Current.Previous->is(tok::coloncolon))
2004       return false;
2005     Next = skipOperatorName(Next);
2006   } else {
2007     if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
2008       return false;
2009     for (; Next; Next = Next->Next) {
2010       if (Next->is(TT_TemplateOpener)) {
2011         Next = Next->MatchingParen;
2012       } else if (Next->is(tok::coloncolon)) {
2013         Next = Next->Next;
2014         if (!Next)
2015           return false;
2016         if (Next->is(tok::kw_operator)) {
2017           Next = skipOperatorName(Next->Next);
2018           break;
2019         }
2020         if (!Next->is(tok::identifier))
2021           return false;
2022       } else if (Next->is(tok::l_paren)) {
2023         break;
2024       } else {
2025         return false;
2026       }
2027     }
2028   }
2029 
2030   // Check whether parameter list can belong to a function declaration.
2031   if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
2032     return false;
2033   // If the lines ends with "{", this is likely an function definition.
2034   if (Line.Last->is(tok::l_brace))
2035     return true;
2036   if (Next->Next == Next->MatchingParen)
2037     return true; // Empty parentheses.
2038   // If there is an &/&& after the r_paren, this is likely a function.
2039   if (Next->MatchingParen->Next &&
2040       Next->MatchingParen->Next->is(TT_PointerOrReference))
2041     return true;
2042   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
2043        Tok = Tok->Next) {
2044     if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
2045       Tok = Tok->MatchingParen;
2046       continue;
2047     }
2048     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
2049         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
2050       return true;
2051     if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
2052         Tok->Tok.isLiteral())
2053       return false;
2054   }
2055   return false;
2056 }
2057 
2058 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
2059   assert(Line.MightBeFunctionDecl);
2060 
2061   if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
2062        Style.AlwaysBreakAfterReturnType ==
2063            FormatStyle::RTBS_TopLevelDefinitions) &&
2064       Line.Level > 0)
2065     return false;
2066 
2067   switch (Style.AlwaysBreakAfterReturnType) {
2068   case FormatStyle::RTBS_None:
2069     return false;
2070   case FormatStyle::RTBS_All:
2071   case FormatStyle::RTBS_TopLevel:
2072     return true;
2073   case FormatStyle::RTBS_AllDefinitions:
2074   case FormatStyle::RTBS_TopLevelDefinitions:
2075     return Line.mightBeFunctionDefinition();
2076   }
2077 
2078   return false;
2079 }
2080 
2081 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2082   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2083                                                   E = Line.Children.end();
2084        I != E; ++I) {
2085     calculateFormattingInformation(**I);
2086   }
2087 
2088   Line.First->TotalLength =
2089       Line.First->IsMultiline ? Style.ColumnLimit
2090                               : Line.FirstStartColumn + Line.First->ColumnWidth;
2091   FormatToken *Current = Line.First->Next;
2092   bool InFunctionDecl = Line.MightBeFunctionDecl;
2093   while (Current) {
2094     if (isFunctionDeclarationName(*Current, Line))
2095       Current->Type = TT_FunctionDeclarationName;
2096     if (Current->is(TT_LineComment)) {
2097       if (Current->Previous->BlockKind == BK_BracedInit &&
2098           Current->Previous->opensScope())
2099         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
2100       else
2101         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2102 
2103       // If we find a trailing comment, iterate backwards to determine whether
2104       // it seems to relate to a specific parameter. If so, break before that
2105       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2106       // to the previous line in:
2107       //   SomeFunction(a,
2108       //                b, // comment
2109       //                c);
2110       if (!Current->HasUnescapedNewline) {
2111         for (FormatToken *Parameter = Current->Previous; Parameter;
2112              Parameter = Parameter->Previous) {
2113           if (Parameter->isOneOf(tok::comment, tok::r_brace))
2114             break;
2115           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2116             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2117                 Parameter->HasUnescapedNewline)
2118               Parameter->MustBreakBefore = true;
2119             break;
2120           }
2121         }
2122       }
2123     } else if (Current->SpacesRequiredBefore == 0 &&
2124                spaceRequiredBefore(Line, *Current)) {
2125       Current->SpacesRequiredBefore = 1;
2126     }
2127 
2128     Current->MustBreakBefore =
2129         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2130 
2131     if (!Current->MustBreakBefore && InFunctionDecl &&
2132         Current->is(TT_FunctionDeclarationName))
2133       Current->MustBreakBefore = mustBreakForReturnType(Line);
2134 
2135     Current->CanBreakBefore =
2136         Current->MustBreakBefore || canBreakBefore(Line, *Current);
2137     unsigned ChildSize = 0;
2138     if (Current->Previous->Children.size() == 1) {
2139       FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
2140       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2141                                                   : LastOfChild.TotalLength + 1;
2142     }
2143     const FormatToken *Prev = Current->Previous;
2144     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2145         (Prev->Children.size() == 1 &&
2146          Prev->Children[0]->First->MustBreakBefore) ||
2147         Current->IsMultiline)
2148       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2149     else
2150       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2151                              ChildSize + Current->SpacesRequiredBefore;
2152 
2153     if (Current->is(TT_CtorInitializerColon))
2154       InFunctionDecl = false;
2155 
2156     // FIXME: Only calculate this if CanBreakBefore is true once static
2157     // initializers etc. are sorted out.
2158     // FIXME: Move magic numbers to a better place.
2159 
2160     // Reduce penalty for aligning ObjC method arguments using the colon
2161     // alignment as this is the canonical way (still prefer fitting everything
2162     // into one line if possible). Trying to fit a whole expression into one
2163     // line should not force other line breaks (e.g. when ObjC method
2164     // expression is a part of other expression).
2165     Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
2166     if (Style.Language == FormatStyle::LK_ObjC &&
2167         Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
2168       if (Current->ParameterIndex == 1)
2169         Current->SplitPenalty += 5 * Current->BindingStrength;
2170     } else {
2171       Current->SplitPenalty += 20 * Current->BindingStrength;
2172     }
2173 
2174     Current = Current->Next;
2175   }
2176 
2177   calculateUnbreakableTailLengths(Line);
2178   unsigned IndentLevel = Line.Level;
2179   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2180     if (Current->Role)
2181       Current->Role->precomputeFormattingInfos(Current);
2182     if (Current->MatchingParen &&
2183         Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
2184       assert(IndentLevel > 0);
2185       --IndentLevel;
2186     }
2187     Current->IndentLevel = IndentLevel;
2188     if (Current->opensBlockOrBlockTypeList(Style))
2189       ++IndentLevel;
2190   }
2191 
2192   LLVM_DEBUG({ printDebugInfo(Line); });
2193 }
2194 
2195 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2196   unsigned UnbreakableTailLength = 0;
2197   FormatToken *Current = Line.Last;
2198   while (Current) {
2199     Current->UnbreakableTailLength = UnbreakableTailLength;
2200     if (Current->CanBreakBefore ||
2201         Current->isOneOf(tok::comment, tok::string_literal)) {
2202       UnbreakableTailLength = 0;
2203     } else {
2204       UnbreakableTailLength +=
2205           Current->ColumnWidth + Current->SpacesRequiredBefore;
2206     }
2207     Current = Current->Previous;
2208   }
2209 }
2210 
2211 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2212                                       const FormatToken &Tok,
2213                                       bool InFunctionDecl) {
2214   const FormatToken &Left = *Tok.Previous;
2215   const FormatToken &Right = Tok;
2216 
2217   if (Left.is(tok::semi))
2218     return 0;
2219 
2220   if (Style.Language == FormatStyle::LK_Java) {
2221     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2222       return 1;
2223     if (Right.is(Keywords.kw_implements))
2224       return 2;
2225     if (Left.is(tok::comma) && Left.NestingLevel == 0)
2226       return 3;
2227   } else if (Style.Language == FormatStyle::LK_JavaScript) {
2228     if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2229       return 100;
2230     if (Left.is(TT_JsTypeColon))
2231       return 35;
2232     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2233         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2234       return 100;
2235     // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2236     if (Left.opensScope() && Right.closesScope())
2237       return 200;
2238   }
2239 
2240   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2241     return 1;
2242   if (Right.is(tok::l_square)) {
2243     if (Style.Language == FormatStyle::LK_Proto)
2244       return 1;
2245     if (Left.is(tok::r_square))
2246       return 200;
2247     // Slightly prefer formatting local lambda definitions like functions.
2248     if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2249       return 35;
2250     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2251                        TT_ArrayInitializerLSquare,
2252                        TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2253       return 500;
2254   }
2255 
2256   if (Left.is(tok::coloncolon) ||
2257       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2258     return 500;
2259   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2260       Right.is(tok::kw_operator)) {
2261     if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2262       return 3;
2263     if (Left.is(TT_StartOfName))
2264       return 110;
2265     if (InFunctionDecl && Right.NestingLevel == 0)
2266       return Style.PenaltyReturnTypeOnItsOwnLine;
2267     return 200;
2268   }
2269   if (Right.is(TT_PointerOrReference))
2270     return 190;
2271   if (Right.is(TT_LambdaArrow))
2272     return 110;
2273   if (Left.is(tok::equal) && Right.is(tok::l_brace))
2274     return 160;
2275   if (Left.is(TT_CastRParen))
2276     return 100;
2277   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2278     return 5000;
2279   if (Left.is(tok::comment))
2280     return 1000;
2281 
2282   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2283                    TT_CtorInitializerColon))
2284     return 2;
2285 
2286   if (Right.isMemberAccess()) {
2287     // Breaking before the "./->" of a chained call/member access is reasonably
2288     // cheap, as formatting those with one call per line is generally
2289     // desirable. In particular, it should be cheaper to break before the call
2290     // than it is to break inside a call's parameters, which could lead to weird
2291     // "hanging" indents. The exception is the very last "./->" to support this
2292     // frequent pattern:
2293     //
2294     //   aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2295     //       dddddddd);
2296     //
2297     // which might otherwise be blown up onto many lines. Here, clang-format
2298     // won't produce "hanging" indents anyway as there is no other trailing
2299     // call.
2300     //
2301     // Also apply higher penalty is not a call as that might lead to a wrapping
2302     // like:
2303     //
2304     //   aaaaaaa
2305     //       .aaaaaaaaa.bbbbbbbb(cccccccc);
2306     return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2307                ? 150
2308                : 35;
2309   }
2310 
2311   if (Right.is(TT_TrailingAnnotation) &&
2312       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2313     // Moving trailing annotations to the next line is fine for ObjC method
2314     // declarations.
2315     if (Line.startsWith(TT_ObjCMethodSpecifier))
2316       return 10;
2317     // Generally, breaking before a trailing annotation is bad unless it is
2318     // function-like. It seems to be especially preferable to keep standard
2319     // annotations (i.e. "const", "final" and "override") on the same line.
2320     // Use a slightly higher penalty after ")" so that annotations like
2321     // "const override" are kept together.
2322     bool is_short_annotation = Right.TokenText.size() < 10;
2323     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2324   }
2325 
2326   // In for-loops, prefer breaking at ',' and ';'.
2327   if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2328     return 4;
2329 
2330   // In Objective-C method expressions, prefer breaking before "param:" over
2331   // breaking after it.
2332   if (Right.is(TT_SelectorName))
2333     return 0;
2334   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2335     return Line.MightBeFunctionDecl ? 50 : 500;
2336 
2337   // In Objective-C type declarations, avoid breaking after the category's
2338   // open paren (we'll prefer breaking after the protocol list's opening
2339   // angle bracket, if present).
2340   if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
2341       Left.Previous->isOneOf(tok::identifier, tok::greater))
2342     return 500;
2343 
2344   if (Left.is(tok::l_paren) && InFunctionDecl &&
2345       Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2346     return 100;
2347   if (Left.is(tok::l_paren) && Left.Previous &&
2348       (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
2349        Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
2350     return 1000;
2351   if (Left.is(tok::equal) && InFunctionDecl)
2352     return 110;
2353   if (Right.is(tok::r_brace))
2354     return 1;
2355   if (Left.is(TT_TemplateOpener))
2356     return 100;
2357   if (Left.opensScope()) {
2358     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2359       return 0;
2360     if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
2361       return 19;
2362     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2363                                    : 19;
2364   }
2365   if (Left.is(TT_JavaAnnotation))
2366     return 50;
2367 
2368   if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2369       Left.Previous->isLabelString() &&
2370       (Left.NextOperator || Left.OperatorIndex != 0))
2371     return 50;
2372   if (Right.is(tok::plus) && Left.isLabelString() &&
2373       (Right.NextOperator || Right.OperatorIndex != 0))
2374     return 25;
2375   if (Left.is(tok::comma))
2376     return 1;
2377   if (Right.is(tok::lessless) && Left.isLabelString() &&
2378       (Right.NextOperator || Right.OperatorIndex != 1))
2379     return 25;
2380   if (Right.is(tok::lessless)) {
2381     // Breaking at a << is really cheap.
2382     if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2383       // Slightly prefer to break before the first one in log-like statements.
2384       return 2;
2385     return 1;
2386   }
2387   if (Left.ClosesTemplateDeclaration)
2388     return Style.PenaltyBreakTemplateDeclaration;
2389   if (Left.is(TT_ConditionalExpr))
2390     return prec::Conditional;
2391   prec::Level Level = Left.getPrecedence();
2392   if (Level == prec::Unknown)
2393     Level = Right.getPrecedence();
2394   if (Level == prec::Assignment)
2395     return Style.PenaltyBreakAssignment;
2396   if (Level != prec::Unknown)
2397     return Level;
2398 
2399   return 3;
2400 }
2401 
2402 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2403                                           const FormatToken &Left,
2404                                           const FormatToken &Right) {
2405   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2406     return true;
2407   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2408     return true;
2409   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2410       Left.Tok.getObjCKeywordID() == tok::objc_property)
2411     return true;
2412   if (Right.is(tok::hashhash))
2413     return Left.is(tok::hash);
2414   if (Left.isOneOf(tok::hashhash, tok::hash))
2415     return Right.is(tok::hash);
2416   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2417     return Style.SpaceInEmptyParentheses;
2418   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2419     return (Right.is(TT_CastRParen) ||
2420             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2421                ? Style.SpacesInCStyleCastParentheses
2422                : Style.SpacesInParentheses;
2423   if (Right.isOneOf(tok::semi, tok::comma))
2424     return false;
2425   if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
2426     bool IsLightweightGeneric =
2427         Right.MatchingParen && Right.MatchingParen->Next &&
2428         Right.MatchingParen->Next->is(tok::colon);
2429     return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
2430   }
2431   if (Right.is(tok::less) && Left.is(tok::kw_template))
2432     return Style.SpaceAfterTemplateKeyword;
2433   if (Left.isOneOf(tok::exclaim, tok::tilde))
2434     return false;
2435   if (Left.is(tok::at) &&
2436       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2437                     tok::numeric_constant, tok::l_paren, tok::l_brace,
2438                     tok::kw_true, tok::kw_false))
2439     return false;
2440   if (Left.is(tok::colon))
2441     return !Left.is(TT_ObjCMethodExpr);
2442   if (Left.is(tok::coloncolon))
2443     return false;
2444   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
2445     if (Style.Language == FormatStyle::LK_TextProto ||
2446         (Style.Language == FormatStyle::LK_Proto &&
2447          (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
2448       // Format empty list as `<>`.
2449       if (Left.is(tok::less) && Right.is(tok::greater))
2450         return false;
2451       return !Style.Cpp11BracedListStyle;
2452     }
2453     return false;
2454   }
2455   if (Right.is(tok::ellipsis))
2456     return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2457                                     Left.Previous->is(tok::kw_case));
2458   if (Left.is(tok::l_square) && Right.is(tok::amp))
2459     return false;
2460   if (Right.is(TT_PointerOrReference)) {
2461     if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2462       if (!Left.MatchingParen)
2463         return true;
2464       FormatToken *TokenBeforeMatchingParen =
2465           Left.MatchingParen->getPreviousNonComment();
2466       if (!TokenBeforeMatchingParen ||
2467           !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
2468         return true;
2469     }
2470     return (Left.Tok.isLiteral() ||
2471             (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2472              (Style.PointerAlignment != FormatStyle::PAS_Left ||
2473               (Line.IsMultiVariableDeclStmt &&
2474                (Left.NestingLevel == 0 ||
2475                 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2476   }
2477   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2478       (!Left.is(TT_PointerOrReference) ||
2479        (Style.PointerAlignment != FormatStyle::PAS_Right &&
2480         !Line.IsMultiVariableDeclStmt)))
2481     return true;
2482   if (Left.is(TT_PointerOrReference))
2483     return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2484            (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2485             !Right.is(TT_StartOfName)) ||
2486            (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2487            (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2488                            tok::l_paren) &&
2489             (Style.PointerAlignment != FormatStyle::PAS_Right &&
2490              !Line.IsMultiVariableDeclStmt) &&
2491             Left.Previous &&
2492             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2493   if (Right.is(tok::star) && Left.is(tok::l_paren))
2494     return false;
2495   const auto SpaceRequiredForArrayInitializerLSquare =
2496       [](const FormatToken &LSquareTok, const FormatStyle &Style) {
2497         return Style.SpacesInContainerLiterals ||
2498                ((Style.Language == FormatStyle::LK_Proto ||
2499                  Style.Language == FormatStyle::LK_TextProto) &&
2500                 !Style.Cpp11BracedListStyle &&
2501                 LSquareTok.endsSequence(tok::l_square, tok::colon,
2502                                         TT_SelectorName));
2503       };
2504   if (Left.is(tok::l_square))
2505     return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
2506             SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
2507            (Left.isOneOf(TT_ArraySubscriptLSquare,
2508                          TT_StructuredBindingLSquare) &&
2509             Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2510   if (Right.is(tok::r_square))
2511     return Right.MatchingParen &&
2512            ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
2513              SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
2514                                                      Style)) ||
2515             (Style.SpacesInSquareBrackets &&
2516              Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2517                                           TT_StructuredBindingLSquare)) ||
2518             Right.MatchingParen->is(TT_AttributeParen));
2519   if (Right.is(tok::l_square) &&
2520       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2521                      TT_DesignatedInitializerLSquare,
2522                      TT_StructuredBindingLSquare, TT_AttributeSquare) &&
2523       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2524     return false;
2525   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2526     return !Left.Children.empty(); // No spaces in "{}".
2527   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2528       (Right.is(tok::r_brace) && Right.MatchingParen &&
2529        Right.MatchingParen->BlockKind != BK_Block))
2530     return !Style.Cpp11BracedListStyle;
2531   if (Left.is(TT_BlockComment))
2532     // No whitespace in x(/*foo=*/1), except for JavaScript.
2533     return Style.Language == FormatStyle::LK_JavaScript ||
2534            !Left.TokenText.endswith("=*/");
2535   if (Right.is(tok::l_paren)) {
2536     if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
2537         (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
2538       return true;
2539     return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2540            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2541             (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2542                           tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2543                           TT_ObjCForIn) ||
2544              Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
2545              (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2546                            tok::kw_new, tok::kw_delete) &&
2547               (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2548            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2549             (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2550              Left.is(tok::r_paren)) &&
2551             Line.Type != LT_PreprocessorDirective);
2552   }
2553   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2554     return false;
2555   if (Right.is(TT_UnaryOperator))
2556     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2557            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2558   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2559                     tok::r_paren) ||
2560        Left.isSimpleTypeSpecifier()) &&
2561       Right.is(tok::l_brace) && Right.getNextNonComment() &&
2562       Right.BlockKind != BK_Block)
2563     return false;
2564   if (Left.is(tok::period) || Right.is(tok::period))
2565     return false;
2566   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2567     return false;
2568   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2569       Left.MatchingParen->Previous &&
2570       (Left.MatchingParen->Previous->is(tok::period) ||
2571        Left.MatchingParen->Previous->is(tok::coloncolon)))
2572     // Java call to generic function with explicit type:
2573     // A.<B<C<...>>>DoSomething();
2574     // A::<B<C<...>>>DoSomething();  // With a Java 8 method reference.
2575     return false;
2576   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2577     return false;
2578   if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
2579     // Objective-C dictionary literal -> no space after opening brace.
2580     return false;
2581   if (Right.is(tok::r_brace) && Right.MatchingParen &&
2582       Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
2583     // Objective-C dictionary literal -> no space before closing brace.
2584     return false;
2585   return true;
2586 }
2587 
2588 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2589                                          const FormatToken &Right) {
2590   const FormatToken &Left = *Right.Previous;
2591   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2592     return true; // Never ever merge two identifiers.
2593   if (Style.isCpp()) {
2594     if (Left.is(tok::kw_operator))
2595       return Right.is(tok::coloncolon);
2596     if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
2597         !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
2598       return true;
2599   } else if (Style.Language == FormatStyle::LK_Proto ||
2600              Style.Language == FormatStyle::LK_TextProto) {
2601     if (Right.is(tok::period) &&
2602         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2603                      Keywords.kw_repeated, Keywords.kw_extend))
2604       return true;
2605     if (Right.is(tok::l_paren) &&
2606         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2607       return true;
2608     if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2609       return true;
2610     // Slashes occur in text protocol extension syntax: [type/type] { ... }.
2611     if (Left.is(tok::slash) || Right.is(tok::slash))
2612       return false;
2613     if (Left.MatchingParen && Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
2614         Right.isOneOf(tok::l_brace, tok::less))
2615       return !Style.Cpp11BracedListStyle;
2616     // A percent is probably part of a formatting specification, such as %lld.
2617     if (Left.is(tok::percent))
2618       return false;
2619     // Preserve the existence of a space before a percent for cases like 0x%04x
2620     // and "%d %d"
2621     if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
2622       return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
2623   } else if (Style.Language == FormatStyle::LK_JavaScript) {
2624     if (Left.is(TT_JsFatArrow))
2625       return true;
2626     // for await ( ...
2627     if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
2628         Left.Previous->is(tok::kw_for))
2629       return true;
2630     if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2631         Right.MatchingParen) {
2632       const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2633       // An async arrow function, for example: `x = async () => foo();`,
2634       // as opposed to calling a function called async: `x = async();`
2635       if (Next && Next->is(TT_JsFatArrow))
2636         return true;
2637     }
2638     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2639         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2640       return false;
2641     // In tagged template literals ("html`bar baz`"), there is no space between
2642     // the tag identifier and the template string. getIdentifierInfo makes sure
2643     // that the identifier is not a pseudo keyword like `yield`, either.
2644     if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
2645         Right.is(TT_TemplateString))
2646       return false;
2647     if (Right.is(tok::star) &&
2648         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2649       return false;
2650     if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2651         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
2652                      Keywords.kw_extends, Keywords.kw_implements))
2653       return true;
2654     if (Right.is(tok::l_paren)) {
2655       // JS methods can use some keywords as names (e.g. `delete()`).
2656       if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
2657         return false;
2658       // Valid JS method names can include keywords, e.g. `foo.delete()` or
2659       // `bar.instanceof()`. Recognize call positions by preceding period.
2660       if (Left.Previous && Left.Previous->is(tok::period) &&
2661           Left.Tok.getIdentifierInfo())
2662         return false;
2663       // Additional unary JavaScript operators that need a space after.
2664       if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
2665                        tok::kw_void))
2666         return true;
2667     }
2668     if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2669                       tok::kw_const) ||
2670          // "of" is only a keyword if it appears after another identifier
2671          // (e.g. as "const x of y" in a for loop), or after a destructuring
2672          // operation (const [x, y] of z, const {a, b} of c).
2673          (Left.is(Keywords.kw_of) && Left.Previous &&
2674           (Left.Previous->Tok.is(tok::identifier) ||
2675            Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
2676         (!Left.Previous || !Left.Previous->is(tok::period)))
2677       return true;
2678     if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2679         Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2680       return false;
2681     if (Left.is(Keywords.kw_as) &&
2682         Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2683       return true;
2684     if (Left.is(tok::kw_default) && Left.Previous &&
2685         Left.Previous->is(tok::kw_export))
2686       return true;
2687     if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2688       return true;
2689     if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2690       return false;
2691     if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2692       return false;
2693     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2694         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2695       return false;
2696     if (Left.is(tok::ellipsis))
2697       return false;
2698     if (Left.is(TT_TemplateCloser) &&
2699         !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2700                        Keywords.kw_implements, Keywords.kw_extends))
2701       // Type assertions ('<type>expr') are not followed by whitespace. Other
2702       // locations that should have whitespace following are identified by the
2703       // above set of follower tokens.
2704       return false;
2705     if (Right.is(TT_JsNonNullAssertion))
2706       return false;
2707     if (Left.is(TT_JsNonNullAssertion) &&
2708         Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
2709       return true; // "x! as string", "x! in y"
2710   } else if (Style.Language == FormatStyle::LK_Java) {
2711     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2712       return true;
2713     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2714       return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2715     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2716                       tok::kw_protected) ||
2717          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2718                       Keywords.kw_native)) &&
2719         Right.is(TT_TemplateOpener))
2720       return true;
2721   }
2722   if (Left.is(TT_ImplicitStringLiteral))
2723     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2724   if (Line.Type == LT_ObjCMethodDecl) {
2725     if (Left.is(TT_ObjCMethodSpecifier))
2726       return true;
2727     if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
2728       // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
2729       // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
2730       // method declaration.
2731       return false;
2732   }
2733   if (Line.Type == LT_ObjCProperty &&
2734       (Right.is(tok::equal) || Left.is(tok::equal)))
2735     return false;
2736 
2737   if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2738       Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2739     return true;
2740   if (Right.is(TT_OverloadedOperatorLParen))
2741     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2742   if (Left.is(tok::comma))
2743     return true;
2744   if (Right.is(tok::comma))
2745     return false;
2746   if (Right.is(TT_ObjCBlockLParen))
2747     return true;
2748   if (Right.is(TT_CtorInitializerColon))
2749     return Style.SpaceBeforeCtorInitializerColon;
2750   if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
2751     return false;
2752   if (Right.is(TT_RangeBasedForLoopColon) &&
2753       !Style.SpaceBeforeRangeBasedForLoopColon)
2754     return false;
2755   if (Right.is(tok::colon)) {
2756     if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2757         !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2758       return false;
2759     if (Right.is(TT_ObjCMethodExpr))
2760       return false;
2761     if (Left.is(tok::question))
2762       return false;
2763     if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2764       return false;
2765     if (Right.is(TT_DictLiteral))
2766       return Style.SpacesInContainerLiterals;
2767     if (Right.is(TT_AttributeColon))
2768       return false;
2769     return true;
2770   }
2771   if (Left.is(TT_UnaryOperator))
2772     return Right.is(TT_BinaryOperator);
2773 
2774   // If the next token is a binary operator or a selector name, we have
2775   // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2776   if (Left.is(TT_CastRParen))
2777     return Style.SpaceAfterCStyleCast ||
2778            Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2779 
2780   if (Left.is(tok::greater) && Right.is(tok::greater)) {
2781     if (Style.Language == FormatStyle::LK_TextProto ||
2782         (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
2783       return !Style.Cpp11BracedListStyle;
2784     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2785            (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2786   }
2787   if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
2788       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2789       (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
2790     return false;
2791   if (!Style.SpaceBeforeAssignmentOperators &&
2792       Right.getPrecedence() == prec::Assignment)
2793     return false;
2794   if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) &&
2795       (Left.is(tok::identifier) || Left.is(tok::kw_this)))
2796     return false;
2797   if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2798     // Generally don't remove existing spaces between an identifier and "::".
2799     // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2800     // this turns out to be too lenient, add analysis of the identifier itself.
2801     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2802   if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2803     return (Left.is(TT_TemplateOpener) &&
2804             Style.Standard == FormatStyle::LS_Cpp03) ||
2805            !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2806                           tok::kw___super, TT_TemplateCloser,
2807                           TT_TemplateOpener)) ||
2808            (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
2809   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2810     return Style.SpacesInAngles;
2811   // Space before TT_StructuredBindingLSquare.
2812   if (Right.is(TT_StructuredBindingLSquare))
2813     return !Left.isOneOf(tok::amp, tok::ampamp) ||
2814            Style.PointerAlignment != FormatStyle::PAS_Right;
2815   // Space before & or && following a TT_StructuredBindingLSquare.
2816   if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
2817       Right.isOneOf(tok::amp, tok::ampamp))
2818     return Style.PointerAlignment != FormatStyle::PAS_Left;
2819   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2820       (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2821        !Right.is(tok::r_paren)))
2822     return true;
2823   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2824       Right.isNot(TT_FunctionTypeLParen))
2825     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2826   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2827       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2828     return false;
2829   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2830       Line.startsWith(tok::hash))
2831     return true;
2832   if (Right.is(TT_TrailingUnaryOperator))
2833     return false;
2834   if (Left.is(TT_RegexLiteral))
2835     return false;
2836   return spaceRequiredBetween(Line, Left, Right);
2837 }
2838 
2839 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2840 static bool isAllmanBrace(const FormatToken &Tok) {
2841   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2842          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2843 }
2844 
2845 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2846                                      const FormatToken &Right) {
2847   const FormatToken &Left = *Right.Previous;
2848   if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2849     return true;
2850 
2851   if (Style.Language == FormatStyle::LK_JavaScript) {
2852     // FIXME: This might apply to other languages and token kinds.
2853     if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2854         Left.Previous->is(tok::string_literal))
2855       return true;
2856     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2857         Left.Previous && Left.Previous->is(tok::equal) &&
2858         Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2859                             tok::kw_const) &&
2860         // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2861         // above.
2862         !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2863       // Object literals on the top level of a file are treated as "enum-style".
2864       // Each key/value pair is put on a separate line, instead of bin-packing.
2865       return true;
2866     if (Left.is(tok::l_brace) && Line.Level == 0 &&
2867         (Line.startsWith(tok::kw_enum) ||
2868          Line.startsWith(tok::kw_const, tok::kw_enum) ||
2869          Line.startsWith(tok::kw_export, tok::kw_enum) ||
2870          Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
2871       // JavaScript top-level enum key/value pairs are put on separate lines
2872       // instead of bin-packing.
2873       return true;
2874     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2875         !Left.Children.empty())
2876       // Support AllowShortFunctionsOnASingleLine for JavaScript.
2877       return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2878              Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2879              (Left.NestingLevel == 0 && Line.Level == 0 &&
2880               Style.AllowShortFunctionsOnASingleLine &
2881                   FormatStyle::SFS_InlineOnly);
2882   } else if (Style.Language == FormatStyle::LK_Java) {
2883     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2884         Right.Next->is(tok::string_literal))
2885       return true;
2886   } else if (Style.Language == FormatStyle::LK_Cpp ||
2887              Style.Language == FormatStyle::LK_ObjC ||
2888              Style.Language == FormatStyle::LK_Proto ||
2889              Style.Language == FormatStyle::LK_TableGen ||
2890              Style.Language == FormatStyle::LK_TextProto) {
2891     if (Left.isStringLiteral() && Right.isStringLiteral())
2892       return true;
2893   }
2894 
2895   // If the last token before a '}', ']', or ')' is a comma or a trailing
2896   // comment, the intention is to insert a line break after it in order to make
2897   // shuffling around entries easier. Import statements, especially in
2898   // JavaScript, can be an exception to this rule.
2899   if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
2900     const FormatToken *BeforeClosingBrace = nullptr;
2901     if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2902          (Style.Language == FormatStyle::LK_JavaScript &&
2903           Left.is(tok::l_paren))) &&
2904         Left.BlockKind != BK_Block && Left.MatchingParen)
2905       BeforeClosingBrace = Left.MatchingParen->Previous;
2906     else if (Right.MatchingParen &&
2907              (Right.MatchingParen->isOneOf(tok::l_brace,
2908                                            TT_ArrayInitializerLSquare) ||
2909               (Style.Language == FormatStyle::LK_JavaScript &&
2910                Right.MatchingParen->is(tok::l_paren))))
2911       BeforeClosingBrace = &Left;
2912     if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2913                                BeforeClosingBrace->isTrailingComment()))
2914       return true;
2915   }
2916 
2917   if (Right.is(tok::comment))
2918     return Left.BlockKind != BK_BracedInit &&
2919            Left.isNot(TT_CtorInitializerColon) &&
2920            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2921   if (Left.isTrailingComment())
2922     return true;
2923   if (Right.Previous->IsUnterminatedLiteral)
2924     return true;
2925   if (Right.is(tok::lessless) && Right.Next &&
2926       Right.Previous->is(tok::string_literal) &&
2927       Right.Next->is(tok::string_literal))
2928     return true;
2929   if (Right.Previous->ClosesTemplateDeclaration &&
2930       Right.Previous->MatchingParen &&
2931       Right.Previous->MatchingParen->NestingLevel == 0 &&
2932       Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
2933     return true;
2934   if (Right.is(TT_CtorInitializerComma) &&
2935       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2936       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2937     return true;
2938   if (Right.is(TT_CtorInitializerColon) &&
2939       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2940       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2941     return true;
2942   // Break only if we have multiple inheritance.
2943   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
2944       Right.is(TT_InheritanceComma))
2945     return true;
2946   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2947     // Multiline raw string literals are special wrt. line breaks. The author
2948     // has made a deliberate choice and might have aligned the contents of the
2949     // string literal accordingly. Thus, we try keep existing line breaks.
2950     return Right.IsMultiline && Right.NewlinesBefore > 0;
2951   if ((Right.Previous->is(tok::l_brace) ||
2952        (Right.Previous->is(tok::less) && Right.Previous->Previous &&
2953         Right.Previous->Previous->is(tok::equal))) &&
2954       Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
2955     // Don't put enums or option definitions onto single lines in protocol
2956     // buffers.
2957     return true;
2958   }
2959   if (Right.is(TT_InlineASMBrace))
2960     return Right.HasUnescapedNewline;
2961   if (isAllmanBrace(Left) || isAllmanBrace(Right))
2962     return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2963            (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
2964             Style.BraceWrapping.AfterEnum) ||
2965            (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2966            (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2967   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2968     return true;
2969 
2970   if ((Style.Language == FormatStyle::LK_Java ||
2971        Style.Language == FormatStyle::LK_JavaScript) &&
2972       Left.is(TT_LeadingJavaAnnotation) &&
2973       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2974       (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2975     return true;
2976 
2977   if (Right.is(TT_ProtoExtensionLSquare))
2978     return true;
2979 
2980   // In text proto instances if a submessage contains at least 2 entries and at
2981   // least one of them is a submessage, like A { ... B { ... } ... },
2982   // put all of the entries of A on separate lines by forcing the selector of
2983   // the submessage B to be put on a newline.
2984   //
2985   // Example: these can stay on one line:
2986   // a { scalar_1: 1 scalar_2: 2 }
2987   // a { b { key: value } }
2988   //
2989   // and these entries need to be on a new line even if putting them all in one
2990   // line is under the column limit:
2991   // a {
2992   //   scalar: 1
2993   //   b { key: value }
2994   // }
2995   //
2996   // We enforce this by breaking before a submessage field that has previous
2997   // siblings, *and* breaking before a field that follows a submessage field.
2998   //
2999   // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
3000   // the TT_SelectorName there, but we don't want to break inside the brackets.
3001   //
3002   // Another edge case is @submessage { key: value }, which is a common
3003   // substitution placeholder. In this case we want to keep `@` and `submessage`
3004   // together.
3005   //
3006   // We ensure elsewhere that extensions are always on their own line.
3007   if ((Style.Language == FormatStyle::LK_Proto ||
3008        Style.Language == FormatStyle::LK_TextProto) &&
3009       Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
3010     // Keep `@submessage` together in:
3011     // @submessage { key: value }
3012     if (Right.Previous && Right.Previous->is(tok::at))
3013       return false;
3014     // Look for the scope opener after selector in cases like:
3015     // selector { ...
3016     // selector: { ...
3017     // selector: @base { ...
3018     FormatToken *LBrace = Right.Next;
3019     if (LBrace && LBrace->is(tok::colon)) {
3020       LBrace = LBrace->Next;
3021       if (LBrace && LBrace->is(tok::at)) {
3022         LBrace = LBrace->Next;
3023         if (LBrace)
3024           LBrace = LBrace->Next;
3025       }
3026     }
3027     if (LBrace &&
3028         // The scope opener is one of {, [, <:
3029         // selector { ... }
3030         // selector [ ... ]
3031         // selector < ... >
3032         //
3033         // In case of selector { ... }, the l_brace is TT_DictLiteral.
3034         // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
3035         // so we check for immediately following r_brace.
3036         ((LBrace->is(tok::l_brace) &&
3037           (LBrace->is(TT_DictLiteral) ||
3038            (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
3039          LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
3040       // If Left.ParameterCount is 0, then this submessage entry is not the
3041       // first in its parent submessage, and we want to break before this entry.
3042       // If Left.ParameterCount is greater than 0, then its parent submessage
3043       // might contain 1 or more entries and we want to break before this entry
3044       // if it contains at least 2 entries. We deal with this case later by
3045       // detecting and breaking before the next entry in the parent submessage.
3046       if (Left.ParameterCount == 0)
3047         return true;
3048       // However, if this submessage is the first entry in its parent
3049       // submessage, Left.ParameterCount might be 1 in some cases.
3050       // We deal with this case later by detecting an entry
3051       // following a closing paren of this submessage.
3052     }
3053 
3054     // If this is an entry immediately following a submessage, it will be
3055     // preceded by a closing paren of that submessage, like in:
3056     //     left---.  .---right
3057     //            v  v
3058     // sub: { ... } key: value
3059     // If there was a comment between `}` an `key` above, then `key` would be
3060     // put on a new line anyways.
3061     if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
3062       return true;
3063   }
3064 
3065   // Deal with lambda arguments in C++ - we want consistent line breaks whether
3066   // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
3067   // as aggressive line breaks are placed when the lambda is not the last arg.
3068   if ((Style.Language == FormatStyle::LK_Cpp ||
3069        Style.Language == FormatStyle::LK_ObjC) &&
3070       Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
3071       !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
3072     // Multiple lambdas in the same function call force line breaks.
3073     if (Left.BlockParameterCount > 1)
3074       return true;
3075 
3076     // A lambda followed by another arg forces a line break.
3077     if (!Left.Role)
3078       return false;
3079     auto Comma = Left.Role->lastComma();
3080     if (!Comma)
3081       return false;
3082     auto Next = Comma->getNextNonComment();
3083     if (!Next)
3084       return false;
3085     if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
3086       return true;
3087   }
3088 
3089   return false;
3090 }
3091 
3092 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
3093                                     const FormatToken &Right) {
3094   const FormatToken &Left = *Right.Previous;
3095 
3096   // Language-specific stuff.
3097   if (Style.Language == FormatStyle::LK_Java) {
3098     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3099                      Keywords.kw_implements))
3100       return false;
3101     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3102                       Keywords.kw_implements))
3103       return true;
3104   } else if (Style.Language == FormatStyle::LK_JavaScript) {
3105     const FormatToken *NonComment = Right.getPreviousNonComment();
3106     if (NonComment &&
3107         NonComment->isOneOf(
3108             tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
3109             tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
3110             tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
3111             Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
3112             Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
3113       return false; // Otherwise automatic semicolon insertion would trigger.
3114     if (Right.NestingLevel == 0 &&
3115         (Left.Tok.getIdentifierInfo() ||
3116          Left.isOneOf(tok::r_square, tok::r_paren)) &&
3117         Right.isOneOf(tok::l_square, tok::l_paren))
3118       return false; // Otherwise automatic semicolon insertion would trigger.
3119     if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
3120       return false;
3121     if (Left.is(TT_JsTypeColon))
3122       return true;
3123     // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
3124     if (Left.is(tok::exclaim) && Right.is(tok::colon))
3125       return false;
3126     // Look for is type annotations like:
3127     // function f(): a is B { ... }
3128     // Do not break before is in these cases.
3129     if (Right.is(Keywords.kw_is)) {
3130       const FormatToken* Next = Right.getNextNonComment();
3131       // If `is` is followed by a colon, it's likely that it's a dict key, so
3132       // ignore it for this check.
3133       // For example this is common in Polymer:
3134       // Polymer({
3135       //   is: 'name',
3136       //   ...
3137       // });
3138       if (!Next || !Next->is(tok::colon))
3139         return false;
3140     }
3141     if (Left.is(Keywords.kw_in))
3142       return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
3143     if (Right.is(Keywords.kw_in))
3144       return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
3145     if (Right.is(Keywords.kw_as))
3146       return false; // must not break before as in 'x as type' casts
3147     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
3148       // extends and infer can appear as keywords in conditional types:
3149       //   https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
3150       // do not break before them, as the expressions are subject to ASI.
3151       return false;
3152     }
3153     if (Left.is(Keywords.kw_as))
3154       return true;
3155     if (Left.is(TT_JsNonNullAssertion))
3156       return true;
3157     if (Left.is(Keywords.kw_declare) &&
3158         Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
3159                       Keywords.kw_function, tok::kw_class, tok::kw_enum,
3160                       Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
3161                       Keywords.kw_let, tok::kw_const))
3162       // See grammar for 'declare' statements at:
3163       // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
3164       return false;
3165     if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
3166         Right.isOneOf(tok::identifier, tok::string_literal))
3167       return false; // must not break in "module foo { ...}"
3168     if (Right.is(TT_TemplateString) && Right.closesScope())
3169       return false;
3170     if (Left.is(TT_TemplateString) && Left.opensScope())
3171       return true;
3172   }
3173 
3174   if (Left.is(tok::at))
3175     return false;
3176   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
3177     return false;
3178   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
3179     return !Right.is(tok::l_paren);
3180   if (Right.is(TT_PointerOrReference))
3181     return Line.IsMultiVariableDeclStmt ||
3182            (Style.PointerAlignment == FormatStyle::PAS_Right &&
3183             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
3184   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
3185       Right.is(tok::kw_operator))
3186     return true;
3187   if (Left.is(TT_PointerOrReference))
3188     return false;
3189   if (Right.isTrailingComment())
3190     // We rely on MustBreakBefore being set correctly here as we should not
3191     // change the "binding" behavior of a comment.
3192     // The first comment in a braced lists is always interpreted as belonging to
3193     // the first list element. Otherwise, it should be placed outside of the
3194     // list.
3195     return Left.BlockKind == BK_BracedInit ||
3196            (Left.is(TT_CtorInitializerColon) &&
3197             Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
3198   if (Left.is(tok::question) && Right.is(tok::colon))
3199     return false;
3200   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
3201     return Style.BreakBeforeTernaryOperators;
3202   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
3203     return !Style.BreakBeforeTernaryOperators;
3204   if (Left.is(TT_InheritanceColon))
3205     return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
3206   if (Right.is(TT_InheritanceColon))
3207     return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
3208   if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
3209       Left.isNot(TT_SelectorName))
3210     return true;
3211 
3212   if (Right.is(tok::colon) &&
3213       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
3214     return false;
3215   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
3216     if (Style.Language == FormatStyle::LK_Proto ||
3217         Style.Language == FormatStyle::LK_TextProto) {
3218       if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
3219         return false;
3220       // Prevent cases like:
3221       //
3222       // submessage:
3223       //     { key: valueeeeeeeeeeee }
3224       //
3225       // when the snippet does not fit into one line.
3226       // Prefer:
3227       //
3228       // submessage: {
3229       //   key: valueeeeeeeeeeee
3230       // }
3231       //
3232       // instead, even if it is longer by one line.
3233       //
3234       // Note that this allows allows the "{" to go over the column limit
3235       // when the column limit is just between ":" and "{", but that does
3236       // not happen too often and alternative formattings in this case are
3237       // not much better.
3238       //
3239       // The code covers the cases:
3240       //
3241       // submessage: { ... }
3242       // submessage: < ... >
3243       // repeated: [ ... ]
3244       if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
3245            Right.is(TT_DictLiteral)) ||
3246           Right.is(TT_ArrayInitializerLSquare))
3247         return false;
3248     }
3249     return true;
3250   }
3251   if (Right.is(tok::r_square) && Right.MatchingParen &&
3252       Right.MatchingParen->is(TT_ProtoExtensionLSquare))
3253     return false;
3254   if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
3255                                     Right.Next->is(TT_ObjCMethodExpr)))
3256     return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
3257   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
3258     return true;
3259   if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
3260     return true;
3261   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
3262                     TT_OverloadedOperator))
3263     return false;
3264   if (Left.is(TT_RangeBasedForLoopColon))
3265     return true;
3266   if (Right.is(TT_RangeBasedForLoopColon))
3267     return false;
3268   if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
3269     return true;
3270   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
3271       Left.is(tok::kw_operator))
3272     return false;
3273   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
3274       Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
3275     return false;
3276   if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
3277       !Style.Cpp11BracedListStyle)
3278     return false;
3279   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
3280     return false;
3281   if (Left.is(tok::l_paren) && Left.Previous &&
3282       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
3283     return false;
3284   if (Right.is(TT_ImplicitStringLiteral))
3285     return false;
3286 
3287   if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
3288     return false;
3289   if (Right.is(tok::r_square) && Right.MatchingParen &&
3290       Right.MatchingParen->is(TT_LambdaLSquare))
3291     return false;
3292 
3293   // We only break before r_brace if there was a corresponding break before
3294   // the l_brace, which is tracked by BreakBeforeClosingBrace.
3295   if (Right.is(tok::r_brace))
3296     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
3297 
3298   // Allow breaking after a trailing annotation, e.g. after a method
3299   // declaration.
3300   if (Left.is(TT_TrailingAnnotation))
3301     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
3302                           tok::less, tok::coloncolon);
3303 
3304   if (Right.is(tok::kw___attribute) ||
3305       (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
3306     return true;
3307 
3308   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
3309     return true;
3310 
3311   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
3312     return true;
3313 
3314   if (Left.is(TT_CtorInitializerColon))
3315     return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
3316   if (Right.is(TT_CtorInitializerColon))
3317     return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
3318   if (Left.is(TT_CtorInitializerComma) &&
3319       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3320     return false;
3321   if (Right.is(TT_CtorInitializerComma) &&
3322       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3323     return true;
3324   if (Left.is(TT_InheritanceComma) &&
3325       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3326     return false;
3327   if (Right.is(TT_InheritanceComma) &&
3328       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3329     return true;
3330   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
3331       (Left.is(tok::less) && Right.is(tok::less)))
3332     return false;
3333   if (Right.is(TT_BinaryOperator) &&
3334       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
3335       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
3336        Right.getPrecedence() != prec::Assignment))
3337     return true;
3338   if (Left.is(TT_ArrayInitializerLSquare))
3339     return true;
3340   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
3341     return true;
3342   if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
3343       !Left.isOneOf(tok::arrowstar, tok::lessless) &&
3344       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
3345       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
3346        Left.getPrecedence() == prec::Assignment))
3347     return true;
3348   if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
3349       (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
3350     return false;
3351   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
3352                       tok::kw_class, tok::kw_struct, tok::comment) ||
3353          Right.isMemberAccess() ||
3354          Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
3355                        tok::colon, tok::l_square, tok::at) ||
3356          (Left.is(tok::r_paren) &&
3357           Right.isOneOf(tok::identifier, tok::kw_const)) ||
3358          (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
3359          (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
3360 }
3361 
3362 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
3363   llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
3364   const FormatToken *Tok = Line.First;
3365   while (Tok) {
3366     llvm::errs() << " M=" << Tok->MustBreakBefore
3367                  << " C=" << Tok->CanBreakBefore
3368                  << " T=" << getTokenTypeName(Tok->Type)
3369                  << " S=" << Tok->SpacesRequiredBefore
3370                  << " B=" << Tok->BlockParameterCount
3371                  << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
3372                  << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
3373                  << " PPK=" << Tok->PackingKind << " FakeLParens=";
3374     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
3375       llvm::errs() << Tok->FakeLParens[i] << "/";
3376     llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
3377     llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
3378     llvm::errs() << " Text='" << Tok->TokenText << "'\n";
3379     if (!Tok->Next)
3380       assert(Tok == Line.Last);
3381     Tok = Tok->Next;
3382   }
3383   llvm::errs() << "----\n";
3384 }
3385 
3386 } // namespace format
3387 } // namespace clang
3388