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