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