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