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