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 "FormatToken.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Basic/TokenKinds.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Support/Debug.h"
21 
22 #define DEBUG_TYPE "format-token-annotator"
23 
24 namespace clang {
25 namespace format {
26 
27 namespace {
28 
29 /// Returns \c true if the line starts with a token that can start a statement
30 /// with an initializer.
31 static bool startsWithInitStatement(const AnnotatedLine &Line) {
32   return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) ||
33          Line.startsWith(tok::kw_switch);
34 }
35 
36 /// Returns \c true if the token can be used as an identifier in
37 /// an Objective-C \c \@selector, \c false otherwise.
38 ///
39 /// Because getFormattingLangOpts() always lexes source code as
40 /// Objective-C++, C++ keywords like \c new and \c delete are
41 /// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
42 ///
43 /// For Objective-C and Objective-C++, both identifiers and keywords
44 /// are valid inside @selector(...) (or a macro which
45 /// invokes @selector(...)). So, we allow treat any identifier or
46 /// keyword as a potential Objective-C selector component.
47 static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
48   return Tok.Tok.getIdentifierInfo() != nullptr;
49 }
50 
51 /// With `Left` being '(', check if we're at either `[...](` or
52 /// `[...]<...>(`, where the [ opens a lambda capture list.
53 static bool isLambdaParameterList(const FormatToken *Left) {
54   // Skip <...> if present.
55   if (Left->Previous && Left->Previous->is(tok::greater) &&
56       Left->Previous->MatchingParen &&
57       Left->Previous->MatchingParen->is(TT_TemplateOpener))
58     Left = Left->Previous->MatchingParen;
59 
60   // Check for `[...]`.
61   return Left->Previous && Left->Previous->is(tok::r_square) &&
62          Left->Previous->MatchingParen &&
63          Left->Previous->MatchingParen->is(TT_LambdaLSquare);
64 }
65 
66 /// Returns \c true if the token is followed by a boolean condition, \c false
67 /// otherwise.
68 static bool isKeywordWithCondition(const FormatToken &Tok) {
69   return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
70                      tok::kw_constexpr, tok::kw_catch);
71 }
72 
73 /// A parser that gathers additional information about tokens.
74 ///
75 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
76 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
77 /// into template parameter lists.
78 class AnnotatingParser {
79 public:
80   AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
81                    const AdditionalKeywords &Keywords)
82       : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
83         Keywords(Keywords) {
84     Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
85     resetTokenMetadata();
86   }
87 
88 private:
89   bool parseAngle() {
90     if (!CurrentToken || !CurrentToken->Previous)
91       return false;
92     if (NonTemplateLess.count(CurrentToken->Previous))
93       return false;
94 
95     const FormatToken &Previous = *CurrentToken->Previous; // The '<'.
96     if (Previous.Previous) {
97       if (Previous.Previous->Tok.isLiteral())
98         return false;
99       if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
100           (!Previous.Previous->MatchingParen ||
101            !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
102         return false;
103     }
104 
105     FormatToken *Left = CurrentToken->Previous;
106     Left->ParentBracket = Contexts.back().ContextKind;
107     ScopedContextCreator ContextCreator(*this, tok::less, 12);
108 
109     // If this angle is in the context of an expression, we need to be more
110     // hesitant to detect it as opening template parameters.
111     bool InExprContext = Contexts.back().IsExpression;
112 
113     Contexts.back().IsExpression = false;
114     // If there's a template keyword before the opening angle bracket, this is a
115     // template parameter, not an argument.
116     Contexts.back().InTemplateArgument =
117         Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
118 
119     if (Style.Language == FormatStyle::LK_Java &&
120         CurrentToken->is(tok::question))
121       next();
122 
123     while (CurrentToken) {
124       if (CurrentToken->is(tok::greater)) {
125         // Try to do a better job at looking for ">>" within the condition of
126         // a statement. Conservatively insert spaces between consecutive ">"
127         // tokens to prevent splitting right bitshift operators and potentially
128         // altering program semantics. This check is overly conservative and
129         // will prevent spaces from being inserted in select nested template
130         // parameter cases, but should not alter program semantics.
131         if (CurrentToken->Next && CurrentToken->Next->is(tok::greater) &&
132             Left->ParentBracket != tok::less &&
133             (isKeywordWithCondition(*Line.First) ||
134              CurrentToken->getStartOfNonWhitespace() ==
135                  CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset(
136                      -1)))
137           return false;
138         Left->MatchingParen = CurrentToken;
139         CurrentToken->MatchingParen = Left;
140         // In TT_Proto, we must distignuish between:
141         //   map<key, value>
142         //   msg < item: data >
143         //   msg: < item: data >
144         // In TT_TextProto, map<key, value> does not occur.
145         if (Style.Language == FormatStyle::LK_TextProto ||
146             (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
147              Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
148           CurrentToken->setType(TT_DictLiteral);
149         else
150           CurrentToken->setType(TT_TemplateCloser);
151         next();
152         return true;
153       }
154       if (CurrentToken->is(tok::question) &&
155           Style.Language == FormatStyle::LK_Java) {
156         next();
157         continue;
158       }
159       if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
160           (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
161            !Style.isCSharp() && Style.Language != FormatStyle::LK_Proto &&
162            Style.Language != FormatStyle::LK_TextProto))
163         return false;
164       // If a && or || is found and interpreted as a binary operator, this set
165       // of angles is likely part of something like "a < b && c > d". If the
166       // angles are inside an expression, the ||/&& might also be a binary
167       // operator that was misinterpreted because we are parsing template
168       // parameters.
169       // FIXME: This is getting out of hand, write a decent parser.
170       if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
171           CurrentToken->Previous->is(TT_BinaryOperator) &&
172           Contexts[Contexts.size() - 2].IsExpression &&
173           !Line.startsWith(tok::kw_template))
174         return false;
175       updateParameterCount(Left, CurrentToken);
176       if (Style.Language == FormatStyle::LK_Proto) {
177         if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
178           if (CurrentToken->is(tok::colon) ||
179               (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
180                Previous->isNot(tok::colon)))
181             Previous->setType(TT_SelectorName);
182         }
183       }
184       if (!consumeToken())
185         return false;
186     }
187     return false;
188   }
189 
190   bool parseUntouchableParens() {
191     while (CurrentToken) {
192       CurrentToken->Finalized = true;
193       switch (CurrentToken->Tok.getKind()) {
194       case tok::l_paren:
195         next();
196         if (!parseUntouchableParens())
197           return false;
198         continue;
199       case tok::r_paren:
200         next();
201         return true;
202       default:
203         // no-op
204         break;
205       }
206       next();
207     }
208     return false;
209   }
210 
211   bool parseParens(bool LookForDecls = false) {
212     if (!CurrentToken)
213       return false;
214     FormatToken *Left = CurrentToken->Previous;
215     assert(Left && "Unknown previous token");
216     FormatToken *PrevNonComment = Left->getPreviousNonComment();
217     Left->ParentBracket = Contexts.back().ContextKind;
218     ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
219 
220     // FIXME: This is a bit of a hack. Do better.
221     Contexts.back().ColonIsForRangeExpr =
222         Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
223 
224     if (Left->Previous && Left->Previous->is(TT_UntouchableMacroFunc)) {
225       Left->Finalized = true;
226       return parseUntouchableParens();
227     }
228 
229     bool StartsObjCMethodExpr = false;
230     if (FormatToken *MaybeSel = Left->Previous) {
231       // @selector( starts a selector.
232       if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
233           MaybeSel->Previous->is(tok::at))
234         StartsObjCMethodExpr = true;
235     }
236 
237     if (Left->is(TT_OverloadedOperatorLParen)) {
238       // Find the previous kw_operator token.
239       FormatToken *Prev = Left;
240       while (!Prev->is(tok::kw_operator)) {
241         Prev = Prev->Previous;
242         assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
243       }
244 
245       // If faced with "a.operator*(argument)" or "a->operator*(argument)",
246       // i.e. the operator is called as a member function,
247       // then the argument must be an expression.
248       bool OperatorCalledAsMemberFunction =
249           Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow);
250       Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
251     } else if (Style.isJavaScript() &&
252                (Line.startsWith(Keywords.kw_type, tok::identifier) ||
253                 Line.startsWith(tok::kw_export, Keywords.kw_type,
254                                 tok::identifier))) {
255       // type X = (...);
256       // export type X = (...);
257       Contexts.back().IsExpression = false;
258     } else if (Left->Previous &&
259                (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_while,
260                                         tok::l_paren, tok::comma) ||
261                 Left->Previous->isIf() ||
262                 Left->Previous->is(TT_BinaryOperator))) {
263       // static_assert, if and while usually contain expressions.
264       Contexts.back().IsExpression = true;
265     } else if (Style.isJavaScript() && Left->Previous &&
266                (Left->Previous->is(Keywords.kw_function) ||
267                 (Left->Previous->endsSequence(tok::identifier,
268                                               Keywords.kw_function)))) {
269       // function(...) or function f(...)
270       Contexts.back().IsExpression = false;
271     } else if (Style.isJavaScript() && Left->Previous &&
272                Left->Previous->is(TT_JsTypeColon)) {
273       // let x: (SomeType);
274       Contexts.back().IsExpression = false;
275     } else if (isLambdaParameterList(Left)) {
276       // This is a parameter list of a lambda expression.
277       Contexts.back().IsExpression = false;
278     } else if (Line.InPPDirective &&
279                (!Left->Previous || !Left->Previous->is(tok::identifier))) {
280       Contexts.back().IsExpression = true;
281     } else if (Contexts[Contexts.size() - 2].CaretFound) {
282       // This is the parameter list of an ObjC block.
283       Contexts.back().IsExpression = false;
284     } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
285       // The first argument to a foreach macro is a declaration.
286       Contexts.back().IsForEachMacro = true;
287       Contexts.back().IsExpression = false;
288     } else if (Left->Previous && Left->Previous->MatchingParen &&
289                Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
290       Contexts.back().IsExpression = false;
291     } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
292       bool IsForOrCatch =
293           Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
294       Contexts.back().IsExpression = !IsForOrCatch;
295     }
296 
297     // Infer the role of the l_paren based on the previous token if we haven't
298     // detected one one yet.
299     if (PrevNonComment && Left->is(TT_Unknown)) {
300       if (PrevNonComment->is(tok::kw___attribute)) {
301         Left->setType(TT_AttributeParen);
302       } else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
303                                          tok::kw_typeof, tok::kw__Atomic,
304                                          tok::kw___underlying_type)) {
305         Left->setType(TT_TypeDeclarationParen);
306         // decltype() and typeof() usually contain expressions.
307         if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
308           Contexts.back().IsExpression = true;
309       }
310     }
311 
312     if (StartsObjCMethodExpr) {
313       Contexts.back().ColonIsObjCMethodExpr = true;
314       Left->setType(TT_ObjCMethodExpr);
315     }
316 
317     // MightBeFunctionType and ProbablyFunctionType are used for
318     // function pointer and reference types as well as Objective-C
319     // block types:
320     //
321     // void (*FunctionPointer)(void);
322     // void (&FunctionReference)(void);
323     // void (&&FunctionReference)(void);
324     // void (^ObjCBlock)(void);
325     bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
326     bool ProbablyFunctionType =
327         CurrentToken->isOneOf(tok::star, tok::amp, tok::ampamp, tok::caret);
328     bool HasMultipleLines = false;
329     bool HasMultipleParametersOnALine = false;
330     bool MightBeObjCForRangeLoop =
331         Left->Previous && Left->Previous->is(tok::kw_for);
332     FormatToken *PossibleObjCForInToken = nullptr;
333     while (CurrentToken) {
334       // LookForDecls is set when "if (" has been seen. Check for
335       // 'identifier' '*' 'identifier' followed by not '=' -- this
336       // '*' has to be a binary operator but determineStarAmpUsage() will
337       // categorize it as an unary operator, so set the right type here.
338       if (LookForDecls && CurrentToken->Next) {
339         FormatToken *Prev = CurrentToken->getPreviousNonComment();
340         if (Prev) {
341           FormatToken *PrevPrev = Prev->getPreviousNonComment();
342           FormatToken *Next = CurrentToken->Next;
343           if (PrevPrev && PrevPrev->is(tok::identifier) &&
344               Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
345               CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
346             Prev->setType(TT_BinaryOperator);
347             LookForDecls = false;
348           }
349         }
350       }
351 
352       if (CurrentToken->Previous->is(TT_PointerOrReference) &&
353           CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
354                                                     tok::coloncolon))
355         ProbablyFunctionType = true;
356       if (CurrentToken->is(tok::comma))
357         MightBeFunctionType = false;
358       if (CurrentToken->Previous->is(TT_BinaryOperator))
359         Contexts.back().IsExpression = true;
360       if (CurrentToken->is(tok::r_paren)) {
361         if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
362             (CurrentToken->Next->is(tok::l_paren) ||
363              (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
364           Left->setType(Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
365                                                    : TT_FunctionTypeLParen);
366         Left->MatchingParen = CurrentToken;
367         CurrentToken->MatchingParen = Left;
368 
369         if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
370             Left->Previous && Left->Previous->is(tok::l_paren)) {
371           // Detect the case where macros are used to generate lambdas or
372           // function bodies, e.g.:
373           //   auto my_lambda = MACRO((Type *type, int i) { .. body .. });
374           for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next)
375             if (Tok->is(TT_BinaryOperator) &&
376                 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
377               Tok->setType(TT_PointerOrReference);
378         }
379 
380         if (StartsObjCMethodExpr) {
381           CurrentToken->setType(TT_ObjCMethodExpr);
382           if (Contexts.back().FirstObjCSelectorName) {
383             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
384                 Contexts.back().LongestObjCSelectorName;
385           }
386         }
387 
388         if (Left->is(TT_AttributeParen))
389           CurrentToken->setType(TT_AttributeParen);
390         if (Left->is(TT_TypeDeclarationParen))
391           CurrentToken->setType(TT_TypeDeclarationParen);
392         if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
393           CurrentToken->setType(TT_JavaAnnotation);
394         if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
395           CurrentToken->setType(TT_LeadingJavaAnnotation);
396         if (Left->Previous && Left->Previous->is(TT_AttributeSquare))
397           CurrentToken->setType(TT_AttributeSquare);
398 
399         if (!HasMultipleLines)
400           Left->setPackingKind(PPK_Inconclusive);
401         else if (HasMultipleParametersOnALine)
402           Left->setPackingKind(PPK_BinPacked);
403         else
404           Left->setPackingKind(PPK_OnePerLine);
405 
406         next();
407         return true;
408       }
409       if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
410         return false;
411 
412       if (CurrentToken->is(tok::l_brace))
413         Left->setType(TT_Unknown); // Not TT_ObjCBlockLParen
414       if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
415           !CurrentToken->Next->HasUnescapedNewline &&
416           !CurrentToken->Next->isTrailingComment())
417         HasMultipleParametersOnALine = true;
418       bool ProbablyFunctionTypeLParen =
419           (CurrentToken->is(tok::l_paren) && CurrentToken->Next &&
420            CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret));
421       if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
422            CurrentToken->Previous->isSimpleTypeSpecifier()) &&
423           !(CurrentToken->is(tok::l_brace) ||
424             (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen)))
425         Contexts.back().IsExpression = false;
426       if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
427         MightBeObjCForRangeLoop = false;
428         if (PossibleObjCForInToken) {
429           PossibleObjCForInToken->setType(TT_Unknown);
430           PossibleObjCForInToken = nullptr;
431         }
432       }
433       if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
434         PossibleObjCForInToken = CurrentToken;
435         PossibleObjCForInToken->setType(TT_ObjCForIn);
436       }
437       // When we discover a 'new', we set CanBeExpression to 'false' in order to
438       // parse the type correctly. Reset that after a comma.
439       if (CurrentToken->is(tok::comma))
440         Contexts.back().CanBeExpression = true;
441 
442       FormatToken *Tok = CurrentToken;
443       if (!consumeToken())
444         return false;
445       updateParameterCount(Left, Tok);
446       if (CurrentToken && CurrentToken->HasUnescapedNewline)
447         HasMultipleLines = true;
448     }
449     return false;
450   }
451 
452   bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
453     if (!Style.isCSharp())
454       return false;
455 
456     // `identifier[i]` is not an attribute.
457     if (Tok.Previous && Tok.Previous->is(tok::identifier))
458       return false;
459 
460     // Chains of [] in `identifier[i][j][k]` are not attributes.
461     if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
462       auto *MatchingParen = Tok.Previous->MatchingParen;
463       if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare))
464         return false;
465     }
466 
467     const FormatToken *AttrTok = Tok.Next;
468     if (!AttrTok)
469       return false;
470 
471     // Just an empty declaration e.g. string [].
472     if (AttrTok->is(tok::r_square))
473       return false;
474 
475     // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
476     while (AttrTok && AttrTok->isNot(tok::r_square))
477       AttrTok = AttrTok->Next;
478 
479     if (!AttrTok)
480       return false;
481 
482     // Allow an attribute to be the only content of a file.
483     AttrTok = AttrTok->Next;
484     if (!AttrTok)
485       return true;
486 
487     // Limit this to being an access modifier that follows.
488     if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
489                          tok::comment, tok::kw_class, tok::kw_static,
490                          tok::l_square, Keywords.kw_internal))
491       return true;
492 
493     // incase its a [XXX] retval func(....
494     if (AttrTok->Next &&
495         AttrTok->Next->startsSequence(tok::identifier, tok::l_paren))
496       return true;
497 
498     return false;
499   }
500 
501   bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
502     if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
503       return false;
504     // The first square bracket is part of an ObjC array literal
505     if (Tok.Previous && Tok.Previous->is(tok::at))
506       return false;
507     const FormatToken *AttrTok = Tok.Next->Next;
508     if (!AttrTok)
509       return false;
510     // C++17 '[[using ns: foo, bar(baz, blech)]]'
511     // We assume nobody will name an ObjC variable 'using'.
512     if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
513       return true;
514     if (AttrTok->isNot(tok::identifier))
515       return false;
516     while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
517       // ObjC message send. We assume nobody will use : in a C++11 attribute
518       // specifier parameter, although this is technically valid:
519       // [[foo(:)]].
520       if (AttrTok->is(tok::colon) ||
521           AttrTok->startsSequence(tok::identifier, tok::identifier) ||
522           AttrTok->startsSequence(tok::r_paren, tok::identifier))
523         return false;
524       if (AttrTok->is(tok::ellipsis))
525         return true;
526       AttrTok = AttrTok->Next;
527     }
528     return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
529   }
530 
531   bool parseSquare() {
532     if (!CurrentToken)
533       return false;
534 
535     // A '[' could be an index subscript (after an identifier or after
536     // ')' or ']'), it could be the start of an Objective-C method
537     // expression, it could the start of an Objective-C array literal,
538     // or it could be a C++ attribute specifier [[foo::bar]].
539     FormatToken *Left = CurrentToken->Previous;
540     Left->ParentBracket = Contexts.back().ContextKind;
541     FormatToken *Parent = Left->getPreviousNonComment();
542 
543     // Cases where '>' is followed by '['.
544     // In C++, this can happen either in array of templates (foo<int>[10])
545     // or when array is a nested template type (unique_ptr<type1<type2>[]>).
546     bool CppArrayTemplates =
547         Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
548         (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
549          Contexts.back().InTemplateArgument);
550 
551     bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
552                                      Contexts.back().InCpp11AttributeSpecifier;
553 
554     // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
555     bool IsCSharpAttributeSpecifier =
556         isCSharpAttributeSpecifier(*Left) ||
557         Contexts.back().InCSharpAttributeSpecifier;
558 
559     bool InsideInlineASM = Line.startsWith(tok::kw_asm);
560     bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
561     bool StartsObjCMethodExpr =
562         !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
563         Style.isCpp() && !IsCpp11AttributeSpecifier &&
564         !IsCSharpAttributeSpecifier && Contexts.back().CanBeExpression &&
565         Left->isNot(TT_LambdaLSquare) &&
566         !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
567         (!Parent ||
568          Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
569                          tok::kw_return, tok::kw_throw) ||
570          Parent->isUnaryOperator() ||
571          // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
572          Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
573          (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
574           prec::Unknown));
575     bool ColonFound = false;
576 
577     unsigned BindingIncrease = 1;
578     if (IsCppStructuredBinding) {
579       Left->setType(TT_StructuredBindingLSquare);
580     } else if (Left->is(TT_Unknown)) {
581       if (StartsObjCMethodExpr) {
582         Left->setType(TT_ObjCMethodExpr);
583       } else if (InsideInlineASM) {
584         Left->setType(TT_InlineASMSymbolicNameLSquare);
585       } else if (IsCpp11AttributeSpecifier) {
586         Left->setType(TT_AttributeSquare);
587       } else if (Style.isJavaScript() && Parent &&
588                  Contexts.back().ContextKind == tok::l_brace &&
589                  Parent->isOneOf(tok::l_brace, tok::comma)) {
590         Left->setType(TT_JsComputedPropertyName);
591       } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
592                  Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
593         Left->setType(TT_DesignatedInitializerLSquare);
594       } else if (IsCSharpAttributeSpecifier) {
595         Left->setType(TT_AttributeSquare);
596       } else if (CurrentToken->is(tok::r_square) && Parent &&
597                  Parent->is(TT_TemplateCloser)) {
598         Left->setType(TT_ArraySubscriptLSquare);
599       } else if (Style.Language == FormatStyle::LK_Proto ||
600                  Style.Language == FormatStyle::LK_TextProto) {
601         // Square braces in LK_Proto can either be message field attributes:
602         //
603         // optional Aaa aaa = 1 [
604         //   (aaa) = aaa
605         // ];
606         //
607         // extensions 123 [
608         //   (aaa) = aaa
609         // ];
610         //
611         // or text proto extensions (in options):
612         //
613         // option (Aaa.options) = {
614         //   [type.type/type] {
615         //     key: value
616         //   }
617         // }
618         //
619         // or repeated fields (in options):
620         //
621         // option (Aaa.options) = {
622         //   keys: [ 1, 2, 3 ]
623         // }
624         //
625         // In the first and the third case we want to spread the contents inside
626         // the square braces; in the second we want to keep them inline.
627         Left->setType(TT_ArrayInitializerLSquare);
628         if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
629                                 tok::equal) &&
630             !Left->endsSequence(tok::l_square, tok::numeric_constant,
631                                 tok::identifier) &&
632             !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
633           Left->setType(TT_ProtoExtensionLSquare);
634           BindingIncrease = 10;
635         }
636       } else if (!CppArrayTemplates && Parent &&
637                  Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
638                                  tok::comma, tok::l_paren, tok::l_square,
639                                  tok::question, tok::colon, tok::kw_return,
640                                  // Should only be relevant to JavaScript:
641                                  tok::kw_default)) {
642         Left->setType(TT_ArrayInitializerLSquare);
643       } else {
644         BindingIncrease = 10;
645         Left->setType(TT_ArraySubscriptLSquare);
646       }
647     }
648 
649     ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
650     Contexts.back().IsExpression = true;
651     if (Style.isJavaScript() && Parent && Parent->is(TT_JsTypeColon))
652       Contexts.back().IsExpression = false;
653 
654     Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
655     Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
656     Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier;
657 
658     while (CurrentToken) {
659       if (CurrentToken->is(tok::r_square)) {
660         if (IsCpp11AttributeSpecifier)
661           CurrentToken->setType(TT_AttributeSquare);
662         if (IsCSharpAttributeSpecifier)
663           CurrentToken->setType(TT_AttributeSquare);
664         else if (((CurrentToken->Next &&
665                    CurrentToken->Next->is(tok::l_paren)) ||
666                   (CurrentToken->Previous &&
667                    CurrentToken->Previous->Previous == Left)) &&
668                  Left->is(TT_ObjCMethodExpr)) {
669           // An ObjC method call is rarely followed by an open parenthesis. It
670           // also can't be composed of just one token, unless it's a macro that
671           // will be expanded to more tokens.
672           // FIXME: Do we incorrectly label ":" with this?
673           StartsObjCMethodExpr = false;
674           Left->setType(TT_Unknown);
675         }
676         if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
677           CurrentToken->setType(TT_ObjCMethodExpr);
678           // If we haven't seen a colon yet, make sure the last identifier
679           // before the r_square is tagged as a selector name component.
680           if (!ColonFound && CurrentToken->Previous &&
681               CurrentToken->Previous->is(TT_Unknown) &&
682               canBeObjCSelectorComponent(*CurrentToken->Previous))
683             CurrentToken->Previous->setType(TT_SelectorName);
684           // determineStarAmpUsage() thinks that '*' '[' is allocating an
685           // array of pointers, but if '[' starts a selector then '*' is a
686           // binary operator.
687           if (Parent && Parent->is(TT_PointerOrReference))
688             Parent->setType(TT_BinaryOperator);
689         }
690         // An arrow after an ObjC method expression is not a lambda arrow.
691         if (CurrentToken->getType() == TT_ObjCMethodExpr &&
692             CurrentToken->Next && CurrentToken->Next->is(TT_LambdaArrow))
693           CurrentToken->Next->setType(TT_Unknown);
694         Left->MatchingParen = CurrentToken;
695         CurrentToken->MatchingParen = Left;
696         // FirstObjCSelectorName is set when a colon is found. This does
697         // not work, however, when the method has no parameters.
698         // Here, we set FirstObjCSelectorName when the end of the method call is
699         // reached, in case it was not set already.
700         if (!Contexts.back().FirstObjCSelectorName) {
701           FormatToken *Previous = CurrentToken->getPreviousNonComment();
702           if (Previous && Previous->is(TT_SelectorName)) {
703             Previous->ObjCSelectorNameParts = 1;
704             Contexts.back().FirstObjCSelectorName = Previous;
705           }
706         } else {
707           Left->ParameterCount =
708               Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
709         }
710         if (Contexts.back().FirstObjCSelectorName) {
711           Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
712               Contexts.back().LongestObjCSelectorName;
713           if (Left->BlockParameterCount > 1)
714             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
715         }
716         next();
717         return true;
718       }
719       if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
720         return false;
721       if (CurrentToken->is(tok::colon)) {
722         if (IsCpp11AttributeSpecifier &&
723             CurrentToken->endsSequence(tok::colon, tok::identifier,
724                                        tok::kw_using)) {
725           // Remember that this is a [[using ns: foo]] C++ attribute, so we
726           // don't add a space before the colon (unlike other colons).
727           CurrentToken->setType(TT_AttributeColon);
728         } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
729                                  TT_DesignatedInitializerLSquare)) {
730           Left->setType(TT_ObjCMethodExpr);
731           StartsObjCMethodExpr = true;
732           Contexts.back().ColonIsObjCMethodExpr = true;
733           if (Parent && Parent->is(tok::r_paren))
734             // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
735             Parent->setType(TT_CastRParen);
736         }
737         ColonFound = true;
738       }
739       if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
740           !ColonFound)
741         Left->setType(TT_ArrayInitializerLSquare);
742       FormatToken *Tok = CurrentToken;
743       if (!consumeToken())
744         return false;
745       updateParameterCount(Left, Tok);
746     }
747     return false;
748   }
749 
750   bool couldBeInStructArrayInitializer() const {
751     if (Contexts.size() < 2)
752       return false;
753     // We want to back up no more then 2 context levels i.e.
754     // . { { <-
755     const auto End = std::next(Contexts.rbegin(), 2);
756     auto Last = Contexts.rbegin();
757     unsigned Depth = 0;
758     for (; Last != End; ++Last)
759       if (Last->ContextKind == tok::l_brace)
760         ++Depth;
761     return Depth == 2 && Last->ContextKind != tok::l_brace;
762   }
763 
764   bool parseBrace() {
765     if (CurrentToken) {
766       FormatToken *Left = CurrentToken->Previous;
767       Left->ParentBracket = Contexts.back().ContextKind;
768 
769       if (Contexts.back().CaretFound)
770         Left->setType(TT_ObjCBlockLBrace);
771       Contexts.back().CaretFound = false;
772 
773       ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
774       Contexts.back().ColonIsDictLiteral = true;
775       if (Left->is(BK_BracedInit))
776         Contexts.back().IsExpression = true;
777       if (Style.isJavaScript() && Left->Previous &&
778           Left->Previous->is(TT_JsTypeColon))
779         Contexts.back().IsExpression = false;
780 
781       unsigned CommaCount = 0;
782       while (CurrentToken) {
783         if (CurrentToken->is(tok::r_brace)) {
784           assert(Left->Optional == CurrentToken->Optional);
785           Left->MatchingParen = CurrentToken;
786           CurrentToken->MatchingParen = Left;
787           if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
788             if (Left->ParentBracket == tok::l_brace &&
789                 couldBeInStructArrayInitializer() && CommaCount > 0)
790               Contexts.back().InStructArrayInitializer = true;
791           }
792           next();
793           return true;
794         }
795         if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
796           return false;
797         updateParameterCount(Left, CurrentToken);
798         if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
799           FormatToken *Previous = CurrentToken->getPreviousNonComment();
800           if (Previous->is(TT_JsTypeOptionalQuestion))
801             Previous = Previous->getPreviousNonComment();
802           if ((CurrentToken->is(tok::colon) &&
803                (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
804               Style.Language == FormatStyle::LK_Proto ||
805               Style.Language == FormatStyle::LK_TextProto) {
806             Left->setType(TT_DictLiteral);
807             if (Previous->Tok.getIdentifierInfo() ||
808                 Previous->is(tok::string_literal))
809               Previous->setType(TT_SelectorName);
810           }
811           if (CurrentToken->is(tok::colon) || Style.isJavaScript())
812             Left->setType(TT_DictLiteral);
813         }
814         if (CurrentToken->is(tok::comma)) {
815           if (Style.isJavaScript())
816             Left->setType(TT_DictLiteral);
817           ++CommaCount;
818         }
819         if (!consumeToken())
820           return false;
821       }
822     }
823     return true;
824   }
825 
826   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
827     // For ObjC methods, the number of parameters is calculated differently as
828     // method declarations have a different structure (the parameters are not
829     // inside a bracket scope).
830     if (Current->is(tok::l_brace) && Current->is(BK_Block))
831       ++Left->BlockParameterCount;
832     if (Current->is(tok::comma)) {
833       ++Left->ParameterCount;
834       if (!Left->Role)
835         Left->Role.reset(new CommaSeparatedList(Style));
836       Left->Role->CommaFound(Current);
837     } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
838       Left->ParameterCount = 1;
839     }
840   }
841 
842   bool parseConditional() {
843     while (CurrentToken) {
844       if (CurrentToken->is(tok::colon)) {
845         CurrentToken->setType(TT_ConditionalExpr);
846         next();
847         return true;
848       }
849       if (!consumeToken())
850         return false;
851     }
852     return false;
853   }
854 
855   bool parseTemplateDeclaration() {
856     if (CurrentToken && CurrentToken->is(tok::less)) {
857       CurrentToken->setType(TT_TemplateOpener);
858       next();
859       if (!parseAngle())
860         return false;
861       if (CurrentToken)
862         CurrentToken->Previous->ClosesTemplateDeclaration = true;
863       return true;
864     }
865     return false;
866   }
867 
868   bool consumeToken() {
869     FormatToken *Tok = CurrentToken;
870     next();
871     switch (Tok->Tok.getKind()) {
872     case tok::plus:
873     case tok::minus:
874       if (!Tok->Previous && Line.MustBeDeclaration)
875         Tok->setType(TT_ObjCMethodSpecifier);
876       break;
877     case tok::colon:
878       if (!Tok->Previous)
879         return false;
880       // Colons from ?: are handled in parseConditional().
881       if (Style.isJavaScript()) {
882         if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
883             (Contexts.size() == 1 &&               // switch/case labels
884              !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
885             Contexts.back().ContextKind == tok::l_paren ||  // function params
886             Contexts.back().ContextKind == tok::l_square || // array type
887             (!Contexts.back().IsExpression &&
888              Contexts.back().ContextKind == tok::l_brace) || // object type
889             (Contexts.size() == 1 &&
890              Line.MustBeDeclaration)) { // method/property declaration
891           Contexts.back().IsExpression = false;
892           Tok->setType(TT_JsTypeColon);
893           break;
894         }
895       } else if (Style.isCSharp()) {
896         if (Contexts.back().InCSharpAttributeSpecifier) {
897           Tok->setType(TT_AttributeColon);
898           break;
899         }
900         if (Contexts.back().ContextKind == tok::l_paren) {
901           Tok->setType(TT_CSharpNamedArgumentColon);
902           break;
903         }
904       }
905       if (Line.First->isOneOf(Keywords.kw_module, Keywords.kw_import) ||
906           Line.First->startsSequence(tok::kw_export, Keywords.kw_module) ||
907           Line.First->startsSequence(tok::kw_export, Keywords.kw_import)) {
908         Tok->setType(TT_ModulePartitionColon);
909       } else if (Contexts.back().ColonIsDictLiteral ||
910                  Style.Language == FormatStyle::LK_Proto ||
911                  Style.Language == FormatStyle::LK_TextProto) {
912         Tok->setType(TT_DictLiteral);
913         if (Style.Language == FormatStyle::LK_TextProto) {
914           if (FormatToken *Previous = Tok->getPreviousNonComment())
915             Previous->setType(TT_SelectorName);
916         }
917       } else if (Contexts.back().ColonIsObjCMethodExpr ||
918                  Line.startsWith(TT_ObjCMethodSpecifier)) {
919         Tok->setType(TT_ObjCMethodExpr);
920         const FormatToken *BeforePrevious = Tok->Previous->Previous;
921         // Ensure we tag all identifiers in method declarations as
922         // TT_SelectorName.
923         bool UnknownIdentifierInMethodDeclaration =
924             Line.startsWith(TT_ObjCMethodSpecifier) &&
925             Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
926         if (!BeforePrevious ||
927             // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
928             !(BeforePrevious->is(TT_CastRParen) ||
929               (BeforePrevious->is(TT_ObjCMethodExpr) &&
930                BeforePrevious->is(tok::colon))) ||
931             BeforePrevious->is(tok::r_square) ||
932             Contexts.back().LongestObjCSelectorName == 0 ||
933             UnknownIdentifierInMethodDeclaration) {
934           Tok->Previous->setType(TT_SelectorName);
935           if (!Contexts.back().FirstObjCSelectorName)
936             Contexts.back().FirstObjCSelectorName = Tok->Previous;
937           else if (Tok->Previous->ColumnWidth >
938                    Contexts.back().LongestObjCSelectorName)
939             Contexts.back().LongestObjCSelectorName =
940                 Tok->Previous->ColumnWidth;
941           Tok->Previous->ParameterIndex =
942               Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
943           ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
944         }
945       } else if (Contexts.back().ColonIsForRangeExpr) {
946         Tok->setType(TT_RangeBasedForLoopColon);
947       } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
948         Tok->setType(TT_BitFieldColon);
949       } else if (Contexts.size() == 1 &&
950                  !Line.First->isOneOf(tok::kw_enum, tok::kw_case,
951                                       tok::kw_default)) {
952         FormatToken *Prev = Tok->getPreviousNonComment();
953         if (!Prev)
954           break;
955         if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept))
956           Tok->setType(TT_CtorInitializerColon);
957         else if (Prev->is(tok::kw_try)) {
958           // Member initializer list within function try block.
959           FormatToken *PrevPrev = Prev->getPreviousNonComment();
960           if (!PrevPrev)
961             break;
962           if (PrevPrev && PrevPrev->isOneOf(tok::r_paren, tok::kw_noexcept))
963             Tok->setType(TT_CtorInitializerColon);
964         } else
965           Tok->setType(TT_InheritanceColon);
966       } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
967                  (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
968                   (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
969                    Tok->Next->Next->is(tok::colon)))) {
970         // This handles a special macro in ObjC code where selectors including
971         // the colon are passed as macro arguments.
972         Tok->setType(TT_ObjCMethodExpr);
973       } else if (Contexts.back().ContextKind == tok::l_paren) {
974         Tok->setType(TT_InlineASMColon);
975       }
976       break;
977     case tok::pipe:
978     case tok::amp:
979       // | and & in declarations/type expressions represent union and
980       // intersection types, respectively.
981       if (Style.isJavaScript() && !Contexts.back().IsExpression)
982         Tok->setType(TT_JsTypeOperator);
983       break;
984     case tok::kw_if:
985     case tok::kw_while:
986       if (Tok->is(tok::kw_if) && CurrentToken &&
987           CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier))
988         next();
989       if (CurrentToken && CurrentToken->is(tok::l_paren)) {
990         next();
991         if (!parseParens(/*LookForDecls=*/true))
992           return false;
993       }
994       break;
995     case tok::kw_for:
996       if (Style.isJavaScript()) {
997         // x.for and {for: ...}
998         if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
999             (Tok->Next && Tok->Next->is(tok::colon)))
1000           break;
1001         // JS' for await ( ...
1002         if (CurrentToken && CurrentToken->is(Keywords.kw_await))
1003           next();
1004       }
1005       if (Style.isCpp() && CurrentToken && CurrentToken->is(tok::kw_co_await))
1006         next();
1007       Contexts.back().ColonIsForRangeExpr = true;
1008       next();
1009       if (!parseParens())
1010         return false;
1011       break;
1012     case tok::l_paren:
1013       // When faced with 'operator()()', the kw_operator handler incorrectly
1014       // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
1015       // the first two parens OverloadedOperators and the second l_paren an
1016       // OverloadedOperatorLParen.
1017       if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
1018           Tok->Previous->MatchingParen &&
1019           Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
1020         Tok->Previous->setType(TT_OverloadedOperator);
1021         Tok->Previous->MatchingParen->setType(TT_OverloadedOperator);
1022         Tok->setType(TT_OverloadedOperatorLParen);
1023       }
1024 
1025       if (!parseParens())
1026         return false;
1027       if (Line.MustBeDeclaration && Contexts.size() == 1 &&
1028           !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
1029           !Tok->isOneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen) &&
1030           (!Tok->Previous || !Tok->Previous->isOneOf(tok::kw___attribute,
1031                                                      TT_LeadingJavaAnnotation)))
1032         Line.MightBeFunctionDecl = true;
1033       break;
1034     case tok::l_square:
1035       if (!parseSquare())
1036         return false;
1037       break;
1038     case tok::l_brace:
1039       if (Style.Language == FormatStyle::LK_TextProto) {
1040         FormatToken *Previous = Tok->getPreviousNonComment();
1041         if (Previous && Previous->getType() != TT_DictLiteral)
1042           Previous->setType(TT_SelectorName);
1043       }
1044       if (!parseBrace())
1045         return false;
1046       break;
1047     case tok::less:
1048       if (parseAngle()) {
1049         Tok->setType(TT_TemplateOpener);
1050         // In TT_Proto, we must distignuish between:
1051         //   map<key, value>
1052         //   msg < item: data >
1053         //   msg: < item: data >
1054         // In TT_TextProto, map<key, value> does not occur.
1055         if (Style.Language == FormatStyle::LK_TextProto ||
1056             (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
1057              Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
1058           Tok->setType(TT_DictLiteral);
1059           FormatToken *Previous = Tok->getPreviousNonComment();
1060           if (Previous && Previous->getType() != TT_DictLiteral)
1061             Previous->setType(TT_SelectorName);
1062         }
1063       } else {
1064         Tok->setType(TT_BinaryOperator);
1065         NonTemplateLess.insert(Tok);
1066         CurrentToken = Tok;
1067         next();
1068       }
1069       break;
1070     case tok::r_paren:
1071     case tok::r_square:
1072       return false;
1073     case tok::r_brace:
1074       // Lines can start with '}'.
1075       if (Tok->Previous)
1076         return false;
1077       break;
1078     case tok::greater:
1079       if (Style.Language != FormatStyle::LK_TextProto)
1080         Tok->setType(TT_BinaryOperator);
1081       if (Tok->Previous && Tok->Previous->is(TT_TemplateCloser))
1082         Tok->SpacesRequiredBefore = 1;
1083       break;
1084     case tok::kw_operator:
1085       if (Style.Language == FormatStyle::LK_TextProto ||
1086           Style.Language == FormatStyle::LK_Proto)
1087         break;
1088       while (CurrentToken &&
1089              !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
1090         if (CurrentToken->isOneOf(tok::star, tok::amp))
1091           CurrentToken->setType(TT_PointerOrReference);
1092         consumeToken();
1093         if (CurrentToken && CurrentToken->is(tok::comma) &&
1094             CurrentToken->Previous->isNot(tok::kw_operator))
1095           break;
1096         if (CurrentToken && CurrentToken->Previous->isOneOf(
1097                                 TT_BinaryOperator, TT_UnaryOperator, tok::comma,
1098                                 tok::star, tok::arrow, tok::amp, tok::ampamp))
1099           CurrentToken->Previous->setType(TT_OverloadedOperator);
1100       }
1101       if (CurrentToken && CurrentToken->is(tok::l_paren))
1102         CurrentToken->setType(TT_OverloadedOperatorLParen);
1103       if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
1104         CurrentToken->Previous->setType(TT_OverloadedOperator);
1105       break;
1106     case tok::question:
1107       if (Style.isJavaScript() && Tok->Next &&
1108           Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
1109                              tok::r_brace)) {
1110         // Question marks before semicolons, colons, etc. indicate optional
1111         // types (fields, parameters), e.g.
1112         //   function(x?: string, y?) {...}
1113         //   class X { y?; }
1114         Tok->setType(TT_JsTypeOptionalQuestion);
1115         break;
1116       }
1117       // Declarations cannot be conditional expressions, this can only be part
1118       // of a type declaration.
1119       if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
1120           Style.isJavaScript())
1121         break;
1122       if (Style.isCSharp()) {
1123         // `Type?)`, `Type?>`, `Type? name;` and `Type? name =` can only be
1124         // nullable types.
1125         // Line.MustBeDeclaration will be true for `Type? name;`.
1126         if ((!Contexts.back().IsExpression && Line.MustBeDeclaration) ||
1127             (Tok->Next && Tok->Next->isOneOf(tok::r_paren, tok::greater)) ||
1128             (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next &&
1129              Tok->Next->Next->is(tok::equal))) {
1130           Tok->setType(TT_CSharpNullable);
1131           break;
1132         }
1133       }
1134       parseConditional();
1135       break;
1136     case tok::kw_template:
1137       parseTemplateDeclaration();
1138       break;
1139     case tok::comma:
1140       if (Contexts.back().InCtorInitializer)
1141         Tok->setType(TT_CtorInitializerComma);
1142       else if (Contexts.back().InInheritanceList)
1143         Tok->setType(TT_InheritanceComma);
1144       else if (Contexts.back().FirstStartOfName &&
1145                (Contexts.size() == 1 || startsWithInitStatement(Line))) {
1146         Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
1147         Line.IsMultiVariableDeclStmt = true;
1148       }
1149       if (Contexts.back().IsForEachMacro)
1150         Contexts.back().IsExpression = true;
1151       break;
1152     case tok::identifier:
1153       if (Tok->isOneOf(Keywords.kw___has_include,
1154                        Keywords.kw___has_include_next))
1155         parseHasInclude();
1156       if (Style.isCSharp() && Tok->is(Keywords.kw_where) && Tok->Next &&
1157           Tok->Next->isNot(tok::l_paren)) {
1158         Tok->setType(TT_CSharpGenericTypeConstraint);
1159         parseCSharpGenericTypeConstraint();
1160       }
1161       break;
1162     case tok::arrow:
1163       if (Tok->Previous && Tok->Previous->is(tok::kw_noexcept))
1164         Tok->setType(TT_TrailingReturnArrow);
1165       break;
1166     default:
1167       break;
1168     }
1169     return true;
1170   }
1171 
1172   void parseCSharpGenericTypeConstraint() {
1173     int OpenAngleBracketsCount = 0;
1174     while (CurrentToken) {
1175       if (CurrentToken->is(tok::less)) {
1176         // parseAngle is too greedy and will consume the whole line.
1177         CurrentToken->setType(TT_TemplateOpener);
1178         ++OpenAngleBracketsCount;
1179         next();
1180       } else if (CurrentToken->is(tok::greater)) {
1181         CurrentToken->setType(TT_TemplateCloser);
1182         --OpenAngleBracketsCount;
1183         next();
1184       } else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount == 0) {
1185         // We allow line breaks after GenericTypeConstraintComma's
1186         // so do not flag commas in Generics as GenericTypeConstraintComma's.
1187         CurrentToken->setType(TT_CSharpGenericTypeConstraintComma);
1188         next();
1189       } else if (CurrentToken->is(Keywords.kw_where)) {
1190         CurrentToken->setType(TT_CSharpGenericTypeConstraint);
1191         next();
1192       } else if (CurrentToken->is(tok::colon)) {
1193         CurrentToken->setType(TT_CSharpGenericTypeConstraintColon);
1194         next();
1195       } else {
1196         next();
1197       }
1198     }
1199   }
1200 
1201   void parseIncludeDirective() {
1202     if (CurrentToken && CurrentToken->is(tok::less)) {
1203       next();
1204       while (CurrentToken) {
1205         // Mark tokens up to the trailing line comments as implicit string
1206         // literals.
1207         if (CurrentToken->isNot(tok::comment) &&
1208             !CurrentToken->TokenText.startswith("//"))
1209           CurrentToken->setType(TT_ImplicitStringLiteral);
1210         next();
1211       }
1212     }
1213   }
1214 
1215   void parseWarningOrError() {
1216     next();
1217     // We still want to format the whitespace left of the first token of the
1218     // warning or error.
1219     next();
1220     while (CurrentToken) {
1221       CurrentToken->setType(TT_ImplicitStringLiteral);
1222       next();
1223     }
1224   }
1225 
1226   void parsePragma() {
1227     next(); // Consume "pragma".
1228     if (CurrentToken &&
1229         CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
1230       bool IsMark = CurrentToken->is(Keywords.kw_mark);
1231       next(); // Consume "mark".
1232       next(); // Consume first token (so we fix leading whitespace).
1233       while (CurrentToken) {
1234         if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
1235           CurrentToken->setType(TT_ImplicitStringLiteral);
1236         next();
1237       }
1238     }
1239   }
1240 
1241   void parseHasInclude() {
1242     if (!CurrentToken || !CurrentToken->is(tok::l_paren))
1243       return;
1244     next(); // '('
1245     parseIncludeDirective();
1246     next(); // ')'
1247   }
1248 
1249   LineType parsePreprocessorDirective() {
1250     bool IsFirstToken = CurrentToken->IsFirst;
1251     LineType Type = LT_PreprocessorDirective;
1252     next();
1253     if (!CurrentToken)
1254       return Type;
1255 
1256     if (Style.isJavaScript() && IsFirstToken) {
1257       // JavaScript files can contain shebang lines of the form:
1258       // #!/usr/bin/env node
1259       // Treat these like C++ #include directives.
1260       while (CurrentToken) {
1261         // Tokens cannot be comments here.
1262         CurrentToken->setType(TT_ImplicitStringLiteral);
1263         next();
1264       }
1265       return LT_ImportStatement;
1266     }
1267 
1268     if (CurrentToken->Tok.is(tok::numeric_constant)) {
1269       CurrentToken->SpacesRequiredBefore = 1;
1270       return Type;
1271     }
1272     // Hashes in the middle of a line can lead to any strange token
1273     // sequence.
1274     if (!CurrentToken->Tok.getIdentifierInfo())
1275       return Type;
1276     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
1277     case tok::pp_include:
1278     case tok::pp_include_next:
1279     case tok::pp_import:
1280       next();
1281       parseIncludeDirective();
1282       Type = LT_ImportStatement;
1283       break;
1284     case tok::pp_error:
1285     case tok::pp_warning:
1286       parseWarningOrError();
1287       break;
1288     case tok::pp_pragma:
1289       parsePragma();
1290       break;
1291     case tok::pp_if:
1292     case tok::pp_elif:
1293       Contexts.back().IsExpression = true;
1294       next();
1295       parseLine();
1296       break;
1297     default:
1298       break;
1299     }
1300     while (CurrentToken) {
1301       FormatToken *Tok = CurrentToken;
1302       next();
1303       if (Tok->is(tok::l_paren))
1304         parseParens();
1305       else if (Tok->isOneOf(Keywords.kw___has_include,
1306                             Keywords.kw___has_include_next))
1307         parseHasInclude();
1308     }
1309     return Type;
1310   }
1311 
1312 public:
1313   LineType parseLine() {
1314     if (!CurrentToken)
1315       return LT_Invalid;
1316     NonTemplateLess.clear();
1317     if (CurrentToken->is(tok::hash))
1318       return parsePreprocessorDirective();
1319 
1320     // Directly allow to 'import <string-literal>' to support protocol buffer
1321     // definitions (github.com/google/protobuf) or missing "#" (either way we
1322     // should not break the line).
1323     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
1324     if ((Style.Language == FormatStyle::LK_Java &&
1325          CurrentToken->is(Keywords.kw_package)) ||
1326         (Info && Info->getPPKeywordID() == tok::pp_import &&
1327          CurrentToken->Next &&
1328          CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
1329                                      tok::kw_static))) {
1330       next();
1331       parseIncludeDirective();
1332       return LT_ImportStatement;
1333     }
1334 
1335     // If this line starts and ends in '<' and '>', respectively, it is likely
1336     // part of "#define <a/b.h>".
1337     if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
1338       parseIncludeDirective();
1339       return LT_ImportStatement;
1340     }
1341 
1342     // In .proto files, top-level options and package statements are very
1343     // similar to import statements and should not be line-wrapped.
1344     if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
1345         CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
1346       next();
1347       if (CurrentToken && CurrentToken->is(tok::identifier)) {
1348         while (CurrentToken)
1349           next();
1350         return LT_ImportStatement;
1351       }
1352     }
1353 
1354     bool KeywordVirtualFound = false;
1355     bool ImportStatement = false;
1356 
1357     // import {...} from '...';
1358     if (Style.isJavaScript() && CurrentToken->is(Keywords.kw_import))
1359       ImportStatement = true;
1360 
1361     while (CurrentToken) {
1362       if (CurrentToken->is(tok::kw_virtual))
1363         KeywordVirtualFound = true;
1364       if (Style.isJavaScript()) {
1365         // export {...} from '...';
1366         // An export followed by "from 'some string';" is a re-export from
1367         // another module identified by a URI and is treated as a
1368         // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
1369         // Just "export {...};" or "export class ..." should not be treated as
1370         // an import in this sense.
1371         if (Line.First->is(tok::kw_export) &&
1372             CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
1373             CurrentToken->Next->isStringLiteral())
1374           ImportStatement = true;
1375         if (isClosureImportStatement(*CurrentToken))
1376           ImportStatement = true;
1377       }
1378       if (!consumeToken())
1379         return LT_Invalid;
1380     }
1381     if (KeywordVirtualFound)
1382       return LT_VirtualFunctionDecl;
1383     if (ImportStatement)
1384       return LT_ImportStatement;
1385 
1386     if (Line.startsWith(TT_ObjCMethodSpecifier)) {
1387       if (Contexts.back().FirstObjCSelectorName)
1388         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
1389             Contexts.back().LongestObjCSelectorName;
1390       return LT_ObjCMethodDecl;
1391     }
1392 
1393     for (const auto &ctx : Contexts)
1394       if (ctx.InStructArrayInitializer)
1395         return LT_ArrayOfStructInitializer;
1396 
1397     return LT_Other;
1398   }
1399 
1400 private:
1401   bool isClosureImportStatement(const FormatToken &Tok) {
1402     // FIXME: Closure-library specific stuff should not be hard-coded but be
1403     // configurable.
1404     return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
1405            Tok.Next->Next &&
1406            (Tok.Next->Next->TokenText == "module" ||
1407             Tok.Next->Next->TokenText == "provide" ||
1408             Tok.Next->Next->TokenText == "require" ||
1409             Tok.Next->Next->TokenText == "requireType" ||
1410             Tok.Next->Next->TokenText == "forwardDeclare") &&
1411            Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
1412   }
1413 
1414   void resetTokenMetadata() {
1415     if (!CurrentToken)
1416       return;
1417 
1418     // Reset token type in case we have already looked at it and then
1419     // recovered from an error (e.g. failure to find the matching >).
1420     if (!CurrentToken->isOneOf(
1421             TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro,
1422             TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace,
1423             TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow,
1424             TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator,
1425             TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral,
1426             TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro,
1427             TT_FunctionLikeOrFreestandingMacro, TT_RecordLBrace,
1428             TT_RequiresClause, TT_RequiresClauseInARequiresExpression,
1429             TT_RequiresExpression, TT_RequiresExpressionLParen,
1430             TT_RequiresExpressionLBrace, TT_BinaryOperator,
1431             TT_CompoundRequirementLBrace, TT_BracedListLBrace))
1432       CurrentToken->setType(TT_Unknown);
1433     CurrentToken->Role.reset();
1434     CurrentToken->MatchingParen = nullptr;
1435     CurrentToken->FakeLParens.clear();
1436     CurrentToken->FakeRParens = 0;
1437   }
1438 
1439   void next() {
1440     if (!CurrentToken)
1441       return;
1442 
1443     CurrentToken->NestingLevel = Contexts.size() - 1;
1444     CurrentToken->BindingStrength = Contexts.back().BindingStrength;
1445     modifyContext(*CurrentToken);
1446     determineTokenType(*CurrentToken);
1447     CurrentToken = CurrentToken->Next;
1448 
1449     resetTokenMetadata();
1450   }
1451 
1452   /// A struct to hold information valid in a specific context, e.g.
1453   /// a pair of parenthesis.
1454   struct Context {
1455     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
1456             bool IsExpression)
1457         : ContextKind(ContextKind), BindingStrength(BindingStrength),
1458           IsExpression(IsExpression) {}
1459 
1460     tok::TokenKind ContextKind;
1461     unsigned BindingStrength;
1462     bool IsExpression;
1463     unsigned LongestObjCSelectorName = 0;
1464     bool ColonIsForRangeExpr = false;
1465     bool ColonIsDictLiteral = false;
1466     bool ColonIsObjCMethodExpr = false;
1467     FormatToken *FirstObjCSelectorName = nullptr;
1468     FormatToken *FirstStartOfName = nullptr;
1469     bool CanBeExpression = true;
1470     bool InTemplateArgument = false;
1471     bool InCtorInitializer = false;
1472     bool InInheritanceList = false;
1473     bool CaretFound = false;
1474     bool IsForEachMacro = false;
1475     bool InCpp11AttributeSpecifier = false;
1476     bool InCSharpAttributeSpecifier = false;
1477     bool InStructArrayInitializer = false;
1478   };
1479 
1480   /// Puts a new \c Context onto the stack \c Contexts for the lifetime
1481   /// of each instance.
1482   struct ScopedContextCreator {
1483     AnnotatingParser &P;
1484 
1485     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1486                          unsigned Increase)
1487         : P(P) {
1488       P.Contexts.push_back(Context(ContextKind,
1489                                    P.Contexts.back().BindingStrength + Increase,
1490                                    P.Contexts.back().IsExpression));
1491     }
1492 
1493     ~ScopedContextCreator() {
1494       if (P.Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
1495         if (P.Contexts.back().InStructArrayInitializer) {
1496           P.Contexts.pop_back();
1497           P.Contexts.back().InStructArrayInitializer = true;
1498           return;
1499         }
1500       }
1501       P.Contexts.pop_back();
1502     }
1503   };
1504 
1505   void modifyContext(const FormatToken &Current) {
1506     if (Current.getPrecedence() == prec::Assignment &&
1507         !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1508         // Type aliases use `type X = ...;` in TypeScript and can be exported
1509         // using `export type ...`.
1510         !(Style.isJavaScript() &&
1511           (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1512            Line.startsWith(tok::kw_export, Keywords.kw_type,
1513                            tok::identifier))) &&
1514         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1515       Contexts.back().IsExpression = true;
1516       if (!Line.startsWith(TT_UnaryOperator)) {
1517         for (FormatToken *Previous = Current.Previous;
1518              Previous && Previous->Previous &&
1519              !Previous->Previous->isOneOf(tok::comma, tok::semi);
1520              Previous = Previous->Previous) {
1521           if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1522             Previous = Previous->MatchingParen;
1523             if (!Previous)
1524               break;
1525           }
1526           if (Previous->opensScope())
1527             break;
1528           if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1529               Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1530               Previous->Previous && Previous->Previous->isNot(tok::equal))
1531             Previous->setType(TT_PointerOrReference);
1532         }
1533       }
1534     } else if (Current.is(tok::lessless) &&
1535                (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1536       Contexts.back().IsExpression = true;
1537     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1538       Contexts.back().IsExpression = true;
1539     } else if (Current.is(TT_TrailingReturnArrow)) {
1540       Contexts.back().IsExpression = false;
1541     } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1542       Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1543     } else if (Current.Previous &&
1544                Current.Previous->is(TT_CtorInitializerColon)) {
1545       Contexts.back().IsExpression = true;
1546       Contexts.back().InCtorInitializer = true;
1547     } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1548       Contexts.back().InInheritanceList = true;
1549     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1550       for (FormatToken *Previous = Current.Previous;
1551            Previous && Previous->isOneOf(tok::star, tok::amp);
1552            Previous = Previous->Previous)
1553         Previous->setType(TT_PointerOrReference);
1554       if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1555         Contexts.back().IsExpression = false;
1556     } else if (Current.is(tok::kw_new)) {
1557       Contexts.back().CanBeExpression = false;
1558     } else if (Current.is(tok::semi) ||
1559                (Current.is(tok::exclaim) && Current.Previous &&
1560                 !Current.Previous->is(tok::kw_operator))) {
1561       // This should be the condition or increment in a for-loop.
1562       // But not operator !() (can't use TT_OverloadedOperator here as its not
1563       // been annotated yet).
1564       Contexts.back().IsExpression = true;
1565     }
1566   }
1567 
1568   static FormatToken *untilMatchingParen(FormatToken *Current) {
1569     // Used when `MatchingParen` is not yet established.
1570     int ParenLevel = 0;
1571     while (Current) {
1572       if (Current->is(tok::l_paren))
1573         ++ParenLevel;
1574       if (Current->is(tok::r_paren))
1575         --ParenLevel;
1576       if (ParenLevel < 1)
1577         break;
1578       Current = Current->Next;
1579     }
1580     return Current;
1581   }
1582 
1583   static bool isDeductionGuide(FormatToken &Current) {
1584     // Look for a deduction guide template<T> A(...) -> A<...>;
1585     if (Current.Previous && Current.Previous->is(tok::r_paren) &&
1586         Current.startsSequence(tok::arrow, tok::identifier, tok::less)) {
1587       // Find the TemplateCloser.
1588       FormatToken *TemplateCloser = Current.Next->Next;
1589       int NestingLevel = 0;
1590       while (TemplateCloser) {
1591         // Skip over an expressions in parens  A<(3 < 2)>;
1592         if (TemplateCloser->is(tok::l_paren)) {
1593           // No Matching Paren yet so skip to matching paren
1594           TemplateCloser = untilMatchingParen(TemplateCloser);
1595           if (!TemplateCloser)
1596             break;
1597         }
1598         if (TemplateCloser->is(tok::less))
1599           ++NestingLevel;
1600         if (TemplateCloser->is(tok::greater))
1601           --NestingLevel;
1602         if (NestingLevel < 1)
1603           break;
1604         TemplateCloser = TemplateCloser->Next;
1605       }
1606       // Assuming we have found the end of the template ensure its followed
1607       // with a semi-colon.
1608       if (TemplateCloser && TemplateCloser->Next &&
1609           TemplateCloser->Next->is(tok::semi) &&
1610           Current.Previous->MatchingParen) {
1611         // Determine if the identifier `A` prior to the A<..>; is the same as
1612         // prior to the A(..)
1613         FormatToken *LeadingIdentifier =
1614             Current.Previous->MatchingParen->Previous;
1615 
1616         // Differentiate a deduction guide by seeing the
1617         // > of the template prior to the leading identifier.
1618         if (LeadingIdentifier) {
1619           FormatToken *PriorLeadingIdentifier = LeadingIdentifier->Previous;
1620           // Skip back past explicit decoration
1621           if (PriorLeadingIdentifier &&
1622               PriorLeadingIdentifier->is(tok::kw_explicit))
1623             PriorLeadingIdentifier = PriorLeadingIdentifier->Previous;
1624 
1625           return PriorLeadingIdentifier &&
1626                  (PriorLeadingIdentifier->is(TT_TemplateCloser) ||
1627                   PriorLeadingIdentifier->ClosesRequiresClause) &&
1628                  LeadingIdentifier->TokenText == Current.Next->TokenText;
1629         }
1630       }
1631     }
1632     return false;
1633   }
1634 
1635   void determineTokenType(FormatToken &Current) {
1636     if (!Current.is(TT_Unknown))
1637       // The token type is already known.
1638       return;
1639 
1640     if ((Style.isJavaScript() || Style.isCSharp()) &&
1641         Current.is(tok::exclaim)) {
1642       if (Current.Previous) {
1643         bool IsIdentifier =
1644             Style.isJavaScript()
1645                 ? Keywords.IsJavaScriptIdentifier(
1646                       *Current.Previous, /* AcceptIdentifierName= */ true)
1647                 : Current.Previous->is(tok::identifier);
1648         if (IsIdentifier ||
1649             Current.Previous->isOneOf(
1650                 tok::kw_namespace, tok::r_paren, tok::r_square, tok::r_brace,
1651                 tok::kw_false, tok::kw_true, Keywords.kw_type, Keywords.kw_get,
1652                 Keywords.kw_set) ||
1653             Current.Previous->Tok.isLiteral()) {
1654           Current.setType(TT_NonNullAssertion);
1655           return;
1656         }
1657       }
1658       if (Current.Next &&
1659           Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1660         Current.setType(TT_NonNullAssertion);
1661         return;
1662       }
1663     }
1664 
1665     // Line.MightBeFunctionDecl can only be true after the parentheses of a
1666     // function declaration have been found. In this case, 'Current' is a
1667     // trailing token of this declaration and thus cannot be a name.
1668     if (Current.is(Keywords.kw_instanceof)) {
1669       Current.setType(TT_BinaryOperator);
1670     } else if (isStartOfName(Current) &&
1671                (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1672       Contexts.back().FirstStartOfName = &Current;
1673       Current.setType(TT_StartOfName);
1674     } else if (Current.is(tok::semi)) {
1675       // Reset FirstStartOfName after finding a semicolon so that a for loop
1676       // with multiple increment statements is not confused with a for loop
1677       // having multiple variable declarations.
1678       Contexts.back().FirstStartOfName = nullptr;
1679     } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1680       AutoFound = true;
1681     } else if (Current.is(tok::arrow) &&
1682                Style.Language == FormatStyle::LK_Java) {
1683       Current.setType(TT_LambdaArrow);
1684     } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1685                Current.NestingLevel == 0 &&
1686                !Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
1687       // not auto operator->() -> xxx;
1688       Current.setType(TT_TrailingReturnArrow);
1689     } else if (Current.is(tok::arrow) && Current.Previous &&
1690                Current.Previous->is(tok::r_brace)) {
1691       // Concept implicit conversion constraint needs to be treated like
1692       // a trailing return type  ... } -> <type>.
1693       Current.setType(TT_TrailingReturnArrow);
1694     } else if (isDeductionGuide(Current)) {
1695       // Deduction guides trailing arrow " A(...) -> A<T>;".
1696       Current.setType(TT_TrailingReturnArrow);
1697     } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1698       Current.setType(determineStarAmpUsage(
1699           Current,
1700           Contexts.back().CanBeExpression && Contexts.back().IsExpression,
1701           Contexts.back().InTemplateArgument));
1702     } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1703       Current.setType(determinePlusMinusCaretUsage(Current));
1704       if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1705         Contexts.back().CaretFound = true;
1706     } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1707       Current.setType(determineIncrementUsage(Current));
1708     } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1709       Current.setType(TT_UnaryOperator);
1710     } else if (Current.is(tok::question)) {
1711       if (Style.isJavaScript() && Line.MustBeDeclaration &&
1712           !Contexts.back().IsExpression) {
1713         // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1714         // on the interface, not a ternary expression.
1715         Current.setType(TT_JsTypeOptionalQuestion);
1716       } else {
1717         Current.setType(TT_ConditionalExpr);
1718       }
1719     } else if (Current.isBinaryOperator() &&
1720                (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
1721                (!Current.is(tok::greater) &&
1722                 Style.Language != FormatStyle::LK_TextProto)) {
1723       Current.setType(TT_BinaryOperator);
1724     } else if (Current.is(tok::comment)) {
1725       if (Current.TokenText.startswith("/*"))
1726         if (Current.TokenText.endswith("*/"))
1727           Current.setType(TT_BlockComment);
1728         else
1729           // The lexer has for some reason determined a comment here. But we
1730           // cannot really handle it, if it isn't properly terminated.
1731           Current.Tok.setKind(tok::unknown);
1732       else
1733         Current.setType(TT_LineComment);
1734     } else if (Current.is(tok::r_paren)) {
1735       if (rParenEndsCast(Current))
1736         Current.setType(TT_CastRParen);
1737       if (Current.MatchingParen && Current.Next &&
1738           !Current.Next->isBinaryOperator() &&
1739           !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1740                                  tok::comma, tok::period, tok::arrow,
1741                                  tok::coloncolon))
1742         if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1743           // Make sure this isn't the return type of an Obj-C block declaration
1744           if (AfterParen->Tok.isNot(tok::caret)) {
1745             if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1746               if (BeforeParen->is(tok::identifier) &&
1747                   !BeforeParen->is(TT_TypenameMacro) &&
1748                   BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1749                   (!BeforeParen->Previous ||
1750                    BeforeParen->Previous->ClosesTemplateDeclaration))
1751                 Current.setType(TT_FunctionAnnotationRParen);
1752           }
1753         }
1754     } else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() &&
1755                Style.Language != FormatStyle::LK_Java) {
1756       // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1757       // marks declarations and properties that need special formatting.
1758       switch (Current.Next->Tok.getObjCKeywordID()) {
1759       case tok::objc_interface:
1760       case tok::objc_implementation:
1761       case tok::objc_protocol:
1762         Current.setType(TT_ObjCDecl);
1763         break;
1764       case tok::objc_property:
1765         Current.setType(TT_ObjCProperty);
1766         break;
1767       default:
1768         break;
1769       }
1770     } else if (Current.is(tok::period)) {
1771       FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1772       if (PreviousNoComment &&
1773           PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1774         Current.setType(TT_DesignatedInitializerPeriod);
1775       else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1776                Current.Previous->isOneOf(TT_JavaAnnotation,
1777                                          TT_LeadingJavaAnnotation))
1778         Current.setType(Current.Previous->getType());
1779     } else if (canBeObjCSelectorComponent(Current) &&
1780                // FIXME(bug 36976): ObjC return types shouldn't use
1781                // TT_CastRParen.
1782                Current.Previous && Current.Previous->is(TT_CastRParen) &&
1783                Current.Previous->MatchingParen &&
1784                Current.Previous->MatchingParen->Previous &&
1785                Current.Previous->MatchingParen->Previous->is(
1786                    TT_ObjCMethodSpecifier)) {
1787       // This is the first part of an Objective-C selector name. (If there's no
1788       // colon after this, this is the only place which annotates the identifier
1789       // as a selector.)
1790       Current.setType(TT_SelectorName);
1791     } else if (Current.isOneOf(tok::identifier, tok::kw_const, tok::kw_noexcept,
1792                                tok::kw_requires) &&
1793                Current.Previous &&
1794                !Current.Previous->isOneOf(tok::equal, tok::at) &&
1795                Line.MightBeFunctionDecl && Contexts.size() == 1) {
1796       // Line.MightBeFunctionDecl can only be true after the parentheses of a
1797       // function declaration have been found.
1798       Current.setType(TT_TrailingAnnotation);
1799     } else if ((Style.Language == FormatStyle::LK_Java ||
1800                 Style.isJavaScript()) &&
1801                Current.Previous) {
1802       if (Current.Previous->is(tok::at) &&
1803           Current.isNot(Keywords.kw_interface)) {
1804         const FormatToken &AtToken = *Current.Previous;
1805         const FormatToken *Previous = AtToken.getPreviousNonComment();
1806         if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1807           Current.setType(TT_LeadingJavaAnnotation);
1808         else
1809           Current.setType(TT_JavaAnnotation);
1810       } else if (Current.Previous->is(tok::period) &&
1811                  Current.Previous->isOneOf(TT_JavaAnnotation,
1812                                            TT_LeadingJavaAnnotation)) {
1813         Current.setType(Current.Previous->getType());
1814       }
1815     }
1816   }
1817 
1818   /// Take a guess at whether \p Tok starts a name of a function or
1819   /// variable declaration.
1820   ///
1821   /// This is a heuristic based on whether \p Tok is an identifier following
1822   /// something that is likely a type.
1823   bool isStartOfName(const FormatToken &Tok) {
1824     if (Tok.isNot(tok::identifier) || !Tok.Previous)
1825       return false;
1826 
1827     if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1828                               Keywords.kw_as))
1829       return false;
1830     if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in))
1831       return false;
1832 
1833     // Skip "const" as it does not have an influence on whether this is a name.
1834     FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1835 
1836     // For javascript const can be like "let" or "var"
1837     if (!Style.isJavaScript())
1838       while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1839         PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1840 
1841     if (!PreviousNotConst)
1842       return false;
1843 
1844     if (PreviousNotConst->ClosesRequiresClause)
1845       return false;
1846 
1847     bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1848                        PreviousNotConst->Previous &&
1849                        PreviousNotConst->Previous->is(tok::hash);
1850 
1851     if (PreviousNotConst->is(TT_TemplateCloser))
1852       return PreviousNotConst && PreviousNotConst->MatchingParen &&
1853              PreviousNotConst->MatchingParen->Previous &&
1854              PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1855              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1856 
1857     if (PreviousNotConst->is(tok::r_paren) &&
1858         PreviousNotConst->is(TT_TypeDeclarationParen))
1859       return true;
1860 
1861     // If is a preprocess keyword like #define.
1862     if (IsPPKeyword)
1863       return false;
1864 
1865     // int a or auto a.
1866     if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto))
1867       return true;
1868 
1869     // *a or &a or &&a.
1870     if (PreviousNotConst->is(TT_PointerOrReference))
1871       return true;
1872 
1873     // MyClass a;
1874     if (PreviousNotConst->isSimpleTypeSpecifier())
1875       return true;
1876 
1877     // const a = in JavaScript.
1878     return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const);
1879   }
1880 
1881   /// Determine whether ')' is ending a cast.
1882   bool rParenEndsCast(const FormatToken &Tok) {
1883     // C-style casts are only used in C++, C# and Java.
1884     if (!Style.isCSharp() && !Style.isCpp() &&
1885         Style.Language != FormatStyle::LK_Java)
1886       return false;
1887 
1888     // Empty parens aren't casts and there are no casts at the end of the line.
1889     if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1890       return false;
1891 
1892     FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1893     if (LeftOfParens) {
1894       // If there is a closing parenthesis left of the current
1895       // parentheses, look past it as these might be chained casts.
1896       if (LeftOfParens->is(tok::r_paren) &&
1897           LeftOfParens->isNot(TT_CastRParen)) {
1898         if (!LeftOfParens->MatchingParen ||
1899             !LeftOfParens->MatchingParen->Previous)
1900           return false;
1901         LeftOfParens = LeftOfParens->MatchingParen->Previous;
1902       }
1903 
1904       if (LeftOfParens->is(tok::r_square)) {
1905         //   delete[] (void *)ptr;
1906         auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
1907           if (Tok->isNot(tok::r_square))
1908             return nullptr;
1909 
1910           Tok = Tok->getPreviousNonComment();
1911           if (!Tok || Tok->isNot(tok::l_square))
1912             return nullptr;
1913 
1914           Tok = Tok->getPreviousNonComment();
1915           if (!Tok || Tok->isNot(tok::kw_delete))
1916             return nullptr;
1917           return Tok;
1918         };
1919         if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
1920           LeftOfParens = MaybeDelete;
1921       }
1922 
1923       // The Condition directly below this one will see the operator arguments
1924       // as a (void *foo) cast.
1925       //   void operator delete(void *foo) ATTRIB;
1926       if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous &&
1927           LeftOfParens->Previous->is(tok::kw_operator))
1928         return false;
1929 
1930       // If there is an identifier (or with a few exceptions a keyword) right
1931       // before the parentheses, this is unlikely to be a cast.
1932       if (LeftOfParens->Tok.getIdentifierInfo() &&
1933           !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1934                                  tok::kw_delete))
1935         return false;
1936 
1937       // Certain other tokens right before the parentheses are also signals that
1938       // this cannot be a cast.
1939       if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1940                                 TT_TemplateCloser, tok::ellipsis))
1941         return false;
1942     }
1943 
1944     if (Tok.Next->is(tok::question))
1945       return false;
1946 
1947     // `foreach((A a, B b) in someList)` should not be seen as a cast.
1948     if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp())
1949       return false;
1950 
1951     // Functions which end with decorations like volatile, noexcept are unlikely
1952     // to be casts.
1953     if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
1954                           tok::kw_requires, tok::kw_throw, tok::arrow,
1955                           Keywords.kw_override, Keywords.kw_final) ||
1956         isCpp11AttributeSpecifier(*Tok.Next))
1957       return false;
1958 
1959     // As Java has no function types, a "(" after the ")" likely means that this
1960     // is a cast.
1961     if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1962       return true;
1963 
1964     // If a (non-string) literal follows, this is likely a cast.
1965     if (Tok.Next->isNot(tok::string_literal) &&
1966         (Tok.Next->Tok.isLiteral() ||
1967          Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1968       return true;
1969 
1970     // Heuristically try to determine whether the parentheses contain a type.
1971     auto IsQualifiedPointerOrReference = [](FormatToken *T) {
1972       // This is used to handle cases such as x = (foo *const)&y;
1973       assert(!T->isSimpleTypeSpecifier() && "Should have already been checked");
1974       // Strip trailing qualifiers such as const or volatile when checking
1975       // whether the parens could be a cast to a pointer/reference type.
1976       while (T) {
1977         if (T->is(TT_AttributeParen)) {
1978           // Handle `x = (foo *__attribute__((foo)))&v;`:
1979           if (T->MatchingParen && T->MatchingParen->Previous &&
1980               T->MatchingParen->Previous->is(tok::kw___attribute)) {
1981             T = T->MatchingParen->Previous->Previous;
1982             continue;
1983           }
1984         } else if (T->is(TT_AttributeSquare)) {
1985           // Handle `x = (foo *[[clang::foo]])&v;`:
1986           if (T->MatchingParen && T->MatchingParen->Previous) {
1987             T = T->MatchingParen->Previous;
1988             continue;
1989           }
1990         } else if (T->canBePointerOrReferenceQualifier()) {
1991           T = T->Previous;
1992           continue;
1993         }
1994         break;
1995       }
1996       return T && T->is(TT_PointerOrReference);
1997     };
1998     bool ParensAreType =
1999         !Tok.Previous ||
2000         Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) ||
2001         Tok.Previous->isSimpleTypeSpecifier() ||
2002         IsQualifiedPointerOrReference(Tok.Previous);
2003     bool ParensCouldEndDecl =
2004         Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
2005     if (ParensAreType && !ParensCouldEndDecl)
2006       return true;
2007 
2008     // At this point, we heuristically assume that there are no casts at the
2009     // start of the line. We assume that we have found most cases where there
2010     // are by the logic above, e.g. "(void)x;".
2011     if (!LeftOfParens)
2012       return false;
2013 
2014     // Certain token types inside the parentheses mean that this can't be a
2015     // cast.
2016     for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
2017          Token = Token->Next)
2018       if (Token->is(TT_BinaryOperator))
2019         return false;
2020 
2021     // If the following token is an identifier or 'this', this is a cast. All
2022     // cases where this can be something else are handled above.
2023     if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
2024       return true;
2025 
2026     // Look for a cast `( x ) (`.
2027     if (Tok.Next->is(tok::l_paren) && Tok.Previous && Tok.Previous->Previous) {
2028       if (Tok.Previous->is(tok::identifier) &&
2029           Tok.Previous->Previous->is(tok::l_paren))
2030         return true;
2031     }
2032 
2033     if (!Tok.Next->Next)
2034       return false;
2035 
2036     // If the next token after the parenthesis is a unary operator, assume
2037     // that this is cast, unless there are unexpected tokens inside the
2038     // parenthesis.
2039     bool NextIsUnary =
2040         Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
2041     if (!NextIsUnary || Tok.Next->is(tok::plus) ||
2042         !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
2043       return false;
2044     // Search for unexpected tokens.
2045     for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
2046          Prev = Prev->Previous)
2047       if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
2048         return false;
2049     return true;
2050   }
2051 
2052   /// Return the type of the given token assuming it is * or &.
2053   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
2054                                   bool InTemplateArgument) {
2055     if (Style.isJavaScript())
2056       return TT_BinaryOperator;
2057 
2058     // && in C# must be a binary operator.
2059     if (Style.isCSharp() && Tok.is(tok::ampamp))
2060       return TT_BinaryOperator;
2061 
2062     const FormatToken *PrevToken = Tok.getPreviousNonComment();
2063     if (!PrevToken)
2064       return TT_UnaryOperator;
2065 
2066     const FormatToken *NextToken = Tok.getNextNonComment();
2067     if (!NextToken ||
2068         NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) ||
2069         NextToken->canBePointerOrReferenceQualifier() ||
2070         (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
2071       return TT_PointerOrReference;
2072 
2073     if (PrevToken->is(tok::coloncolon))
2074       return TT_PointerOrReference;
2075 
2076     if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen))
2077       return TT_PointerOrReference;
2078 
2079     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
2080                            tok::comma, tok::semi, tok::kw_return, tok::colon,
2081                            tok::kw_co_return, tok::kw_co_await,
2082                            tok::kw_co_yield, tok::equal, tok::kw_delete,
2083                            tok::kw_sizeof, tok::kw_throw, TT_BinaryOperator,
2084                            TT_ConditionalExpr, TT_UnaryOperator, TT_CastRParen))
2085       return TT_UnaryOperator;
2086 
2087     if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
2088       return TT_PointerOrReference;
2089     if (NextToken->is(tok::kw_operator) && !IsExpression)
2090       return TT_PointerOrReference;
2091     if (NextToken->isOneOf(tok::comma, tok::semi))
2092       return TT_PointerOrReference;
2093 
2094     if (PrevToken->Tok.isLiteral() ||
2095         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
2096                            tok::kw_false, tok::r_brace) ||
2097         NextToken->Tok.isLiteral() ||
2098         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
2099         NextToken->isUnaryOperator() ||
2100         // If we know we're in a template argument, there are no named
2101         // declarations. Thus, having an identifier on the right-hand side
2102         // indicates a binary operator.
2103         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
2104       return TT_BinaryOperator;
2105 
2106     // "&&(" is quite unlikely to be two successive unary "&".
2107     if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren))
2108       return TT_BinaryOperator;
2109 
2110     // This catches some cases where evaluation order is used as control flow:
2111     //   aaa && aaa->f();
2112     if (NextToken->Tok.isAnyIdentifier()) {
2113       const FormatToken *NextNextToken = NextToken->getNextNonComment();
2114       if (NextNextToken && NextNextToken->is(tok::arrow))
2115         return TT_BinaryOperator;
2116     }
2117 
2118     // It is very unlikely that we are going to find a pointer or reference type
2119     // definition on the RHS of an assignment.
2120     if (IsExpression && !Contexts.back().CaretFound)
2121       return TT_BinaryOperator;
2122 
2123     return TT_PointerOrReference;
2124   }
2125 
2126   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
2127     const FormatToken *PrevToken = Tok.getPreviousNonComment();
2128     if (!PrevToken)
2129       return TT_UnaryOperator;
2130 
2131     if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
2132       // This must be a sequence of leading unary operators.
2133       return TT_UnaryOperator;
2134 
2135     // Use heuristics to recognize unary operators.
2136     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
2137                            tok::question, tok::colon, tok::kw_return,
2138                            tok::kw_case, tok::at, tok::l_brace, tok::kw_throw,
2139                            tok::kw_co_return, tok::kw_co_yield))
2140       return TT_UnaryOperator;
2141 
2142     // There can't be two consecutive binary operators.
2143     if (PrevToken->is(TT_BinaryOperator))
2144       return TT_UnaryOperator;
2145 
2146     // Fall back to marking the token as binary operator.
2147     return TT_BinaryOperator;
2148   }
2149 
2150   /// Determine whether ++/-- are pre- or post-increments/-decrements.
2151   TokenType determineIncrementUsage(const FormatToken &Tok) {
2152     const FormatToken *PrevToken = Tok.getPreviousNonComment();
2153     if (!PrevToken || PrevToken->is(TT_CastRParen))
2154       return TT_UnaryOperator;
2155     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
2156       return TT_TrailingUnaryOperator;
2157 
2158     return TT_UnaryOperator;
2159   }
2160 
2161   SmallVector<Context, 8> Contexts;
2162 
2163   const FormatStyle &Style;
2164   AnnotatedLine &Line;
2165   FormatToken *CurrentToken;
2166   bool AutoFound;
2167   const AdditionalKeywords &Keywords;
2168 
2169   // Set of "<" tokens that do not open a template parameter list. If parseAngle
2170   // determines that a specific token can't be a template opener, it will make
2171   // same decision irrespective of the decisions for tokens leading up to it.
2172   // Store this information to prevent this from causing exponential runtime.
2173   llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
2174 };
2175 
2176 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
2177 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
2178 
2179 /// Parses binary expressions by inserting fake parenthesis based on
2180 /// operator precedence.
2181 class ExpressionParser {
2182 public:
2183   ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
2184                    AnnotatedLine &Line)
2185       : Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {}
2186 
2187   /// Parse expressions with the given operator precedence.
2188   void parse(int Precedence = 0) {
2189     // Skip 'return' and ObjC selector colons as they are not part of a binary
2190     // expression.
2191     while (Current && (Current->is(tok::kw_return) ||
2192                        (Current->is(tok::colon) &&
2193                         Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
2194       next();
2195 
2196     if (!Current || Precedence > PrecedenceArrowAndPeriod)
2197       return;
2198 
2199     // Conditional expressions need to be parsed separately for proper nesting.
2200     if (Precedence == prec::Conditional) {
2201       parseConditionalExpr();
2202       return;
2203     }
2204 
2205     // Parse unary operators, which all have a higher precedence than binary
2206     // operators.
2207     if (Precedence == PrecedenceUnaryOperator) {
2208       parseUnaryOperator();
2209       return;
2210     }
2211 
2212     FormatToken *Start = Current;
2213     FormatToken *LatestOperator = nullptr;
2214     unsigned OperatorIndex = 0;
2215 
2216     while (Current) {
2217       // Consume operators with higher precedence.
2218       parse(Precedence + 1);
2219 
2220       int CurrentPrecedence = getCurrentPrecedence();
2221 
2222       if (Precedence == CurrentPrecedence && Current &&
2223           Current->is(TT_SelectorName)) {
2224         if (LatestOperator)
2225           addFakeParenthesis(Start, prec::Level(Precedence));
2226         Start = Current;
2227       }
2228 
2229       // At the end of the line or when an operator with higher precedence is
2230       // found, insert fake parenthesis and return.
2231       if (!Current ||
2232           (Current->closesScope() &&
2233            (Current->MatchingParen || Current->is(TT_TemplateString))) ||
2234           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
2235           (CurrentPrecedence == prec::Conditional &&
2236            Precedence == prec::Assignment && Current->is(tok::colon)))
2237         break;
2238 
2239       // Consume scopes: (), [], <> and {}
2240       // In addition to that we handle require clauses as scope, so that the
2241       // constraints in that are correctly indented.
2242       if (Current->opensScope() ||
2243           Current->isOneOf(TT_RequiresClause,
2244                            TT_RequiresClauseInARequiresExpression)) {
2245         // In fragment of a JavaScript template string can look like '}..${' and
2246         // thus close a scope and open a new one at the same time.
2247         while (Current && (!Current->closesScope() || Current->opensScope())) {
2248           next();
2249           parse();
2250         }
2251         next();
2252       } else {
2253         // Operator found.
2254         if (CurrentPrecedence == Precedence) {
2255           if (LatestOperator)
2256             LatestOperator->NextOperator = Current;
2257           LatestOperator = Current;
2258           Current->OperatorIndex = OperatorIndex;
2259           ++OperatorIndex;
2260         }
2261         next(/*SkipPastLeadingComments=*/Precedence > 0);
2262       }
2263     }
2264 
2265     if (LatestOperator && (Current || Precedence > 0)) {
2266       // The requires clauses do not neccessarily end in a semicolon or a brace,
2267       // but just go over to struct/class or a function declaration, we need to
2268       // intervene so that the fake right paren is inserted correctly.
2269       auto End =
2270           (Start->Previous &&
2271            Start->Previous->isOneOf(TT_RequiresClause,
2272                                     TT_RequiresClauseInARequiresExpression))
2273               ? [this](){
2274                   auto Ret = Current ? Current : Line.Last;
2275                   while (!Ret->ClosesRequiresClause && Ret->Previous)
2276                     Ret = Ret->Previous;
2277                   return Ret;
2278                 }()
2279               : nullptr;
2280 
2281       if (Precedence == PrecedenceArrowAndPeriod) {
2282         // Call expressions don't have a binary operator precedence.
2283         addFakeParenthesis(Start, prec::Unknown, End);
2284       } else {
2285         addFakeParenthesis(Start, prec::Level(Precedence), End);
2286       }
2287     }
2288   }
2289 
2290 private:
2291   /// Gets the precedence (+1) of the given token for binary operators
2292   /// and other tokens that we treat like binary operators.
2293   int getCurrentPrecedence() {
2294     if (Current) {
2295       const FormatToken *NextNonComment = Current->getNextNonComment();
2296       if (Current->is(TT_ConditionalExpr))
2297         return prec::Conditional;
2298       if (NextNonComment && Current->is(TT_SelectorName) &&
2299           (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
2300            ((Style.Language == FormatStyle::LK_Proto ||
2301              Style.Language == FormatStyle::LK_TextProto) &&
2302             NextNonComment->is(tok::less))))
2303         return prec::Assignment;
2304       if (Current->is(TT_JsComputedPropertyName))
2305         return prec::Assignment;
2306       if (Current->is(TT_LambdaArrow))
2307         return prec::Comma;
2308       if (Current->is(TT_FatArrow))
2309         return prec::Assignment;
2310       if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
2311           (Current->is(tok::comment) && NextNonComment &&
2312            NextNonComment->is(TT_SelectorName)))
2313         return 0;
2314       if (Current->is(TT_RangeBasedForLoopColon))
2315         return prec::Comma;
2316       if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
2317           Current->is(Keywords.kw_instanceof))
2318         return prec::Relational;
2319       if (Style.isJavaScript() &&
2320           Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
2321         return prec::Relational;
2322       if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
2323         return Current->getPrecedence();
2324       if (Current->isOneOf(tok::period, tok::arrow))
2325         return PrecedenceArrowAndPeriod;
2326       if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
2327           Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
2328                            Keywords.kw_throws))
2329         return 0;
2330     }
2331     return -1;
2332   }
2333 
2334   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence,
2335                           FormatToken *End = nullptr) {
2336     Start->FakeLParens.push_back(Precedence);
2337     if (Precedence > prec::Unknown)
2338       Start->StartsBinaryExpression = true;
2339     if (!End && Current)
2340       End = Current->getPreviousNonComment();
2341     if (End) {
2342       ++End->FakeRParens;
2343       if (Precedence > prec::Unknown)
2344         End->EndsBinaryExpression = true;
2345     }
2346   }
2347 
2348   /// Parse unary operator expressions and surround them with fake
2349   /// parentheses if appropriate.
2350   void parseUnaryOperator() {
2351     llvm::SmallVector<FormatToken *, 2> Tokens;
2352     while (Current && Current->is(TT_UnaryOperator)) {
2353       Tokens.push_back(Current);
2354       next();
2355     }
2356     parse(PrecedenceArrowAndPeriod);
2357     for (FormatToken *Token : llvm::reverse(Tokens))
2358       // The actual precedence doesn't matter.
2359       addFakeParenthesis(Token, prec::Unknown);
2360   }
2361 
2362   void parseConditionalExpr() {
2363     while (Current && Current->isTrailingComment())
2364       next();
2365     FormatToken *Start = Current;
2366     parse(prec::LogicalOr);
2367     if (!Current || !Current->is(tok::question))
2368       return;
2369     next();
2370     parse(prec::Assignment);
2371     if (!Current || Current->isNot(TT_ConditionalExpr))
2372       return;
2373     next();
2374     parse(prec::Assignment);
2375     addFakeParenthesis(Start, prec::Conditional);
2376   }
2377 
2378   void next(bool SkipPastLeadingComments = true) {
2379     if (Current)
2380       Current = Current->Next;
2381     while (Current &&
2382            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
2383            Current->isTrailingComment())
2384       Current = Current->Next;
2385   }
2386 
2387   const FormatStyle &Style;
2388   const AdditionalKeywords &Keywords;
2389   const AnnotatedLine &Line;
2390   FormatToken *Current;
2391 };
2392 
2393 } // end anonymous namespace
2394 
2395 void TokenAnnotator::setCommentLineLevels(
2396     SmallVectorImpl<AnnotatedLine *> &Lines) {
2397   const AnnotatedLine *NextNonCommentLine = nullptr;
2398   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
2399     assert(Line->First);
2400     bool CommentLine = true;
2401     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
2402       if (!Tok->is(tok::comment)) {
2403         CommentLine = false;
2404         break;
2405       }
2406     }
2407 
2408     // If the comment is currently aligned with the line immediately following
2409     // it, that's probably intentional and we should keep it.
2410     if (NextNonCommentLine && CommentLine &&
2411         NextNonCommentLine->First->NewlinesBefore <= 1 &&
2412         NextNonCommentLine->First->OriginalColumn ==
2413             Line->First->OriginalColumn) {
2414       // Align comments for preprocessor lines with the # in column 0 if
2415       // preprocessor lines are not indented. Otherwise, align with the next
2416       // line.
2417       Line->Level =
2418           (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
2419            (NextNonCommentLine->Type == LT_PreprocessorDirective ||
2420             NextNonCommentLine->Type == LT_ImportStatement))
2421               ? 0
2422               : NextNonCommentLine->Level;
2423     } else {
2424       NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr;
2425     }
2426 
2427     setCommentLineLevels(Line->Children);
2428   }
2429 }
2430 
2431 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
2432   unsigned Result = 0;
2433   for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
2434     Result = std::max(Result, Tok->NestingLevel);
2435   return Result;
2436 }
2437 
2438 void TokenAnnotator::annotate(AnnotatedLine &Line) {
2439   for (auto &Child : Line.Children)
2440     annotate(*Child);
2441 
2442   AnnotatingParser Parser(Style, Line, Keywords);
2443   Line.Type = Parser.parseLine();
2444 
2445   // With very deep nesting, ExpressionParser uses lots of stack and the
2446   // formatting algorithm is very slow. We're not going to do a good job here
2447   // anyway - it's probably generated code being formatted by mistake.
2448   // Just skip the whole line.
2449   if (maxNestingDepth(Line) > 50)
2450     Line.Type = LT_Invalid;
2451 
2452   if (Line.Type == LT_Invalid)
2453     return;
2454 
2455   ExpressionParser ExprParser(Style, Keywords, Line);
2456   ExprParser.parse();
2457 
2458   if (Line.startsWith(TT_ObjCMethodSpecifier))
2459     Line.Type = LT_ObjCMethodDecl;
2460   else if (Line.startsWith(TT_ObjCDecl))
2461     Line.Type = LT_ObjCDecl;
2462   else if (Line.startsWith(TT_ObjCProperty))
2463     Line.Type = LT_ObjCProperty;
2464 
2465   Line.First->SpacesRequiredBefore = 1;
2466   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
2467 }
2468 
2469 // This function heuristically determines whether 'Current' starts the name of a
2470 // function declaration.
2471 static bool isFunctionDeclarationName(bool IsCpp, const FormatToken &Current,
2472                                       const AnnotatedLine &Line) {
2473   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
2474     for (; Next; Next = Next->Next) {
2475       if (Next->is(TT_OverloadedOperatorLParen))
2476         return Next;
2477       if (Next->is(TT_OverloadedOperator))
2478         continue;
2479       if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
2480         // For 'new[]' and 'delete[]'.
2481         if (Next->Next &&
2482             Next->Next->startsSequence(tok::l_square, tok::r_square))
2483           Next = Next->Next->Next;
2484         continue;
2485       }
2486       if (Next->startsSequence(tok::l_square, tok::r_square)) {
2487         // For operator[]().
2488         Next = Next->Next;
2489         continue;
2490       }
2491       if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) &&
2492           Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) {
2493         // For operator void*(), operator char*(), operator Foo*().
2494         Next = Next->Next;
2495         continue;
2496       }
2497       if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
2498         Next = Next->MatchingParen;
2499         continue;
2500       }
2501 
2502       break;
2503     }
2504     return nullptr;
2505   };
2506 
2507   // Find parentheses of parameter list.
2508   const FormatToken *Next = Current.Next;
2509   if (Current.is(tok::kw_operator)) {
2510     if (Current.Previous && Current.Previous->is(tok::coloncolon))
2511       return false;
2512     Next = skipOperatorName(Next);
2513   } else {
2514     if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
2515       return false;
2516     for (; Next; Next = Next->Next) {
2517       if (Next->is(TT_TemplateOpener)) {
2518         Next = Next->MatchingParen;
2519       } else if (Next->is(tok::coloncolon)) {
2520         Next = Next->Next;
2521         if (!Next)
2522           return false;
2523         if (Next->is(tok::kw_operator)) {
2524           Next = skipOperatorName(Next->Next);
2525           break;
2526         }
2527         if (!Next->is(tok::identifier))
2528           return false;
2529       } else if (Next->is(tok::l_paren)) {
2530         break;
2531       } else {
2532         return false;
2533       }
2534     }
2535   }
2536 
2537   // Check whether parameter list can belong to a function declaration.
2538   if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
2539     return false;
2540   // If the lines ends with "{", this is likely a function definition.
2541   if (Line.Last->is(tok::l_brace))
2542     return true;
2543   if (Next->Next == Next->MatchingParen)
2544     return true; // Empty parentheses.
2545   // If there is an &/&& after the r_paren, this is likely a function.
2546   if (Next->MatchingParen->Next &&
2547       Next->MatchingParen->Next->is(TT_PointerOrReference))
2548     return true;
2549 
2550   // Check for K&R C function definitions (and C++ function definitions with
2551   // unnamed parameters), e.g.:
2552   //   int f(i)
2553   //   {
2554   //     return i + 1;
2555   //   }
2556   //   bool g(size_t = 0, bool b = false)
2557   //   {
2558   //     return !b;
2559   //   }
2560   if (IsCpp && Next->Next && Next->Next->is(tok::identifier) &&
2561       !Line.endsWith(tok::semi))
2562     return true;
2563 
2564   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
2565        Tok = Tok->Next) {
2566     if (Tok->is(TT_TypeDeclarationParen))
2567       return true;
2568     if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
2569       Tok = Tok->MatchingParen;
2570       continue;
2571     }
2572     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
2573         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
2574       return true;
2575     if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
2576         Tok->Tok.isLiteral())
2577       return false;
2578   }
2579   return false;
2580 }
2581 
2582 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
2583   assert(Line.MightBeFunctionDecl);
2584 
2585   if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
2586        Style.AlwaysBreakAfterReturnType ==
2587            FormatStyle::RTBS_TopLevelDefinitions) &&
2588       Line.Level > 0)
2589     return false;
2590 
2591   switch (Style.AlwaysBreakAfterReturnType) {
2592   case FormatStyle::RTBS_None:
2593     return false;
2594   case FormatStyle::RTBS_All:
2595   case FormatStyle::RTBS_TopLevel:
2596     return true;
2597   case FormatStyle::RTBS_AllDefinitions:
2598   case FormatStyle::RTBS_TopLevelDefinitions:
2599     return Line.mightBeFunctionDefinition();
2600   }
2601 
2602   return false;
2603 }
2604 
2605 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2606   for (AnnotatedLine *ChildLine : Line.Children)
2607     calculateFormattingInformation(*ChildLine);
2608 
2609   Line.First->TotalLength =
2610       Line.First->IsMultiline ? Style.ColumnLimit
2611                               : Line.FirstStartColumn + Line.First->ColumnWidth;
2612   FormatToken *Current = Line.First->Next;
2613   bool InFunctionDecl = Line.MightBeFunctionDecl;
2614   bool AlignArrayOfStructures =
2615       (Style.AlignArrayOfStructures != FormatStyle::AIAS_None &&
2616        Line.Type == LT_ArrayOfStructInitializer);
2617   if (AlignArrayOfStructures)
2618     calculateArrayInitializerColumnList(Line);
2619 
2620   while (Current) {
2621     if (isFunctionDeclarationName(Style.isCpp(), *Current, Line))
2622       Current->setType(TT_FunctionDeclarationName);
2623     const FormatToken *Prev = Current->Previous;
2624     if (Current->is(TT_LineComment)) {
2625       if (Prev->is(BK_BracedInit) && Prev->opensScope())
2626         Current->SpacesRequiredBefore =
2627             (Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1;
2628       else
2629         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2630 
2631       // If we find a trailing comment, iterate backwards to determine whether
2632       // it seems to relate to a specific parameter. If so, break before that
2633       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2634       // to the previous line in:
2635       //   SomeFunction(a,
2636       //                b, // comment
2637       //                c);
2638       if (!Current->HasUnescapedNewline) {
2639         for (FormatToken *Parameter = Current->Previous; Parameter;
2640              Parameter = Parameter->Previous) {
2641           if (Parameter->isOneOf(tok::comment, tok::r_brace))
2642             break;
2643           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2644             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2645                 Parameter->HasUnescapedNewline)
2646               Parameter->MustBreakBefore = true;
2647             break;
2648           }
2649         }
2650       }
2651     } else if (Current->SpacesRequiredBefore == 0 &&
2652                spaceRequiredBefore(Line, *Current)) {
2653       Current->SpacesRequiredBefore = 1;
2654     }
2655 
2656     Current->MustBreakBefore =
2657         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2658 
2659     if (!Current->MustBreakBefore && InFunctionDecl &&
2660         Current->is(TT_FunctionDeclarationName))
2661       Current->MustBreakBefore = mustBreakForReturnType(Line);
2662 
2663     Current->CanBreakBefore =
2664         Current->MustBreakBefore || canBreakBefore(Line, *Current);
2665     unsigned ChildSize = 0;
2666     if (Prev->Children.size() == 1) {
2667       FormatToken &LastOfChild = *Prev->Children[0]->Last;
2668       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2669                                                   : LastOfChild.TotalLength + 1;
2670     }
2671     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2672         (Prev->Children.size() == 1 &&
2673          Prev->Children[0]->First->MustBreakBefore) ||
2674         Current->IsMultiline)
2675       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2676     else
2677       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2678                              ChildSize + Current->SpacesRequiredBefore;
2679 
2680     if (Current->is(TT_CtorInitializerColon))
2681       InFunctionDecl = false;
2682 
2683     // FIXME: Only calculate this if CanBreakBefore is true once static
2684     // initializers etc. are sorted out.
2685     // FIXME: Move magic numbers to a better place.
2686 
2687     // Reduce penalty for aligning ObjC method arguments using the colon
2688     // alignment as this is the canonical way (still prefer fitting everything
2689     // into one line if possible). Trying to fit a whole expression into one
2690     // line should not force other line breaks (e.g. when ObjC method
2691     // expression is a part of other expression).
2692     Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
2693     if (Style.Language == FormatStyle::LK_ObjC &&
2694         Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
2695       if (Current->ParameterIndex == 1)
2696         Current->SplitPenalty += 5 * Current->BindingStrength;
2697     } else {
2698       Current->SplitPenalty += 20 * Current->BindingStrength;
2699     }
2700 
2701     Current = Current->Next;
2702   }
2703 
2704   calculateUnbreakableTailLengths(Line);
2705   unsigned IndentLevel = Line.Level;
2706   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2707     if (Current->Role)
2708       Current->Role->precomputeFormattingInfos(Current);
2709     if (Current->MatchingParen &&
2710         Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
2711         IndentLevel > 0)
2712       --IndentLevel;
2713     Current->IndentLevel = IndentLevel;
2714     if (Current->opensBlockOrBlockTypeList(Style))
2715       ++IndentLevel;
2716   }
2717 
2718   LLVM_DEBUG({ printDebugInfo(Line); });
2719 }
2720 
2721 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2722   unsigned UnbreakableTailLength = 0;
2723   FormatToken *Current = Line.Last;
2724   while (Current) {
2725     Current->UnbreakableTailLength = UnbreakableTailLength;
2726     if (Current->CanBreakBefore ||
2727         Current->isOneOf(tok::comment, tok::string_literal)) {
2728       UnbreakableTailLength = 0;
2729     } else {
2730       UnbreakableTailLength +=
2731           Current->ColumnWidth + Current->SpacesRequiredBefore;
2732     }
2733     Current = Current->Previous;
2734   }
2735 }
2736 
2737 void TokenAnnotator::calculateArrayInitializerColumnList(AnnotatedLine &Line) {
2738   if (Line.First == Line.Last)
2739     return;
2740   auto *CurrentToken = Line.First;
2741   CurrentToken->ArrayInitializerLineStart = true;
2742   unsigned Depth = 0;
2743   while (CurrentToken != nullptr && CurrentToken != Line.Last) {
2744     if (CurrentToken->is(tok::l_brace)) {
2745       CurrentToken->IsArrayInitializer = true;
2746       if (CurrentToken->Next != nullptr)
2747         CurrentToken->Next->MustBreakBefore = true;
2748       CurrentToken =
2749           calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1);
2750     } else {
2751       CurrentToken = CurrentToken->Next;
2752     }
2753   }
2754 }
2755 
2756 FormatToken *TokenAnnotator::calculateInitializerColumnList(
2757     AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) {
2758   while (CurrentToken != nullptr && CurrentToken != Line.Last) {
2759     if (CurrentToken->is(tok::l_brace))
2760       ++Depth;
2761     else if (CurrentToken->is(tok::r_brace))
2762       --Depth;
2763     if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) {
2764       CurrentToken = CurrentToken->Next;
2765       if (CurrentToken == nullptr)
2766         break;
2767       CurrentToken->StartsColumn = true;
2768       CurrentToken = CurrentToken->Previous;
2769     }
2770     CurrentToken = CurrentToken->Next;
2771   }
2772   return CurrentToken;
2773 }
2774 
2775 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2776                                       const FormatToken &Tok,
2777                                       bool InFunctionDecl) {
2778   const FormatToken &Left = *Tok.Previous;
2779   const FormatToken &Right = Tok;
2780 
2781   if (Left.is(tok::semi))
2782     return 0;
2783 
2784   if (Style.Language == FormatStyle::LK_Java) {
2785     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2786       return 1;
2787     if (Right.is(Keywords.kw_implements))
2788       return 2;
2789     if (Left.is(tok::comma) && Left.NestingLevel == 0)
2790       return 3;
2791   } else if (Style.isJavaScript()) {
2792     if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2793       return 100;
2794     if (Left.is(TT_JsTypeColon))
2795       return 35;
2796     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2797         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2798       return 100;
2799     // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2800     if (Left.opensScope() && Right.closesScope())
2801       return 200;
2802   }
2803 
2804   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2805     return 1;
2806   if (Right.is(tok::l_square)) {
2807     if (Style.Language == FormatStyle::LK_Proto)
2808       return 1;
2809     if (Left.is(tok::r_square))
2810       return 200;
2811     // Slightly prefer formatting local lambda definitions like functions.
2812     if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2813       return 35;
2814     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2815                        TT_ArrayInitializerLSquare,
2816                        TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2817       return 500;
2818   }
2819 
2820   if (Left.is(tok::coloncolon) ||
2821       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2822     return 500;
2823   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2824       Right.is(tok::kw_operator)) {
2825     if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2826       return 3;
2827     if (Left.is(TT_StartOfName))
2828       return 110;
2829     if (InFunctionDecl && Right.NestingLevel == 0)
2830       return Style.PenaltyReturnTypeOnItsOwnLine;
2831     return 200;
2832   }
2833   if (Right.is(TT_PointerOrReference))
2834     return 190;
2835   if (Right.is(TT_LambdaArrow))
2836     return 110;
2837   if (Left.is(tok::equal) && Right.is(tok::l_brace))
2838     return 160;
2839   if (Left.is(TT_CastRParen))
2840     return 100;
2841   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2842     return 5000;
2843   if (Left.is(tok::comment))
2844     return 1000;
2845 
2846   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2847                    TT_CtorInitializerColon))
2848     return 2;
2849 
2850   if (Right.isMemberAccess()) {
2851     // Breaking before the "./->" of a chained call/member access is reasonably
2852     // cheap, as formatting those with one call per line is generally
2853     // desirable. In particular, it should be cheaper to break before the call
2854     // than it is to break inside a call's parameters, which could lead to weird
2855     // "hanging" indents. The exception is the very last "./->" to support this
2856     // frequent pattern:
2857     //
2858     //   aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2859     //       dddddddd);
2860     //
2861     // which might otherwise be blown up onto many lines. Here, clang-format
2862     // won't produce "hanging" indents anyway as there is no other trailing
2863     // call.
2864     //
2865     // Also apply higher penalty is not a call as that might lead to a wrapping
2866     // like:
2867     //
2868     //   aaaaaaa
2869     //       .aaaaaaaaa.bbbbbbbb(cccccccc);
2870     return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2871                ? 150
2872                : 35;
2873   }
2874 
2875   if (Right.is(TT_TrailingAnnotation) &&
2876       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2877     // Moving trailing annotations to the next line is fine for ObjC method
2878     // declarations.
2879     if (Line.startsWith(TT_ObjCMethodSpecifier))
2880       return 10;
2881     // Generally, breaking before a trailing annotation is bad unless it is
2882     // function-like. It seems to be especially preferable to keep standard
2883     // annotations (i.e. "const", "final" and "override") on the same line.
2884     // Use a slightly higher penalty after ")" so that annotations like
2885     // "const override" are kept together.
2886     bool is_short_annotation = Right.TokenText.size() < 10;
2887     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2888   }
2889 
2890   // In for-loops, prefer breaking at ',' and ';'.
2891   if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2892     return 4;
2893 
2894   // In Objective-C method expressions, prefer breaking before "param:" over
2895   // breaking after it.
2896   if (Right.is(TT_SelectorName))
2897     return 0;
2898   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2899     return Line.MightBeFunctionDecl ? 50 : 500;
2900 
2901   // In Objective-C type declarations, avoid breaking after the category's
2902   // open paren (we'll prefer breaking after the protocol list's opening
2903   // angle bracket, if present).
2904   if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
2905       Left.Previous->isOneOf(tok::identifier, tok::greater))
2906     return 500;
2907 
2908   if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
2909     return Style.PenaltyBreakOpenParenthesis;
2910   if (Left.is(tok::l_paren) && InFunctionDecl &&
2911       Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2912     return 100;
2913   if (Left.is(tok::l_paren) && Left.Previous &&
2914       (Left.Previous->is(tok::kw_for) || Left.Previous->isIf()))
2915     return 1000;
2916   if (Left.is(tok::equal) && InFunctionDecl)
2917     return 110;
2918   if (Right.is(tok::r_brace))
2919     return 1;
2920   if (Left.is(TT_TemplateOpener))
2921     return 100;
2922   if (Left.opensScope()) {
2923     // If we aren't aligning after opening parens/braces we can always break
2924     // here unless the style does not want us to place all arguments on the
2925     // next line.
2926     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign &&
2927         (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine))
2928       return 0;
2929     if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
2930       return 19;
2931     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2932                                    : 19;
2933   }
2934   if (Left.is(TT_JavaAnnotation))
2935     return 50;
2936 
2937   if (Left.is(TT_UnaryOperator))
2938     return 60;
2939   if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2940       Left.Previous->isLabelString() &&
2941       (Left.NextOperator || Left.OperatorIndex != 0))
2942     return 50;
2943   if (Right.is(tok::plus) && Left.isLabelString() &&
2944       (Right.NextOperator || Right.OperatorIndex != 0))
2945     return 25;
2946   if (Left.is(tok::comma))
2947     return 1;
2948   if (Right.is(tok::lessless) && Left.isLabelString() &&
2949       (Right.NextOperator || Right.OperatorIndex != 1))
2950     return 25;
2951   if (Right.is(tok::lessless)) {
2952     // Breaking at a << is really cheap.
2953     if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2954       // Slightly prefer to break before the first one in log-like statements.
2955       return 2;
2956     return 1;
2957   }
2958   if (Left.ClosesTemplateDeclaration)
2959     return Style.PenaltyBreakTemplateDeclaration;
2960   if (Left.ClosesRequiresClause)
2961     return 0;
2962   if (Left.is(TT_ConditionalExpr))
2963     return prec::Conditional;
2964   prec::Level Level = Left.getPrecedence();
2965   if (Level == prec::Unknown)
2966     Level = Right.getPrecedence();
2967   if (Level == prec::Assignment)
2968     return Style.PenaltyBreakAssignment;
2969   if (Level != prec::Unknown)
2970     return Level;
2971 
2972   return 3;
2973 }
2974 
2975 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
2976   if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
2977     return true;
2978   if (Right.is(TT_OverloadedOperatorLParen) &&
2979       Style.SpaceBeforeParensOptions.AfterOverloadedOperator)
2980     return true;
2981   if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
2982       Right.ParameterCount > 0)
2983     return true;
2984   return false;
2985 }
2986 
2987 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2988                                           const FormatToken &Left,
2989                                           const FormatToken &Right) {
2990   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2991     return true;
2992   if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon))
2993     return false;
2994   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2995     return true;
2996   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2997       Left.Tok.getObjCKeywordID() == tok::objc_property)
2998     return true;
2999   if (Right.is(tok::hashhash))
3000     return Left.is(tok::hash);
3001   if (Left.isOneOf(tok::hashhash, tok::hash))
3002     return Right.is(tok::hash);
3003   if ((Left.is(tok::l_paren) && Right.is(tok::r_paren)) ||
3004       (Left.is(tok::l_brace) && Left.isNot(BK_Block) &&
3005        Right.is(tok::r_brace) && Right.isNot(BK_Block)))
3006     return Style.SpaceInEmptyParentheses;
3007   if (Style.SpacesInConditionalStatement) {
3008     if (Left.is(tok::l_paren) && Left.Previous &&
3009         isKeywordWithCondition(*Left.Previous))
3010       return true;
3011     if (Right.is(tok::r_paren) && Right.MatchingParen &&
3012         Right.MatchingParen->Previous &&
3013         isKeywordWithCondition(*Right.MatchingParen->Previous))
3014       return true;
3015   }
3016 
3017   // auto{x} auto(x)
3018   if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
3019     return false;
3020 
3021   // operator co_await(x)
3022   if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && Left.Previous &&
3023       Left.Previous->is(tok::kw_operator))
3024     return false;
3025   // co_await (x), co_yield (x), co_return (x)
3026   if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) &&
3027       Right.isNot(tok::semi))
3028     return true;
3029 
3030   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
3031     return (Right.is(TT_CastRParen) ||
3032             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
3033                ? Style.SpacesInCStyleCastParentheses
3034                : Style.SpacesInParentheses;
3035   if (Right.isOneOf(tok::semi, tok::comma))
3036     return false;
3037   if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
3038     bool IsLightweightGeneric = Right.MatchingParen &&
3039                                 Right.MatchingParen->Next &&
3040                                 Right.MatchingParen->Next->is(tok::colon);
3041     return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
3042   }
3043   if (Right.is(tok::less) && Left.is(tok::kw_template))
3044     return Style.SpaceAfterTemplateKeyword;
3045   if (Left.isOneOf(tok::exclaim, tok::tilde))
3046     return false;
3047   if (Left.is(tok::at) &&
3048       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
3049                     tok::numeric_constant, tok::l_paren, tok::l_brace,
3050                     tok::kw_true, tok::kw_false))
3051     return false;
3052   if (Left.is(tok::colon))
3053     return !Left.is(TT_ObjCMethodExpr);
3054   if (Left.is(tok::coloncolon))
3055     return false;
3056   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
3057     if (Style.Language == FormatStyle::LK_TextProto ||
3058         (Style.Language == FormatStyle::LK_Proto &&
3059          (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
3060       // Format empty list as `<>`.
3061       if (Left.is(tok::less) && Right.is(tok::greater))
3062         return false;
3063       return !Style.Cpp11BracedListStyle;
3064     }
3065     return false;
3066   }
3067   if (Right.is(tok::ellipsis))
3068     return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
3069                                     Left.Previous->is(tok::kw_case));
3070   if (Left.is(tok::l_square) && Right.is(tok::amp))
3071     return Style.SpacesInSquareBrackets;
3072   if (Right.is(TT_PointerOrReference)) {
3073     if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
3074       if (!Left.MatchingParen)
3075         return true;
3076       FormatToken *TokenBeforeMatchingParen =
3077           Left.MatchingParen->getPreviousNonComment();
3078       if (!TokenBeforeMatchingParen || !Left.is(TT_TypeDeclarationParen))
3079         return true;
3080     }
3081     // Add a space if the previous token is a pointer qualifier or the closing
3082     // parenthesis of __attribute__(()) expression and the style requires spaces
3083     // after pointer qualifiers.
3084     if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After ||
3085          Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
3086         (Left.is(TT_AttributeParen) || Left.canBePointerOrReferenceQualifier()))
3087       return true;
3088     if (Left.Tok.isLiteral())
3089       return true;
3090     // for (auto a = 0, b = 0; const auto & c : {1, 2, 3})
3091     if (Left.isTypeOrIdentifier() && Right.Next && Right.Next->Next &&
3092         Right.Next->Next->is(TT_RangeBasedForLoopColon))
3093       return getTokenPointerOrReferenceAlignment(Right) !=
3094              FormatStyle::PAS_Left;
3095     return !Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
3096            (getTokenPointerOrReferenceAlignment(Right) !=
3097                 FormatStyle::PAS_Left ||
3098             (Line.IsMultiVariableDeclStmt &&
3099              (Left.NestingLevel == 0 ||
3100               (Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
3101   }
3102   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
3103       (!Left.is(TT_PointerOrReference) ||
3104        (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right &&
3105         !Line.IsMultiVariableDeclStmt)))
3106     return true;
3107   if (Left.is(TT_PointerOrReference)) {
3108     // Add a space if the next token is a pointer qualifier and the style
3109     // requires spaces before pointer qualifiers.
3110     if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before ||
3111          Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
3112         Right.canBePointerOrReferenceQualifier())
3113       return true;
3114     // & 1
3115     if (Right.Tok.isLiteral())
3116       return true;
3117     // & /* comment
3118     if (Right.is(TT_BlockComment))
3119       return true;
3120     // foo() -> const Bar * override/final
3121     if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
3122         !Right.is(TT_StartOfName))
3123       return true;
3124     // & {
3125     if (Right.is(tok::l_brace) && Right.is(BK_Block))
3126       return true;
3127     // for (auto a = 0, b = 0; const auto& c : {1, 2, 3})
3128     if (Left.Previous && Left.Previous->isTypeOrIdentifier() && Right.Next &&
3129         Right.Next->is(TT_RangeBasedForLoopColon))
3130       return getTokenPointerOrReferenceAlignment(Left) !=
3131              FormatStyle::PAS_Right;
3132     if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
3133                       tok::l_paren))
3134       return false;
3135     if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right)
3136       return false;
3137     // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone,
3138     // because it does not take into account nested scopes like lambdas.
3139     // In multi-variable declaration statements, attach */& to the variable
3140     // independently of the style. However, avoid doing it if we are in a nested
3141     // scope, e.g. lambda. We still need to special-case statements with
3142     // initializers.
3143     if (Line.IsMultiVariableDeclStmt &&
3144         (Left.NestingLevel == Line.First->NestingLevel ||
3145          ((Left.NestingLevel == Line.First->NestingLevel + 1) &&
3146           startsWithInitStatement(Line))))
3147       return false;
3148     return Left.Previous && !Left.Previous->isOneOf(
3149                                 tok::l_paren, tok::coloncolon, tok::l_square);
3150   }
3151   // Ensure right pointer alignment with ellipsis e.g. int *...P
3152   if (Left.is(tok::ellipsis) && Left.Previous &&
3153       Left.Previous->isOneOf(tok::star, tok::amp, tok::ampamp))
3154     return Style.PointerAlignment != FormatStyle::PAS_Right;
3155 
3156   if (Right.is(tok::star) && Left.is(tok::l_paren))
3157     return false;
3158   if (Left.is(tok::star) && Right.isOneOf(tok::star, tok::amp, tok::ampamp))
3159     return false;
3160   if (Right.isOneOf(tok::star, tok::amp, tok::ampamp)) {
3161     const FormatToken *Previous = &Left;
3162     while (Previous && !Previous->is(tok::kw_operator)) {
3163       if (Previous->is(tok::identifier) || Previous->isSimpleTypeSpecifier()) {
3164         Previous = Previous->getPreviousNonComment();
3165         continue;
3166       }
3167       if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) {
3168         Previous = Previous->MatchingParen->getPreviousNonComment();
3169         continue;
3170       }
3171       if (Previous->is(tok::coloncolon)) {
3172         Previous = Previous->getPreviousNonComment();
3173         continue;
3174       }
3175       break;
3176     }
3177     // Space between the type and the * in:
3178     //   operator void*()
3179     //   operator char*()
3180     //   operator void const*()
3181     //   operator void volatile*()
3182     //   operator /*comment*/ const char*()
3183     //   operator volatile /*comment*/ char*()
3184     //   operator Foo*()
3185     //   operator C<T>*()
3186     //   operator std::Foo*()
3187     //   operator C<T>::D<U>*()
3188     // dependent on PointerAlignment style.
3189     if (Previous) {
3190       if (Previous->endsSequence(tok::kw_operator))
3191         return Style.PointerAlignment != FormatStyle::PAS_Left;
3192       if (Previous->is(tok::kw_const) || Previous->is(tok::kw_volatile))
3193         return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
3194                (Style.SpaceAroundPointerQualifiers ==
3195                 FormatStyle::SAPQ_After) ||
3196                (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
3197     }
3198   }
3199   const auto SpaceRequiredForArrayInitializerLSquare =
3200       [](const FormatToken &LSquareTok, const FormatStyle &Style) {
3201         return Style.SpacesInContainerLiterals ||
3202                ((Style.Language == FormatStyle::LK_Proto ||
3203                  Style.Language == FormatStyle::LK_TextProto) &&
3204                 !Style.Cpp11BracedListStyle &&
3205                 LSquareTok.endsSequence(tok::l_square, tok::colon,
3206                                         TT_SelectorName));
3207       };
3208   if (Left.is(tok::l_square))
3209     return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
3210             SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
3211            (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare,
3212                          TT_LambdaLSquare) &&
3213             Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
3214   if (Right.is(tok::r_square))
3215     return Right.MatchingParen &&
3216            ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
3217              SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
3218                                                      Style)) ||
3219             (Style.SpacesInSquareBrackets &&
3220              Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
3221                                           TT_StructuredBindingLSquare,
3222                                           TT_LambdaLSquare)) ||
3223             Right.MatchingParen->is(TT_AttributeParen));
3224   if (Right.is(tok::l_square) &&
3225       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
3226                      TT_DesignatedInitializerLSquare,
3227                      TT_StructuredBindingLSquare, TT_AttributeSquare) &&
3228       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral) &&
3229       !(!Left.is(tok::r_square) && Style.SpaceBeforeSquareBrackets &&
3230         Right.is(TT_ArraySubscriptLSquare)))
3231     return false;
3232   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
3233     return !Left.Children.empty(); // No spaces in "{}".
3234   if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
3235       (Right.is(tok::r_brace) && Right.MatchingParen &&
3236        Right.MatchingParen->isNot(BK_Block)))
3237     return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true;
3238   if (Left.is(TT_BlockComment))
3239     // No whitespace in x(/*foo=*/1), except for JavaScript.
3240     return Style.isJavaScript() || !Left.TokenText.endswith("=*/");
3241 
3242   // Space between template and attribute.
3243   // e.g. template <typename T> [[nodiscard]] ...
3244   if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeSquare))
3245     return true;
3246   // Space before parentheses common for all languages
3247   if (Right.is(tok::l_paren)) {
3248     if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen))
3249       return spaceRequiredBeforeParens(Right);
3250     if (Left.is(tok::kw_requires))
3251       return spaceRequiredBeforeParens(Right);
3252     if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
3253         (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
3254       return true;
3255     if (Left.is(TT_ForEachMacro))
3256       return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
3257              spaceRequiredBeforeParens(Right);
3258     if (Left.is(TT_IfMacro))
3259       return Style.SpaceBeforeParensOptions.AfterIfMacros ||
3260              spaceRequiredBeforeParens(Right);
3261     if (Line.Type == LT_ObjCDecl)
3262       return true;
3263     if (Left.is(tok::semi))
3264       return true;
3265     if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch,
3266                      tok::kw_case, TT_ForEachMacro, TT_ObjCForIn))
3267       return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3268              spaceRequiredBeforeParens(Right);
3269     if (Left.isIf(Line.Type != LT_PreprocessorDirective))
3270       return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3271              spaceRequiredBeforeParens(Right);
3272 
3273     // TODO add Operator overloading specific Options to
3274     // SpaceBeforeParensOptions
3275     if (Right.is(TT_OverloadedOperatorLParen))
3276       return spaceRequiredBeforeParens(Right);
3277     // Function declaration or definition
3278     if (Line.MightBeFunctionDecl && (Left.is(TT_FunctionDeclarationName))) {
3279       if (Line.mightBeFunctionDefinition())
3280         return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
3281                spaceRequiredBeforeParens(Right);
3282       else
3283         return Style.SpaceBeforeParensOptions.AfterFunctionDeclarationName ||
3284                spaceRequiredBeforeParens(Right);
3285     }
3286     // Lambda
3287     if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) &&
3288         Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare))
3289       return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
3290              spaceRequiredBeforeParens(Right);
3291     if (!Left.Previous || Left.Previous->isNot(tok::period)) {
3292       if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch))
3293         return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3294                spaceRequiredBeforeParens(Right);
3295       if (Left.isOneOf(tok::kw_new, tok::kw_delete) ||
3296           (Left.is(tok::r_square) && Left.MatchingParen &&
3297            Left.MatchingParen->Previous &&
3298            Left.MatchingParen->Previous->is(tok::kw_delete)))
3299         return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
3300                spaceRequiredBeforeParens(Right);
3301     }
3302     if (Line.Type != LT_PreprocessorDirective &&
3303         (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
3304          Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier()))
3305       return spaceRequiredBeforeParens(Right);
3306     return false;
3307   }
3308   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
3309     return false;
3310   if (Right.is(TT_UnaryOperator))
3311     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
3312            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
3313   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
3314                     tok::r_paren) ||
3315        Left.isSimpleTypeSpecifier()) &&
3316       Right.is(tok::l_brace) && Right.getNextNonComment() &&
3317       Right.isNot(BK_Block))
3318     return false;
3319   if (Left.is(tok::period) || Right.is(tok::period))
3320     return false;
3321   // u#str, U#str, L#str, u8#str
3322   // uR#str, UR#str, LR#str, u8R#str
3323   if (Right.is(tok::hash) && Left.is(tok::identifier) &&
3324       (Left.TokenText == "L" || Left.TokenText == "u" ||
3325        Left.TokenText == "U" || Left.TokenText == "u8" ||
3326        Left.TokenText == "LR" || Left.TokenText == "uR" ||
3327        Left.TokenText == "UR" || Left.TokenText == "u8R"))
3328     return false;
3329   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
3330       Left.MatchingParen->Previous &&
3331       (Left.MatchingParen->Previous->is(tok::period) ||
3332        Left.MatchingParen->Previous->is(tok::coloncolon)))
3333     // Java call to generic function with explicit type:
3334     // A.<B<C<...>>>DoSomething();
3335     // A::<B<C<...>>>DoSomething();  // With a Java 8 method reference.
3336     return false;
3337   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
3338     return false;
3339   if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
3340     // Objective-C dictionary literal -> no space after opening brace.
3341     return false;
3342   if (Right.is(tok::r_brace) && Right.MatchingParen &&
3343       Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
3344     // Objective-C dictionary literal -> no space before closing brace.
3345     return false;
3346   if (Right.getType() == TT_TrailingAnnotation &&
3347       Right.isOneOf(tok::amp, tok::ampamp) &&
3348       Left.isOneOf(tok::kw_const, tok::kw_volatile) &&
3349       (!Right.Next || Right.Next->is(tok::semi)))
3350     // Match const and volatile ref-qualifiers without any additional
3351     // qualifiers such as
3352     // void Fn() const &;
3353     return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
3354 
3355   return true;
3356 }
3357 
3358 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
3359                                          const FormatToken &Right) {
3360   const FormatToken &Left = *Right.Previous;
3361 
3362   // If the token is finalized don't touch it (as it could be in a
3363   // clang-format-off section).
3364   if (Left.Finalized)
3365     return Right.hasWhitespaceBefore();
3366 
3367   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
3368     return true; // Never ever merge two identifiers.
3369 
3370   // Leave a space between * and /* to avoid C4138 `comment end` found outside
3371   // of comment.
3372   if (Left.is(tok::star) && Right.is(tok::comment))
3373     return true;
3374 
3375   if (Style.isCpp()) {
3376     // Space between import <iostream>.
3377     // or import .....;
3378     if (Left.is(Keywords.kw_import) && Right.isOneOf(tok::less, tok::ellipsis))
3379       return true;
3380     // Space between `module :` and `import :`.
3381     if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) &&
3382         Right.is(TT_ModulePartitionColon))
3383       return true;
3384     // No space between import foo:bar but keep a space between import :bar;
3385     if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon))
3386       return false;
3387     // No space between :bar;
3388     if (Left.is(TT_ModulePartitionColon) &&
3389         Right.isOneOf(tok::identifier, tok::kw_private))
3390       return false;
3391     if (Left.is(tok::ellipsis) && Right.is(tok::identifier) &&
3392         Line.First->is(Keywords.kw_import))
3393       return false;
3394     // Space in __attribute__((attr)) ::type.
3395     if (Left.is(TT_AttributeParen) && Right.is(tok::coloncolon))
3396       return true;
3397 
3398     if (Left.is(tok::kw_operator))
3399       return Right.is(tok::coloncolon);
3400     if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) &&
3401         !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
3402       return true;
3403     if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) &&
3404         Right.is(TT_TemplateOpener))
3405       return true;
3406   } else if (Style.Language == FormatStyle::LK_Proto ||
3407              Style.Language == FormatStyle::LK_TextProto) {
3408     if (Right.is(tok::period) &&
3409         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
3410                      Keywords.kw_repeated, Keywords.kw_extend))
3411       return true;
3412     if (Right.is(tok::l_paren) &&
3413         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
3414       return true;
3415     if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
3416       return true;
3417     // Slashes occur in text protocol extension syntax: [type/type] { ... }.
3418     if (Left.is(tok::slash) || Right.is(tok::slash))
3419       return false;
3420     if (Left.MatchingParen &&
3421         Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
3422         Right.isOneOf(tok::l_brace, tok::less))
3423       return !Style.Cpp11BracedListStyle;
3424     // A percent is probably part of a formatting specification, such as %lld.
3425     if (Left.is(tok::percent))
3426       return false;
3427     // Preserve the existence of a space before a percent for cases like 0x%04x
3428     // and "%d %d"
3429     if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
3430       return Right.hasWhitespaceBefore();
3431   } else if (Style.isJson()) {
3432     if (Right.is(tok::colon))
3433       return false;
3434   } else if (Style.isCSharp()) {
3435     // Require spaces around '{' and  before '}' unless they appear in
3436     // interpolated strings. Interpolated strings are merged into a single token
3437     // so cannot have spaces inserted by this function.
3438 
3439     // No space between 'this' and '['
3440     if (Left.is(tok::kw_this) && Right.is(tok::l_square))
3441       return false;
3442 
3443     // No space between 'new' and '('
3444     if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
3445       return false;
3446 
3447     // Space before { (including space within '{ {').
3448     if (Right.is(tok::l_brace))
3449       return true;
3450 
3451     // Spaces inside braces.
3452     if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
3453       return true;
3454 
3455     if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
3456       return true;
3457 
3458     // Spaces around '=>'.
3459     if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow))
3460       return true;
3461 
3462     // No spaces around attribute target colons
3463     if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
3464       return false;
3465 
3466     // space between type and variable e.g. Dictionary<string,string> foo;
3467     if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
3468       return true;
3469 
3470     // spaces inside square brackets.
3471     if (Left.is(tok::l_square) || Right.is(tok::r_square))
3472       return Style.SpacesInSquareBrackets;
3473 
3474     // No space before ? in nullable types.
3475     if (Right.is(TT_CSharpNullable))
3476       return false;
3477 
3478     // No space before null forgiving '!'.
3479     if (Right.is(TT_NonNullAssertion))
3480       return false;
3481 
3482     // No space between consecutive commas '[,,]'.
3483     if (Left.is(tok::comma) && Right.is(tok::comma))
3484       return false;
3485 
3486     // space after var in `var (key, value)`
3487     if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
3488       return true;
3489 
3490     // space between keywords and paren e.g. "using ("
3491     if (Right.is(tok::l_paren))
3492       if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
3493                        Keywords.kw_lock))
3494         return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3495                spaceRequiredBeforeParens(Right);
3496 
3497     // space between method modifier and opening parenthesis of a tuple return
3498     // type
3499     if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
3500                      tok::kw_virtual, tok::kw_extern, tok::kw_static,
3501                      Keywords.kw_internal, Keywords.kw_abstract,
3502                      Keywords.kw_sealed, Keywords.kw_override,
3503                      Keywords.kw_async, Keywords.kw_unsafe) &&
3504         Right.is(tok::l_paren))
3505       return true;
3506   } else if (Style.isJavaScript()) {
3507     if (Left.is(TT_FatArrow))
3508       return true;
3509     // for await ( ...
3510     if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
3511         Left.Previous->is(tok::kw_for))
3512       return true;
3513     if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
3514         Right.MatchingParen) {
3515       const FormatToken *Next = Right.MatchingParen->getNextNonComment();
3516       // An async arrow function, for example: `x = async () => foo();`,
3517       // as opposed to calling a function called async: `x = async();`
3518       if (Next && Next->is(TT_FatArrow))
3519         return true;
3520     }
3521     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
3522         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
3523       return false;
3524     // In tagged template literals ("html`bar baz`"), there is no space between
3525     // the tag identifier and the template string.
3526     if (Keywords.IsJavaScriptIdentifier(Left,
3527                                         /* AcceptIdentifierName= */ false) &&
3528         Right.is(TT_TemplateString))
3529       return false;
3530     if (Right.is(tok::star) &&
3531         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
3532       return false;
3533     if (Right.isOneOf(tok::l_brace, tok::l_square) &&
3534         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
3535                      Keywords.kw_extends, Keywords.kw_implements))
3536       return true;
3537     if (Right.is(tok::l_paren)) {
3538       // JS methods can use some keywords as names (e.g. `delete()`).
3539       if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
3540         return false;
3541       // Valid JS method names can include keywords, e.g. `foo.delete()` or
3542       // `bar.instanceof()`. Recognize call positions by preceding period.
3543       if (Left.Previous && Left.Previous->is(tok::period) &&
3544           Left.Tok.getIdentifierInfo())
3545         return false;
3546       // Additional unary JavaScript operators that need a space after.
3547       if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
3548                        tok::kw_void))
3549         return true;
3550     }
3551     // `foo as const;` casts into a const type.
3552     if (Left.endsSequence(tok::kw_const, Keywords.kw_as))
3553       return false;
3554     if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
3555                       tok::kw_const) ||
3556          // "of" is only a keyword if it appears after another identifier
3557          // (e.g. as "const x of y" in a for loop), or after a destructuring
3558          // operation (const [x, y] of z, const {a, b} of c).
3559          (Left.is(Keywords.kw_of) && Left.Previous &&
3560           (Left.Previous->Tok.is(tok::identifier) ||
3561            Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
3562         (!Left.Previous || !Left.Previous->is(tok::period)))
3563       return true;
3564     if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
3565         Left.Previous->is(tok::period) && Right.is(tok::l_paren))
3566       return false;
3567     if (Left.is(Keywords.kw_as) &&
3568         Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
3569       return true;
3570     if (Left.is(tok::kw_default) && Left.Previous &&
3571         Left.Previous->is(tok::kw_export))
3572       return true;
3573     if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
3574       return true;
3575     if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
3576       return false;
3577     if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
3578       return false;
3579     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
3580         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
3581       return false;
3582     if (Left.is(tok::ellipsis))
3583       return false;
3584     if (Left.is(TT_TemplateCloser) &&
3585         !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
3586                        Keywords.kw_implements, Keywords.kw_extends))
3587       // Type assertions ('<type>expr') are not followed by whitespace. Other
3588       // locations that should have whitespace following are identified by the
3589       // above set of follower tokens.
3590       return false;
3591     if (Right.is(TT_NonNullAssertion))
3592       return false;
3593     if (Left.is(TT_NonNullAssertion) &&
3594         Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
3595       return true; // "x! as string", "x! in y"
3596   } else if (Style.Language == FormatStyle::LK_Java) {
3597     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
3598       return true;
3599     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
3600       return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3601              spaceRequiredBeforeParens(Right);
3602     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
3603                       tok::kw_protected) ||
3604          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
3605                       Keywords.kw_native)) &&
3606         Right.is(TT_TemplateOpener))
3607       return true;
3608   }
3609   if (Left.is(TT_ImplicitStringLiteral))
3610     return Right.hasWhitespaceBefore();
3611   if (Line.Type == LT_ObjCMethodDecl) {
3612     if (Left.is(TT_ObjCMethodSpecifier))
3613       return true;
3614     if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
3615       // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
3616       // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
3617       // method declaration.
3618       return false;
3619   }
3620   if (Line.Type == LT_ObjCProperty &&
3621       (Right.is(tok::equal) || Left.is(tok::equal)))
3622     return false;
3623 
3624   if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
3625       Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
3626     return true;
3627   if (Left.is(tok::comma) && !Right.is(TT_OverloadedOperatorLParen))
3628     return true;
3629   if (Right.is(tok::comma))
3630     return false;
3631   if (Right.is(TT_ObjCBlockLParen))
3632     return true;
3633   if (Right.is(TT_CtorInitializerColon))
3634     return Style.SpaceBeforeCtorInitializerColon;
3635   if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
3636     return false;
3637   if (Right.is(TT_RangeBasedForLoopColon) &&
3638       !Style.SpaceBeforeRangeBasedForLoopColon)
3639     return false;
3640   if (Left.is(TT_BitFieldColon))
3641     return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
3642            Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
3643   if (Right.is(tok::colon)) {
3644     if (Line.First->isOneOf(tok::kw_default, tok::kw_case))
3645       return Style.SpaceBeforeCaseColon;
3646     const FormatToken *Next = Right.getNextNonComment();
3647     if (!Next || Next->is(tok::semi))
3648       return false;
3649     if (Right.is(TT_ObjCMethodExpr))
3650       return false;
3651     if (Left.is(tok::question))
3652       return false;
3653     if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
3654       return false;
3655     if (Right.is(TT_DictLiteral))
3656       return Style.SpacesInContainerLiterals;
3657     if (Right.is(TT_AttributeColon))
3658       return false;
3659     if (Right.is(TT_CSharpNamedArgumentColon))
3660       return false;
3661     if (Right.is(TT_BitFieldColon))
3662       return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
3663              Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
3664     return true;
3665   }
3666   // Do not merge "- -" into "--".
3667   if ((Left.isOneOf(tok::minus, tok::minusminus) &&
3668        Right.isOneOf(tok::minus, tok::minusminus)) ||
3669       (Left.isOneOf(tok::plus, tok::plusplus) &&
3670        Right.isOneOf(tok::plus, tok::plusplus)))
3671     return true;
3672   if (Left.is(TT_UnaryOperator)) {
3673     if (!Right.is(tok::l_paren)) {
3674       // The alternative operators for ~ and ! are "compl" and "not".
3675       // If they are used instead, we do not want to combine them with
3676       // the token to the right, unless that is a left paren.
3677       if (Left.is(tok::exclaim) && Left.TokenText == "not")
3678         return true;
3679       if (Left.is(tok::tilde) && Left.TokenText == "compl")
3680         return true;
3681       // Lambda captures allow for a lone &, so "&]" needs to be properly
3682       // handled.
3683       if (Left.is(tok::amp) && Right.is(tok::r_square))
3684         return Style.SpacesInSquareBrackets;
3685     }
3686     return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
3687            Right.is(TT_BinaryOperator);
3688   }
3689 
3690   // If the next token is a binary operator or a selector name, we have
3691   // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
3692   if (Left.is(TT_CastRParen))
3693     return Style.SpaceAfterCStyleCast ||
3694            Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
3695 
3696   auto ShouldAddSpacesInAngles = [this, &Right]() {
3697     if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always)
3698       return true;
3699     if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave)
3700       return Right.hasWhitespaceBefore();
3701     return false;
3702   };
3703 
3704   if (Left.is(tok::greater) && Right.is(tok::greater)) {
3705     if (Style.Language == FormatStyle::LK_TextProto ||
3706         (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
3707       return !Style.Cpp11BracedListStyle;
3708     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
3709            ((Style.Standard < FormatStyle::LS_Cpp11) ||
3710             ShouldAddSpacesInAngles());
3711   }
3712   if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
3713       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
3714       (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
3715     return false;
3716   if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
3717       Right.getPrecedence() == prec::Assignment)
3718     return false;
3719   if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) &&
3720       (Left.is(tok::identifier) || Left.is(tok::kw_this)))
3721     return false;
3722   if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
3723     // Generally don't remove existing spaces between an identifier and "::".
3724     // The identifier might actually be a macro name such as ALWAYS_INLINE. If
3725     // this turns out to be too lenient, add analysis of the identifier itself.
3726     return Right.hasWhitespaceBefore();
3727   if (Right.is(tok::coloncolon) &&
3728       !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren))
3729     // Put a space between < and :: in vector< ::std::string >
3730     return (Left.is(TT_TemplateOpener) &&
3731             ((Style.Standard < FormatStyle::LS_Cpp11) ||
3732              ShouldAddSpacesInAngles())) ||
3733            !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
3734                           tok::kw___super, TT_TemplateOpener,
3735                           TT_TemplateCloser)) ||
3736            (Left.is(tok::l_paren) && Style.SpacesInParentheses);
3737   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
3738     return ShouldAddSpacesInAngles();
3739   // Space before TT_StructuredBindingLSquare.
3740   if (Right.is(TT_StructuredBindingLSquare))
3741     return !Left.isOneOf(tok::amp, tok::ampamp) ||
3742            getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right;
3743   // Space before & or && following a TT_StructuredBindingLSquare.
3744   if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
3745       Right.isOneOf(tok::amp, tok::ampamp))
3746     return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
3747   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
3748       (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
3749        !Right.is(tok::r_paren)))
3750     return true;
3751   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
3752       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
3753     return false;
3754   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
3755       Line.startsWith(tok::hash))
3756     return true;
3757   if (Right.is(TT_TrailingUnaryOperator))
3758     return false;
3759   if (Left.is(TT_RegexLiteral))
3760     return false;
3761   return spaceRequiredBetween(Line, Left, Right);
3762 }
3763 
3764 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
3765 static bool isAllmanBrace(const FormatToken &Tok) {
3766   return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
3767          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
3768 }
3769 
3770 // Returns 'true' if 'Tok' is a function argument.
3771 static bool IsFunctionArgument(const FormatToken &Tok) {
3772   return Tok.MatchingParen && Tok.MatchingParen->Next &&
3773          Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren);
3774 }
3775 
3776 static bool
3777 isItAnEmptyLambdaAllowed(const FormatToken &Tok,
3778                          FormatStyle::ShortLambdaStyle ShortLambdaOption) {
3779   return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
3780 }
3781 
3782 static bool isAllmanLambdaBrace(const FormatToken &Tok) {
3783   return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
3784          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
3785 }
3786 
3787 // Returns the first token on the line that is not a comment.
3788 static const FormatToken *getFirstNonComment(const AnnotatedLine &Line) {
3789   const FormatToken *Next = Line.First;
3790   if (!Next)
3791     return Next;
3792   if (Next->is(tok::comment))
3793     Next = Next->getNextNonComment();
3794   return Next;
3795 }
3796 
3797 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
3798                                      const FormatToken &Right) {
3799   const FormatToken &Left = *Right.Previous;
3800   if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
3801     return true;
3802 
3803   if (Style.isCSharp()) {
3804     if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) &&
3805         Style.BraceWrapping.AfterFunction)
3806       return true;
3807     if (Right.is(TT_CSharpNamedArgumentColon) ||
3808         Left.is(TT_CSharpNamedArgumentColon))
3809       return false;
3810     if (Right.is(TT_CSharpGenericTypeConstraint))
3811       return true;
3812     if (Right.Next && Right.Next->is(TT_FatArrow) &&
3813         (Right.is(tok::numeric_constant) ||
3814          (Right.is(tok::identifier) && Right.TokenText == "_")))
3815       return true;
3816 
3817     // Break after C# [...] and before public/protected/private/internal.
3818     if (Left.is(TT_AttributeSquare) && Left.is(tok::r_square) &&
3819         (Right.isAccessSpecifier(/*ColonRequired=*/false) ||
3820          Right.is(Keywords.kw_internal)))
3821       return true;
3822     // Break between ] and [ but only when there are really 2 attributes.
3823     if (Left.is(TT_AttributeSquare) && Right.is(TT_AttributeSquare) &&
3824         Left.is(tok::r_square) && Right.is(tok::l_square))
3825       return true;
3826 
3827   } else if (Style.isJavaScript()) {
3828     // FIXME: This might apply to other languages and token kinds.
3829     if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
3830         Left.Previous->is(tok::string_literal))
3831       return true;
3832     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
3833         Left.Previous && Left.Previous->is(tok::equal) &&
3834         Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
3835                             tok::kw_const) &&
3836         // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
3837         // above.
3838         !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
3839       // Object literals on the top level of a file are treated as "enum-style".
3840       // Each key/value pair is put on a separate line, instead of bin-packing.
3841       return true;
3842     if (Left.is(tok::l_brace) && Line.Level == 0 &&
3843         (Line.startsWith(tok::kw_enum) ||
3844          Line.startsWith(tok::kw_const, tok::kw_enum) ||
3845          Line.startsWith(tok::kw_export, tok::kw_enum) ||
3846          Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
3847       // JavaScript top-level enum key/value pairs are put on separate lines
3848       // instead of bin-packing.
3849       return true;
3850     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous &&
3851         Left.Previous->is(TT_FatArrow)) {
3852       // JS arrow function (=> {...}).
3853       switch (Style.AllowShortLambdasOnASingleLine) {
3854       case FormatStyle::SLS_All:
3855         return false;
3856       case FormatStyle::SLS_None:
3857         return true;
3858       case FormatStyle::SLS_Empty:
3859         return !Left.Children.empty();
3860       case FormatStyle::SLS_Inline:
3861         // allow one-lining inline (e.g. in function call args) and empty arrow
3862         // functions.
3863         return (Left.NestingLevel == 0 && Line.Level == 0) &&
3864                !Left.Children.empty();
3865       }
3866       llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
3867     }
3868 
3869     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
3870         !Left.Children.empty())
3871       // Support AllowShortFunctionsOnASingleLine for JavaScript.
3872       return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
3873              Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
3874              (Left.NestingLevel == 0 && Line.Level == 0 &&
3875               Style.AllowShortFunctionsOnASingleLine &
3876                   FormatStyle::SFS_InlineOnly);
3877   } else if (Style.Language == FormatStyle::LK_Java) {
3878     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
3879         Right.Next->is(tok::string_literal))
3880       return true;
3881   } else if (Style.Language == FormatStyle::LK_Cpp ||
3882              Style.Language == FormatStyle::LK_ObjC ||
3883              Style.Language == FormatStyle::LK_Proto ||
3884              Style.Language == FormatStyle::LK_TableGen ||
3885              Style.Language == FormatStyle::LK_TextProto) {
3886     if (Left.isStringLiteral() && Right.isStringLiteral())
3887       return true;
3888   }
3889 
3890   // Basic JSON newline processing.
3891   if (Style.isJson()) {
3892     // Always break after a JSON record opener.
3893     // {
3894     // }
3895     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace))
3896       return true;
3897     // Always break after a JSON array opener.
3898     // [
3899     // ]
3900     if (Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) &&
3901         !Right.is(tok::r_square))
3902       return true;
3903     // Always break after successive entries.
3904     // 1,
3905     // 2
3906     if (Left.is(tok::comma))
3907       return true;
3908   }
3909 
3910   // If the last token before a '}', ']', or ')' is a comma or a trailing
3911   // comment, the intention is to insert a line break after it in order to make
3912   // shuffling around entries easier. Import statements, especially in
3913   // JavaScript, can be an exception to this rule.
3914   if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
3915     const FormatToken *BeforeClosingBrace = nullptr;
3916     if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
3917          (Style.isJavaScript() && Left.is(tok::l_paren))) &&
3918         Left.isNot(BK_Block) && Left.MatchingParen)
3919       BeforeClosingBrace = Left.MatchingParen->Previous;
3920     else if (Right.MatchingParen &&
3921              (Right.MatchingParen->isOneOf(tok::l_brace,
3922                                            TT_ArrayInitializerLSquare) ||
3923               (Style.isJavaScript() && Right.MatchingParen->is(tok::l_paren))))
3924       BeforeClosingBrace = &Left;
3925     if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
3926                                BeforeClosingBrace->isTrailingComment()))
3927       return true;
3928   }
3929 
3930   if (Right.is(tok::comment))
3931     return Left.isNot(BK_BracedInit) && Left.isNot(TT_CtorInitializerColon) &&
3932            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
3933   if (Left.isTrailingComment())
3934     return true;
3935   if (Left.IsUnterminatedLiteral)
3936     return true;
3937   if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&
3938       Right.Next->is(tok::string_literal))
3939     return true;
3940   if (Right.is(TT_RequiresClause)) {
3941     switch (Style.RequiresClausePosition) {
3942     case FormatStyle::RCPS_OwnLine:
3943     case FormatStyle::RCPS_WithFollowing:
3944       return true;
3945     default:
3946       break;
3947     }
3948   }
3949   // Can break after template<> declaration
3950   if (Left.ClosesTemplateDeclaration && Left.MatchingParen &&
3951       Left.MatchingParen->NestingLevel == 0) {
3952     // Put concepts on the next line e.g.
3953     // template<typename T>
3954     // concept ...
3955     if (Right.is(tok::kw_concept))
3956       return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always;
3957     return Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes;
3958   }
3959   if (Left.ClosesRequiresClause) {
3960     switch (Style.RequiresClausePosition) {
3961     case FormatStyle::RCPS_OwnLine:
3962     case FormatStyle::RCPS_WithPreceding:
3963       return true;
3964     default:
3965       break;
3966     }
3967   }
3968   if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) {
3969     if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon &&
3970         (Left.is(TT_CtorInitializerComma) || Right.is(TT_CtorInitializerColon)))
3971       return true;
3972 
3973     if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
3974         Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma))
3975       return true;
3976   }
3977   if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine &&
3978       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3979       Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon))
3980     return true;
3981   // Break only if we have multiple inheritance.
3982   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
3983       Right.is(TT_InheritanceComma))
3984     return true;
3985   if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
3986       Left.is(TT_InheritanceComma))
3987     return true;
3988   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
3989     // Multiline raw string literals are special wrt. line breaks. The author
3990     // has made a deliberate choice and might have aligned the contents of the
3991     // string literal accordingly. Thus, we try keep existing line breaks.
3992     return Right.IsMultiline && Right.NewlinesBefore > 0;
3993   if ((Left.is(tok::l_brace) || (Left.is(tok::less) && Left.Previous &&
3994                                  Left.Previous->is(tok::equal))) &&
3995       Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
3996     // Don't put enums or option definitions onto single lines in protocol
3997     // buffers.
3998     return true;
3999   }
4000   if (Right.is(TT_InlineASMBrace))
4001     return Right.HasUnescapedNewline;
4002 
4003   if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
4004     auto FirstNonComment = getFirstNonComment(Line);
4005     bool AccessSpecifier =
4006         FirstNonComment &&
4007         FirstNonComment->isOneOf(Keywords.kw_internal, tok::kw_public,
4008                                  tok::kw_private, tok::kw_protected);
4009 
4010     if (Style.BraceWrapping.AfterEnum) {
4011       if (Line.startsWith(tok::kw_enum) ||
4012           Line.startsWith(tok::kw_typedef, tok::kw_enum))
4013         return true;
4014       // Ensure BraceWrapping for `public enum A {`.
4015       if (AccessSpecifier && FirstNonComment->Next &&
4016           FirstNonComment->Next->is(tok::kw_enum))
4017         return true;
4018     }
4019 
4020     // Ensure BraceWrapping for `public interface A {`.
4021     if (Style.BraceWrapping.AfterClass &&
4022         ((AccessSpecifier && FirstNonComment->Next &&
4023           FirstNonComment->Next->is(Keywords.kw_interface)) ||
4024          Line.startsWith(Keywords.kw_interface)))
4025       return true;
4026 
4027     return (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
4028            (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
4029   }
4030 
4031   if (Left.is(TT_ObjCBlockLBrace) &&
4032       Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
4033     return true;
4034 
4035   // Ensure wrapping after __attribute__((XX)) and @interface etc.
4036   if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
4037     return true;
4038 
4039   if (Left.is(TT_LambdaLBrace)) {
4040     if (IsFunctionArgument(Left) &&
4041         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
4042       return false;
4043 
4044     if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
4045         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
4046         (!Left.Children.empty() &&
4047          Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty))
4048       return true;
4049   }
4050 
4051   if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) &&
4052       Left.isOneOf(tok::star, tok::amp, tok::ampamp, TT_TemplateCloser))
4053     return true;
4054 
4055   // Put multiple Java annotation on a new line.
4056   if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
4057       Left.is(TT_LeadingJavaAnnotation) &&
4058       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
4059       (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
4060     return true;
4061 
4062   if (Right.is(TT_ProtoExtensionLSquare))
4063     return true;
4064 
4065   // In text proto instances if a submessage contains at least 2 entries and at
4066   // least one of them is a submessage, like A { ... B { ... } ... },
4067   // put all of the entries of A on separate lines by forcing the selector of
4068   // the submessage B to be put on a newline.
4069   //
4070   // Example: these can stay on one line:
4071   // a { scalar_1: 1 scalar_2: 2 }
4072   // a { b { key: value } }
4073   //
4074   // and these entries need to be on a new line even if putting them all in one
4075   // line is under the column limit:
4076   // a {
4077   //   scalar: 1
4078   //   b { key: value }
4079   // }
4080   //
4081   // We enforce this by breaking before a submessage field that has previous
4082   // siblings, *and* breaking before a field that follows a submessage field.
4083   //
4084   // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
4085   // the TT_SelectorName there, but we don't want to break inside the brackets.
4086   //
4087   // Another edge case is @submessage { key: value }, which is a common
4088   // substitution placeholder. In this case we want to keep `@` and `submessage`
4089   // together.
4090   //
4091   // We ensure elsewhere that extensions are always on their own line.
4092   if ((Style.Language == FormatStyle::LK_Proto ||
4093        Style.Language == FormatStyle::LK_TextProto) &&
4094       Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
4095     // Keep `@submessage` together in:
4096     // @submessage { key: value }
4097     if (Left.is(tok::at))
4098       return false;
4099     // Look for the scope opener after selector in cases like:
4100     // selector { ...
4101     // selector: { ...
4102     // selector: @base { ...
4103     FormatToken *LBrace = Right.Next;
4104     if (LBrace && LBrace->is(tok::colon)) {
4105       LBrace = LBrace->Next;
4106       if (LBrace && LBrace->is(tok::at)) {
4107         LBrace = LBrace->Next;
4108         if (LBrace)
4109           LBrace = LBrace->Next;
4110       }
4111     }
4112     if (LBrace &&
4113         // The scope opener is one of {, [, <:
4114         // selector { ... }
4115         // selector [ ... ]
4116         // selector < ... >
4117         //
4118         // In case of selector { ... }, the l_brace is TT_DictLiteral.
4119         // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
4120         // so we check for immediately following r_brace.
4121         ((LBrace->is(tok::l_brace) &&
4122           (LBrace->is(TT_DictLiteral) ||
4123            (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
4124          LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
4125       // If Left.ParameterCount is 0, then this submessage entry is not the
4126       // first in its parent submessage, and we want to break before this entry.
4127       // If Left.ParameterCount is greater than 0, then its parent submessage
4128       // might contain 1 or more entries and we want to break before this entry
4129       // if it contains at least 2 entries. We deal with this case later by
4130       // detecting and breaking before the next entry in the parent submessage.
4131       if (Left.ParameterCount == 0)
4132         return true;
4133       // However, if this submessage is the first entry in its parent
4134       // submessage, Left.ParameterCount might be 1 in some cases.
4135       // We deal with this case later by detecting an entry
4136       // following a closing paren of this submessage.
4137     }
4138 
4139     // If this is an entry immediately following a submessage, it will be
4140     // preceded by a closing paren of that submessage, like in:
4141     //     left---.  .---right
4142     //            v  v
4143     // sub: { ... } key: value
4144     // If there was a comment between `}` an `key` above, then `key` would be
4145     // put on a new line anyways.
4146     if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
4147       return true;
4148   }
4149 
4150   // Deal with lambda arguments in C++ - we want consistent line breaks whether
4151   // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
4152   // as aggressive line breaks are placed when the lambda is not the last arg.
4153   if ((Style.Language == FormatStyle::LK_Cpp ||
4154        Style.Language == FormatStyle::LK_ObjC) &&
4155       Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
4156       !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
4157     // Multiple lambdas in the same function call force line breaks.
4158     if (Left.BlockParameterCount > 1)
4159       return true;
4160 
4161     // A lambda followed by another arg forces a line break.
4162     if (!Left.Role)
4163       return false;
4164     auto Comma = Left.Role->lastComma();
4165     if (!Comma)
4166       return false;
4167     auto Next = Comma->getNextNonComment();
4168     if (!Next)
4169       return false;
4170     if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
4171       return true;
4172   }
4173 
4174   return false;
4175 }
4176 
4177 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
4178                                     const FormatToken &Right) {
4179   const FormatToken &Left = *Right.Previous;
4180   // Language-specific stuff.
4181   if (Style.isCSharp()) {
4182     if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
4183         Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon))
4184       return false;
4185     // Only break after commas for generic type constraints.
4186     if (Line.First->is(TT_CSharpGenericTypeConstraint))
4187       return Left.is(TT_CSharpGenericTypeConstraintComma);
4188     // Keep nullable operators attached to their identifiers.
4189     if (Right.is(TT_CSharpNullable))
4190       return false;
4191   } else if (Style.Language == FormatStyle::LK_Java) {
4192     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
4193                      Keywords.kw_implements))
4194       return false;
4195     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
4196                       Keywords.kw_implements))
4197       return true;
4198   } else if (Style.isJavaScript()) {
4199     const FormatToken *NonComment = Right.getPreviousNonComment();
4200     if (NonComment &&
4201         NonComment->isOneOf(
4202             tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
4203             tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
4204             tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
4205             Keywords.kw_readonly, Keywords.kw_override, Keywords.kw_abstract,
4206             Keywords.kw_get, Keywords.kw_set, Keywords.kw_async,
4207             Keywords.kw_await))
4208       return false; // Otherwise automatic semicolon insertion would trigger.
4209     if (Right.NestingLevel == 0 &&
4210         (Left.Tok.getIdentifierInfo() ||
4211          Left.isOneOf(tok::r_square, tok::r_paren)) &&
4212         Right.isOneOf(tok::l_square, tok::l_paren))
4213       return false; // Otherwise automatic semicolon insertion would trigger.
4214     if (NonComment && NonComment->is(tok::identifier) &&
4215         NonComment->TokenText == "asserts")
4216       return false;
4217     if (Left.is(TT_FatArrow) && Right.is(tok::l_brace))
4218       return false;
4219     if (Left.is(TT_JsTypeColon))
4220       return true;
4221     // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
4222     if (Left.is(tok::exclaim) && Right.is(tok::colon))
4223       return false;
4224     // Look for is type annotations like:
4225     // function f(): a is B { ... }
4226     // Do not break before is in these cases.
4227     if (Right.is(Keywords.kw_is)) {
4228       const FormatToken *Next = Right.getNextNonComment();
4229       // If `is` is followed by a colon, it's likely that it's a dict key, so
4230       // ignore it for this check.
4231       // For example this is common in Polymer:
4232       // Polymer({
4233       //   is: 'name',
4234       //   ...
4235       // });
4236       if (!Next || !Next->is(tok::colon))
4237         return false;
4238     }
4239     if (Left.is(Keywords.kw_in))
4240       return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
4241     if (Right.is(Keywords.kw_in))
4242       return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
4243     if (Right.is(Keywords.kw_as))
4244       return false; // must not break before as in 'x as type' casts
4245     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
4246       // extends and infer can appear as keywords in conditional types:
4247       //   https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
4248       // do not break before them, as the expressions are subject to ASI.
4249       return false;
4250     }
4251     if (Left.is(Keywords.kw_as))
4252       return true;
4253     if (Left.is(TT_NonNullAssertion))
4254       return true;
4255     if (Left.is(Keywords.kw_declare) &&
4256         Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
4257                       Keywords.kw_function, tok::kw_class, tok::kw_enum,
4258                       Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
4259                       Keywords.kw_let, tok::kw_const))
4260       // See grammar for 'declare' statements at:
4261       // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10
4262       return false;
4263     if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
4264         Right.isOneOf(tok::identifier, tok::string_literal))
4265       return false; // must not break in "module foo { ...}"
4266     if (Right.is(TT_TemplateString) && Right.closesScope())
4267       return false;
4268     // Don't split tagged template literal so there is a break between the tag
4269     // identifier and template string.
4270     if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
4271       return false;
4272     if (Left.is(TT_TemplateString) && Left.opensScope())
4273       return true;
4274   }
4275 
4276   if (Left.is(tok::at))
4277     return false;
4278   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
4279     return false;
4280   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
4281     return !Right.is(tok::l_paren);
4282   if (Right.is(TT_PointerOrReference))
4283     return Line.IsMultiVariableDeclStmt ||
4284            (getTokenPointerOrReferenceAlignment(Right) ==
4285                 FormatStyle::PAS_Right &&
4286             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
4287   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
4288       Right.is(tok::kw_operator))
4289     return true;
4290   if (Left.is(TT_PointerOrReference))
4291     return false;
4292   if (Right.isTrailingComment())
4293     // We rely on MustBreakBefore being set correctly here as we should not
4294     // change the "binding" behavior of a comment.
4295     // The first comment in a braced lists is always interpreted as belonging to
4296     // the first list element. Otherwise, it should be placed outside of the
4297     // list.
4298     return Left.is(BK_BracedInit) ||
4299            (Left.is(TT_CtorInitializerColon) &&
4300             Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
4301   if (Left.is(tok::question) && Right.is(tok::colon))
4302     return false;
4303   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
4304     return Style.BreakBeforeTernaryOperators;
4305   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
4306     return !Style.BreakBeforeTernaryOperators;
4307   if (Left.is(TT_InheritanceColon))
4308     return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
4309   if (Right.is(TT_InheritanceColon))
4310     return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
4311   if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
4312       Left.isNot(TT_SelectorName))
4313     return true;
4314 
4315   if (Right.is(tok::colon) &&
4316       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
4317     return false;
4318   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
4319     if (Style.Language == FormatStyle::LK_Proto ||
4320         Style.Language == FormatStyle::LK_TextProto) {
4321       if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
4322         return false;
4323       // Prevent cases like:
4324       //
4325       // submessage:
4326       //     { key: valueeeeeeeeeeee }
4327       //
4328       // when the snippet does not fit into one line.
4329       // Prefer:
4330       //
4331       // submessage: {
4332       //   key: valueeeeeeeeeeee
4333       // }
4334       //
4335       // instead, even if it is longer by one line.
4336       //
4337       // Note that this allows allows the "{" to go over the column limit
4338       // when the column limit is just between ":" and "{", but that does
4339       // not happen too often and alternative formattings in this case are
4340       // not much better.
4341       //
4342       // The code covers the cases:
4343       //
4344       // submessage: { ... }
4345       // submessage: < ... >
4346       // repeated: [ ... ]
4347       if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
4348            Right.is(TT_DictLiteral)) ||
4349           Right.is(TT_ArrayInitializerLSquare))
4350         return false;
4351     }
4352     return true;
4353   }
4354   if (Right.is(tok::r_square) && Right.MatchingParen &&
4355       Right.MatchingParen->is(TT_ProtoExtensionLSquare))
4356     return false;
4357   if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
4358                                     Right.Next->is(TT_ObjCMethodExpr)))
4359     return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
4360   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
4361     return true;
4362   if (Right.is(tok::kw_concept))
4363     return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never;
4364   if (Right.is(TT_RequiresClause))
4365     return true;
4366   if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
4367     return true;
4368   if (Left.ClosesRequiresClause)
4369     return true;
4370   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
4371                     TT_OverloadedOperator))
4372     return false;
4373   if (Left.is(TT_RangeBasedForLoopColon))
4374     return true;
4375   if (Right.is(TT_RangeBasedForLoopColon))
4376     return false;
4377   if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
4378     return true;
4379   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
4380       Left.is(tok::kw_operator))
4381     return false;
4382   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
4383       Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
4384     return false;
4385   if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
4386       !Style.Cpp11BracedListStyle)
4387     return false;
4388   if (Left.is(tok::l_paren) &&
4389       Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen))
4390     return false;
4391   if (Left.is(tok::l_paren) && Left.Previous &&
4392       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
4393     return false;
4394   if (Right.is(TT_ImplicitStringLiteral))
4395     return false;
4396 
4397   if (Right.is(TT_TemplateCloser))
4398     return false;
4399   if (Right.is(tok::r_square) && Right.MatchingParen &&
4400       Right.MatchingParen->is(TT_LambdaLSquare))
4401     return false;
4402 
4403   // We only break before r_brace if there was a corresponding break before
4404   // the l_brace, which is tracked by BreakBeforeClosingBrace.
4405   if (Right.is(tok::r_brace))
4406     return Right.MatchingParen && Right.MatchingParen->is(BK_Block);
4407 
4408   // We only break before r_paren if we're in a block indented context.
4409   if (Right.is(tok::r_paren)) {
4410     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) {
4411       return Right.MatchingParen &&
4412              !(Right.MatchingParen->Previous &&
4413                (Right.MatchingParen->Previous->is(tok::kw_for) ||
4414                 Right.MatchingParen->Previous->isIf()));
4415     }
4416 
4417     return false;
4418   }
4419 
4420   // Allow breaking after a trailing annotation, e.g. after a method
4421   // declaration.
4422   if (Left.is(TT_TrailingAnnotation))
4423     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
4424                           tok::less, tok::coloncolon);
4425 
4426   if (Right.is(tok::kw___attribute) ||
4427       (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
4428     return !Left.is(TT_AttributeSquare);
4429 
4430   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
4431     return true;
4432 
4433   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
4434     return true;
4435 
4436   if (Left.is(TT_CtorInitializerColon))
4437     return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
4438   if (Right.is(TT_CtorInitializerColon))
4439     return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
4440   if (Left.is(TT_CtorInitializerComma) &&
4441       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
4442     return false;
4443   if (Right.is(TT_CtorInitializerComma) &&
4444       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
4445     return true;
4446   if (Left.is(TT_InheritanceComma) &&
4447       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
4448     return false;
4449   if (Right.is(TT_InheritanceComma) &&
4450       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
4451     return true;
4452   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
4453       (Left.is(tok::less) && Right.is(tok::less)))
4454     return false;
4455   if (Right.is(TT_BinaryOperator) &&
4456       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
4457       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
4458        Right.getPrecedence() != prec::Assignment))
4459     return true;
4460   if (Left.is(TT_ArrayInitializerLSquare))
4461     return true;
4462   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
4463     return true;
4464   if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
4465       !Left.isOneOf(tok::arrowstar, tok::lessless) &&
4466       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
4467       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
4468        Left.getPrecedence() == prec::Assignment))
4469     return true;
4470   if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
4471       (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
4472     return false;
4473 
4474   auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
4475   if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) {
4476     if (isAllmanLambdaBrace(Left))
4477       return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption);
4478     if (isAllmanLambdaBrace(Right))
4479       return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption);
4480   }
4481 
4482   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
4483                       tok::kw_class, tok::kw_struct, tok::comment) ||
4484          Right.isMemberAccess() ||
4485          Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
4486                        tok::colon, tok::l_square, tok::at) ||
4487          (Left.is(tok::r_paren) &&
4488           Right.isOneOf(tok::identifier, tok::kw_const)) ||
4489          (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
4490          (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
4491 }
4492 
4493 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
4494   llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
4495   const FormatToken *Tok = Line.First;
4496   while (Tok) {
4497     llvm::errs() << " M=" << Tok->MustBreakBefore
4498                  << " C=" << Tok->CanBreakBefore
4499                  << " T=" << getTokenTypeName(Tok->getType())
4500                  << " S=" << Tok->SpacesRequiredBefore
4501                  << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
4502                  << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
4503                  << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
4504                  << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
4505     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
4506       llvm::errs() << Tok->FakeLParens[i] << "/";
4507     llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
4508     llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
4509     llvm::errs() << " Text='" << Tok->TokenText << "'\n";
4510     if (!Tok->Next)
4511       assert(Tok == Line.Last);
4512     Tok = Tok->Next;
4513   }
4514   llvm::errs() << "----\n";
4515 }
4516 
4517 FormatStyle::PointerAlignmentStyle
4518 TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) {
4519   assert(Reference.isOneOf(tok::amp, tok::ampamp));
4520   switch (Style.ReferenceAlignment) {
4521   case FormatStyle::RAS_Pointer:
4522     return Style.PointerAlignment;
4523   case FormatStyle::RAS_Left:
4524     return FormatStyle::PAS_Left;
4525   case FormatStyle::RAS_Right:
4526     return FormatStyle::PAS_Right;
4527   case FormatStyle::RAS_Middle:
4528     return FormatStyle::PAS_Middle;
4529   }
4530   assert(0); //"Unhandled value of ReferenceAlignment"
4531   return Style.PointerAlignment;
4532 }
4533 
4534 FormatStyle::PointerAlignmentStyle
4535 TokenAnnotator::getTokenPointerOrReferenceAlignment(
4536     const FormatToken &PointerOrReference) {
4537   if (PointerOrReference.isOneOf(tok::amp, tok::ampamp)) {
4538     switch (Style.ReferenceAlignment) {
4539     case FormatStyle::RAS_Pointer:
4540       return Style.PointerAlignment;
4541     case FormatStyle::RAS_Left:
4542       return FormatStyle::PAS_Left;
4543     case FormatStyle::RAS_Right:
4544       return FormatStyle::PAS_Right;
4545     case FormatStyle::RAS_Middle:
4546       return FormatStyle::PAS_Middle;
4547     }
4548   }
4549   assert(PointerOrReference.is(tok::star));
4550   return Style.PointerAlignment;
4551 }
4552 
4553 } // namespace format
4554 } // namespace clang
4555