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