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