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