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       if (LeftOfParens->is(tok::r_square)) {
1887         //   delete[] (void *)ptr;
1888         auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
1889           if (Tok->isNot(tok::r_square))
1890             return nullptr;
1891 
1892           Tok = Tok->getPreviousNonComment();
1893           if (!Tok || Tok->isNot(tok::l_square))
1894             return nullptr;
1895 
1896           Tok = Tok->getPreviousNonComment();
1897           if (!Tok || Tok->isNot(tok::kw_delete))
1898             return nullptr;
1899           return Tok;
1900         };
1901         if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
1902           LeftOfParens = MaybeDelete;
1903       }
1904 
1905       // The Condition directly below this one will see the operator arguments
1906       // as a (void *foo) cast.
1907       //   void operator delete(void *foo) ATTRIB;
1908       if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous &&
1909           LeftOfParens->Previous->is(tok::kw_operator))
1910         return false;
1911 
1912       // If there is an identifier (or with a few exceptions a keyword) right
1913       // before the parentheses, this is unlikely to be a cast.
1914       if (LeftOfParens->Tok.getIdentifierInfo() &&
1915           !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1916                                  tok::kw_delete))
1917         return false;
1918 
1919       // Certain other tokens right before the parentheses are also signals that
1920       // this cannot be a cast.
1921       if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1922                                 TT_TemplateCloser, tok::ellipsis))
1923         return false;
1924     }
1925 
1926     if (Tok.Next->is(tok::question))
1927       return false;
1928 
1929     // `foreach((A a, B b) in someList)` should not be seen as a cast.
1930     if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp())
1931       return false;
1932 
1933     // Functions which end with decorations like volatile, noexcept are unlikely
1934     // to be casts.
1935     if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
1936                           tok::kw_requires, tok::kw_throw, tok::arrow,
1937                           Keywords.kw_override, Keywords.kw_final) ||
1938         isCpp11AttributeSpecifier(*Tok.Next))
1939       return false;
1940 
1941     // As Java has no function types, a "(" after the ")" likely means that this
1942     // is a cast.
1943     if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1944       return true;
1945 
1946     // If a (non-string) literal follows, this is likely a cast.
1947     if (Tok.Next->isNot(tok::string_literal) &&
1948         (Tok.Next->Tok.isLiteral() ||
1949          Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1950       return true;
1951 
1952     // Heuristically try to determine whether the parentheses contain a type.
1953     auto IsQualifiedPointerOrReference = [](FormatToken *T) {
1954       // This is used to handle cases such as x = (foo *const)&y;
1955       assert(!T->isSimpleTypeSpecifier() && "Should have already been checked");
1956       // Strip trailing qualifiers such as const or volatile when checking
1957       // whether the parens could be a cast to a pointer/reference type.
1958       while (T) {
1959         if (T->is(TT_AttributeParen)) {
1960           // Handle `x = (foo *__attribute__((foo)))&v;`:
1961           if (T->MatchingParen && T->MatchingParen->Previous &&
1962               T->MatchingParen->Previous->is(tok::kw___attribute)) {
1963             T = T->MatchingParen->Previous->Previous;
1964             continue;
1965           }
1966         } else if (T->is(TT_AttributeSquare)) {
1967           // Handle `x = (foo *[[clang::foo]])&v;`:
1968           if (T->MatchingParen && T->MatchingParen->Previous) {
1969             T = T->MatchingParen->Previous;
1970             continue;
1971           }
1972         } else if (T->canBePointerOrReferenceQualifier()) {
1973           T = T->Previous;
1974           continue;
1975         }
1976         break;
1977       }
1978       return T && T->is(TT_PointerOrReference);
1979     };
1980     bool ParensAreType =
1981         !Tok.Previous ||
1982         Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) ||
1983         Tok.Previous->isSimpleTypeSpecifier() ||
1984         IsQualifiedPointerOrReference(Tok.Previous);
1985     bool ParensCouldEndDecl =
1986         Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1987     if (ParensAreType && !ParensCouldEndDecl)
1988       return true;
1989 
1990     // At this point, we heuristically assume that there are no casts at the
1991     // start of the line. We assume that we have found most cases where there
1992     // are by the logic above, e.g. "(void)x;".
1993     if (!LeftOfParens)
1994       return false;
1995 
1996     // Certain token types inside the parentheses mean that this can't be a
1997     // cast.
1998     for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1999          Token = Token->Next)
2000       if (Token->is(TT_BinaryOperator))
2001         return false;
2002 
2003     // If the following token is an identifier or 'this', this is a cast. All
2004     // cases where this can be something else are handled above.
2005     if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
2006       return true;
2007 
2008     // Look for a cast `( x ) (`.
2009     if (Tok.Next->is(tok::l_paren) && Tok.Previous && Tok.Previous->Previous) {
2010       if (Tok.Previous->is(tok::identifier) &&
2011           Tok.Previous->Previous->is(tok::l_paren))
2012         return true;
2013     }
2014 
2015     if (!Tok.Next->Next)
2016       return false;
2017 
2018     // If the next token after the parenthesis is a unary operator, assume
2019     // that this is cast, unless there are unexpected tokens inside the
2020     // parenthesis.
2021     bool NextIsUnary =
2022         Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
2023     if (!NextIsUnary || Tok.Next->is(tok::plus) ||
2024         !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
2025       return false;
2026     // Search for unexpected tokens.
2027     for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
2028          Prev = Prev->Previous)
2029       if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
2030         return false;
2031     return true;
2032   }
2033 
2034   /// Return the type of the given token assuming it is * or &.
2035   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
2036                                   bool InTemplateArgument) {
2037     if (Style.isJavaScript())
2038       return TT_BinaryOperator;
2039 
2040     // && in C# must be a binary operator.
2041     if (Style.isCSharp() && Tok.is(tok::ampamp))
2042       return TT_BinaryOperator;
2043 
2044     const FormatToken *PrevToken = Tok.getPreviousNonComment();
2045     if (!PrevToken)
2046       return TT_UnaryOperator;
2047 
2048     const FormatToken *NextToken = Tok.getNextNonComment();
2049     if (!NextToken ||
2050         NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) ||
2051         NextToken->canBePointerOrReferenceQualifier() ||
2052         (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
2053       return TT_PointerOrReference;
2054 
2055     if (PrevToken->is(tok::coloncolon))
2056       return TT_PointerOrReference;
2057 
2058     if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen))
2059       return TT_PointerOrReference;
2060 
2061     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
2062                            tok::comma, tok::semi, tok::kw_return, tok::colon,
2063                            tok::kw_co_return, tok::kw_co_await,
2064                            tok::kw_co_yield, tok::equal, tok::kw_delete,
2065                            tok::kw_sizeof, tok::kw_throw, TT_BinaryOperator,
2066                            TT_ConditionalExpr, TT_UnaryOperator, TT_CastRParen))
2067       return TT_UnaryOperator;
2068 
2069     if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
2070       return TT_PointerOrReference;
2071     if (NextToken->is(tok::kw_operator) && !IsExpression)
2072       return TT_PointerOrReference;
2073     if (NextToken->isOneOf(tok::comma, tok::semi))
2074       return TT_PointerOrReference;
2075 
2076     if (PrevToken->Tok.isLiteral() ||
2077         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
2078                            tok::kw_false, tok::r_brace) ||
2079         NextToken->Tok.isLiteral() ||
2080         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
2081         NextToken->isUnaryOperator() ||
2082         // If we know we're in a template argument, there are no named
2083         // declarations. Thus, having an identifier on the right-hand side
2084         // indicates a binary operator.
2085         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
2086       return TT_BinaryOperator;
2087 
2088     // "&&(" is quite unlikely to be two successive unary "&".
2089     if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren))
2090       return TT_BinaryOperator;
2091 
2092     // This catches some cases where evaluation order is used as control flow:
2093     //   aaa && aaa->f();
2094     if (NextToken->Tok.isAnyIdentifier()) {
2095       const FormatToken *NextNextToken = NextToken->getNextNonComment();
2096       if (NextNextToken && NextNextToken->is(tok::arrow))
2097         return TT_BinaryOperator;
2098     }
2099 
2100     // It is very unlikely that we are going to find a pointer or reference type
2101     // definition on the RHS of an assignment.
2102     if (IsExpression && !Contexts.back().CaretFound)
2103       return TT_BinaryOperator;
2104 
2105     return TT_PointerOrReference;
2106   }
2107 
2108   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
2109     const FormatToken *PrevToken = Tok.getPreviousNonComment();
2110     if (!PrevToken)
2111       return TT_UnaryOperator;
2112 
2113     if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
2114       // This must be a sequence of leading unary operators.
2115       return TT_UnaryOperator;
2116 
2117     // Use heuristics to recognize unary operators.
2118     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
2119                            tok::question, tok::colon, tok::kw_return,
2120                            tok::kw_case, tok::at, tok::l_brace, tok::kw_throw,
2121                            tok::kw_co_return, tok::kw_co_yield))
2122       return TT_UnaryOperator;
2123 
2124     // There can't be two consecutive binary operators.
2125     if (PrevToken->is(TT_BinaryOperator))
2126       return TT_UnaryOperator;
2127 
2128     // Fall back to marking the token as binary operator.
2129     return TT_BinaryOperator;
2130   }
2131 
2132   /// Determine whether ++/-- are pre- or post-increments/-decrements.
2133   TokenType determineIncrementUsage(const FormatToken &Tok) {
2134     const FormatToken *PrevToken = Tok.getPreviousNonComment();
2135     if (!PrevToken || PrevToken->is(TT_CastRParen))
2136       return TT_UnaryOperator;
2137     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
2138       return TT_TrailingUnaryOperator;
2139 
2140     return TT_UnaryOperator;
2141   }
2142 
2143   SmallVector<Context, 8> Contexts;
2144 
2145   const FormatStyle &Style;
2146   AnnotatedLine &Line;
2147   FormatToken *CurrentToken;
2148   bool AutoFound;
2149   const AdditionalKeywords &Keywords;
2150 
2151   // Set of "<" tokens that do not open a template parameter list. If parseAngle
2152   // determines that a specific token can't be a template opener, it will make
2153   // same decision irrespective of the decisions for tokens leading up to it.
2154   // Store this information to prevent this from causing exponential runtime.
2155   llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
2156 };
2157 
2158 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
2159 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
2160 
2161 /// Parses binary expressions by inserting fake parenthesis based on
2162 /// operator precedence.
2163 class ExpressionParser {
2164 public:
2165   ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
2166                    AnnotatedLine &Line)
2167       : Style(Style), Keywords(Keywords), Current(Line.First) {}
2168 
2169   /// Parse expressions with the given operator precedence.
2170   void parse(int Precedence = 0) {
2171     // Skip 'return' and ObjC selector colons as they are not part of a binary
2172     // expression.
2173     while (Current && (Current->is(tok::kw_return) ||
2174                        (Current->is(tok::colon) &&
2175                         Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
2176       next();
2177 
2178     if (!Current || Precedence > PrecedenceArrowAndPeriod)
2179       return;
2180 
2181     // Conditional expressions need to be parsed separately for proper nesting.
2182     if (Precedence == prec::Conditional) {
2183       parseConditionalExpr();
2184       return;
2185     }
2186 
2187     // Parse unary operators, which all have a higher precedence than binary
2188     // operators.
2189     if (Precedence == PrecedenceUnaryOperator) {
2190       parseUnaryOperator();
2191       return;
2192     }
2193 
2194     FormatToken *Start = Current;
2195     FormatToken *LatestOperator = nullptr;
2196     unsigned OperatorIndex = 0;
2197 
2198     while (Current) {
2199       // Consume operators with higher precedence.
2200       parse(Precedence + 1);
2201 
2202       int CurrentPrecedence = getCurrentPrecedence();
2203 
2204       if (Precedence == CurrentPrecedence && Current &&
2205           Current->is(TT_SelectorName)) {
2206         if (LatestOperator)
2207           addFakeParenthesis(Start, prec::Level(Precedence));
2208         Start = Current;
2209       }
2210 
2211       // At the end of the line or when an operator with higher precedence is
2212       // found, insert fake parenthesis and return.
2213       if (!Current ||
2214           (Current->closesScope() &&
2215            (Current->MatchingParen || Current->is(TT_TemplateString))) ||
2216           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
2217           (CurrentPrecedence == prec::Conditional &&
2218            Precedence == prec::Assignment && Current->is(tok::colon)))
2219         break;
2220 
2221       // Consume scopes: (), [], <> and {}
2222       if (Current->opensScope()) {
2223         // In fragment of a JavaScript template string can look like '}..${' and
2224         // thus close a scope and open a new one at the same time.
2225         while (Current && (!Current->closesScope() || Current->opensScope())) {
2226           next();
2227           parse();
2228         }
2229         next();
2230       } else {
2231         // Operator found.
2232         if (CurrentPrecedence == Precedence) {
2233           if (LatestOperator)
2234             LatestOperator->NextOperator = Current;
2235           LatestOperator = Current;
2236           Current->OperatorIndex = OperatorIndex;
2237           ++OperatorIndex;
2238         }
2239         next(/*SkipPastLeadingComments=*/Precedence > 0);
2240       }
2241     }
2242 
2243     if (LatestOperator && (Current || Precedence > 0)) {
2244       // LatestOperator->LastOperator = true;
2245       if (Precedence == PrecedenceArrowAndPeriod) {
2246         // Call expressions don't have a binary operator precedence.
2247         addFakeParenthesis(Start, prec::Unknown);
2248       } else {
2249         addFakeParenthesis(Start, prec::Level(Precedence));
2250       }
2251     }
2252   }
2253 
2254 private:
2255   /// Gets the precedence (+1) of the given token for binary operators
2256   /// and other tokens that we treat like binary operators.
2257   int getCurrentPrecedence() {
2258     if (Current) {
2259       const FormatToken *NextNonComment = Current->getNextNonComment();
2260       if (Current->is(TT_ConditionalExpr))
2261         return prec::Conditional;
2262       if (NextNonComment && Current->is(TT_SelectorName) &&
2263           (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
2264            ((Style.Language == FormatStyle::LK_Proto ||
2265              Style.Language == FormatStyle::LK_TextProto) &&
2266             NextNonComment->is(tok::less))))
2267         return prec::Assignment;
2268       if (Current->is(TT_JsComputedPropertyName))
2269         return prec::Assignment;
2270       if (Current->is(TT_LambdaArrow))
2271         return prec::Comma;
2272       if (Current->is(TT_FatArrow))
2273         return prec::Assignment;
2274       if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
2275           (Current->is(tok::comment) && NextNonComment &&
2276            NextNonComment->is(TT_SelectorName)))
2277         return 0;
2278       if (Current->is(TT_RangeBasedForLoopColon))
2279         return prec::Comma;
2280       if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
2281           Current->is(Keywords.kw_instanceof))
2282         return prec::Relational;
2283       if (Style.isJavaScript() &&
2284           Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
2285         return prec::Relational;
2286       if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
2287         return Current->getPrecedence();
2288       if (Current->isOneOf(tok::period, tok::arrow))
2289         return PrecedenceArrowAndPeriod;
2290       if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
2291           Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
2292                            Keywords.kw_throws))
2293         return 0;
2294     }
2295     return -1;
2296   }
2297 
2298   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
2299     Start->FakeLParens.push_back(Precedence);
2300     if (Precedence > prec::Unknown)
2301       Start->StartsBinaryExpression = true;
2302     if (Current) {
2303       FormatToken *Previous = Current->Previous;
2304       while (Previous->is(tok::comment) && Previous->Previous)
2305         Previous = Previous->Previous;
2306       ++Previous->FakeRParens;
2307       if (Precedence > prec::Unknown)
2308         Previous->EndsBinaryExpression = true;
2309     }
2310   }
2311 
2312   /// Parse unary operator expressions and surround them with fake
2313   /// parentheses if appropriate.
2314   void parseUnaryOperator() {
2315     llvm::SmallVector<FormatToken *, 2> Tokens;
2316     while (Current && Current->is(TT_UnaryOperator)) {
2317       Tokens.push_back(Current);
2318       next();
2319     }
2320     parse(PrecedenceArrowAndPeriod);
2321     for (FormatToken *Token : llvm::reverse(Tokens))
2322       // The actual precedence doesn't matter.
2323       addFakeParenthesis(Token, prec::Unknown);
2324   }
2325 
2326   void parseConditionalExpr() {
2327     while (Current && Current->isTrailingComment())
2328       next();
2329     FormatToken *Start = Current;
2330     parse(prec::LogicalOr);
2331     if (!Current || !Current->is(tok::question))
2332       return;
2333     next();
2334     parse(prec::Assignment);
2335     if (!Current || Current->isNot(TT_ConditionalExpr))
2336       return;
2337     next();
2338     parse(prec::Assignment);
2339     addFakeParenthesis(Start, prec::Conditional);
2340   }
2341 
2342   void next(bool SkipPastLeadingComments = true) {
2343     if (Current)
2344       Current = Current->Next;
2345     while (Current &&
2346            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
2347            Current->isTrailingComment())
2348       Current = Current->Next;
2349   }
2350 
2351   const FormatStyle &Style;
2352   const AdditionalKeywords &Keywords;
2353   FormatToken *Current;
2354 };
2355 
2356 } // end anonymous namespace
2357 
2358 void TokenAnnotator::setCommentLineLevels(
2359     SmallVectorImpl<AnnotatedLine *> &Lines) {
2360   const AnnotatedLine *NextNonCommentLine = nullptr;
2361   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
2362     assert(Line->First);
2363     bool CommentLine = true;
2364     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
2365       if (!Tok->is(tok::comment)) {
2366         CommentLine = false;
2367         break;
2368       }
2369     }
2370 
2371     // If the comment is currently aligned with the line immediately following
2372     // it, that's probably intentional and we should keep it.
2373     if (NextNonCommentLine && CommentLine &&
2374         NextNonCommentLine->First->NewlinesBefore <= 1 &&
2375         NextNonCommentLine->First->OriginalColumn ==
2376             Line->First->OriginalColumn) {
2377       // Align comments for preprocessor lines with the # in column 0 if
2378       // preprocessor lines are not indented. Otherwise, align with the next
2379       // line.
2380       Line->Level =
2381           (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
2382            (NextNonCommentLine->Type == LT_PreprocessorDirective ||
2383             NextNonCommentLine->Type == LT_ImportStatement))
2384               ? 0
2385               : NextNonCommentLine->Level;
2386     } else {
2387       NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr;
2388     }
2389 
2390     setCommentLineLevels(Line->Children);
2391   }
2392 }
2393 
2394 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
2395   unsigned Result = 0;
2396   for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
2397     Result = std::max(Result, Tok->NestingLevel);
2398   return Result;
2399 }
2400 
2401 void TokenAnnotator::annotate(AnnotatedLine &Line) {
2402   for (auto &Child : Line.Children)
2403     annotate(*Child);
2404 
2405   AnnotatingParser Parser(Style, Line, Keywords);
2406   Line.Type = Parser.parseLine();
2407 
2408   // With very deep nesting, ExpressionParser uses lots of stack and the
2409   // formatting algorithm is very slow. We're not going to do a good job here
2410   // anyway - it's probably generated code being formatted by mistake.
2411   // Just skip the whole line.
2412   if (maxNestingDepth(Line) > 50)
2413     Line.Type = LT_Invalid;
2414 
2415   if (Line.Type == LT_Invalid)
2416     return;
2417 
2418   ExpressionParser ExprParser(Style, Keywords, Line);
2419   ExprParser.parse();
2420 
2421   if (Line.startsWith(TT_ObjCMethodSpecifier))
2422     Line.Type = LT_ObjCMethodDecl;
2423   else if (Line.startsWith(TT_ObjCDecl))
2424     Line.Type = LT_ObjCDecl;
2425   else if (Line.startsWith(TT_ObjCProperty))
2426     Line.Type = LT_ObjCProperty;
2427 
2428   Line.First->SpacesRequiredBefore = 1;
2429   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
2430 }
2431 
2432 // This function heuristically determines whether 'Current' starts the name of a
2433 // function declaration.
2434 static bool isFunctionDeclarationName(bool IsCpp, const FormatToken &Current,
2435                                       const AnnotatedLine &Line) {
2436   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
2437     for (; Next; Next = Next->Next) {
2438       if (Next->is(TT_OverloadedOperatorLParen))
2439         return Next;
2440       if (Next->is(TT_OverloadedOperator))
2441         continue;
2442       if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
2443         // For 'new[]' and 'delete[]'.
2444         if (Next->Next &&
2445             Next->Next->startsSequence(tok::l_square, tok::r_square))
2446           Next = Next->Next->Next;
2447         continue;
2448       }
2449       if (Next->startsSequence(tok::l_square, tok::r_square)) {
2450         // For operator[]().
2451         Next = Next->Next;
2452         continue;
2453       }
2454       if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) &&
2455           Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) {
2456         // For operator void*(), operator char*(), operator Foo*().
2457         Next = Next->Next;
2458         continue;
2459       }
2460       if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
2461         Next = Next->MatchingParen;
2462         continue;
2463       }
2464 
2465       break;
2466     }
2467     return nullptr;
2468   };
2469 
2470   // Find parentheses of parameter list.
2471   const FormatToken *Next = Current.Next;
2472   if (Current.is(tok::kw_operator)) {
2473     if (Current.Previous && Current.Previous->is(tok::coloncolon))
2474       return false;
2475     Next = skipOperatorName(Next);
2476   } else {
2477     if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
2478       return false;
2479     for (; Next; Next = Next->Next) {
2480       if (Next->is(TT_TemplateOpener)) {
2481         Next = Next->MatchingParen;
2482       } else if (Next->is(tok::coloncolon)) {
2483         Next = Next->Next;
2484         if (!Next)
2485           return false;
2486         if (Next->is(tok::kw_operator)) {
2487           Next = skipOperatorName(Next->Next);
2488           break;
2489         }
2490         if (!Next->is(tok::identifier))
2491           return false;
2492       } else if (Next->is(tok::l_paren)) {
2493         break;
2494       } else {
2495         return false;
2496       }
2497     }
2498   }
2499 
2500   // Check whether parameter list can belong to a function declaration.
2501   if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
2502     return false;
2503   // If the lines ends with "{", this is likely a function definition.
2504   if (Line.Last->is(tok::l_brace))
2505     return true;
2506   if (Next->Next == Next->MatchingParen)
2507     return true; // Empty parentheses.
2508   // If there is an &/&& after the r_paren, this is likely a function.
2509   if (Next->MatchingParen->Next &&
2510       Next->MatchingParen->Next->is(TT_PointerOrReference))
2511     return true;
2512 
2513   // Check for K&R C function definitions (and C++ function definitions with
2514   // unnamed parameters), e.g.:
2515   //   int f(i)
2516   //   {
2517   //     return i + 1;
2518   //   }
2519   //   bool g(size_t = 0, bool b = false)
2520   //   {
2521   //     return !b;
2522   //   }
2523   if (IsCpp && Next->Next && Next->Next->is(tok::identifier) &&
2524       !Line.endsWith(tok::semi))
2525     return true;
2526 
2527   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
2528        Tok = Tok->Next) {
2529     if (Tok->is(TT_TypeDeclarationParen))
2530       return true;
2531     if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
2532       Tok = Tok->MatchingParen;
2533       continue;
2534     }
2535     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
2536         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
2537       return true;
2538     if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
2539         Tok->Tok.isLiteral())
2540       return false;
2541   }
2542   return false;
2543 }
2544 
2545 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
2546   assert(Line.MightBeFunctionDecl);
2547 
2548   if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
2549        Style.AlwaysBreakAfterReturnType ==
2550            FormatStyle::RTBS_TopLevelDefinitions) &&
2551       Line.Level > 0)
2552     return false;
2553 
2554   switch (Style.AlwaysBreakAfterReturnType) {
2555   case FormatStyle::RTBS_None:
2556     return false;
2557   case FormatStyle::RTBS_All:
2558   case FormatStyle::RTBS_TopLevel:
2559     return true;
2560   case FormatStyle::RTBS_AllDefinitions:
2561   case FormatStyle::RTBS_TopLevelDefinitions:
2562     return Line.mightBeFunctionDefinition();
2563   }
2564 
2565   return false;
2566 }
2567 
2568 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2569   for (AnnotatedLine *ChildLine : Line.Children)
2570     calculateFormattingInformation(*ChildLine);
2571 
2572   Line.First->TotalLength =
2573       Line.First->IsMultiline ? Style.ColumnLimit
2574                               : Line.FirstStartColumn + Line.First->ColumnWidth;
2575   FormatToken *Current = Line.First->Next;
2576   bool InFunctionDecl = Line.MightBeFunctionDecl;
2577   bool AlignArrayOfStructures =
2578       (Style.AlignArrayOfStructures != FormatStyle::AIAS_None &&
2579        Line.Type == LT_ArrayOfStructInitializer);
2580   if (AlignArrayOfStructures)
2581     calculateArrayInitializerColumnList(Line);
2582 
2583   while (Current) {
2584     if (isFunctionDeclarationName(Style.isCpp(), *Current, Line))
2585       Current->setType(TT_FunctionDeclarationName);
2586     const FormatToken *Prev = Current->Previous;
2587     if (Current->is(TT_LineComment)) {
2588       if (Prev->is(BK_BracedInit) && Prev->opensScope())
2589         Current->SpacesRequiredBefore =
2590             (Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1;
2591       else
2592         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2593 
2594       // If we find a trailing comment, iterate backwards to determine whether
2595       // it seems to relate to a specific parameter. If so, break before that
2596       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2597       // to the previous line in:
2598       //   SomeFunction(a,
2599       //                b, // comment
2600       //                c);
2601       if (!Current->HasUnescapedNewline) {
2602         for (FormatToken *Parameter = Current->Previous; Parameter;
2603              Parameter = Parameter->Previous) {
2604           if (Parameter->isOneOf(tok::comment, tok::r_brace))
2605             break;
2606           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2607             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2608                 Parameter->HasUnescapedNewline)
2609               Parameter->MustBreakBefore = true;
2610             break;
2611           }
2612         }
2613       }
2614     } else if (Current->SpacesRequiredBefore == 0 &&
2615                spaceRequiredBefore(Line, *Current)) {
2616       Current->SpacesRequiredBefore = 1;
2617     }
2618 
2619     Current->MustBreakBefore =
2620         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2621 
2622     if (!Current->MustBreakBefore && InFunctionDecl &&
2623         Current->is(TT_FunctionDeclarationName))
2624       Current->MustBreakBefore = mustBreakForReturnType(Line);
2625 
2626     Current->CanBreakBefore =
2627         Current->MustBreakBefore || canBreakBefore(Line, *Current);
2628     unsigned ChildSize = 0;
2629     if (Prev->Children.size() == 1) {
2630       FormatToken &LastOfChild = *Prev->Children[0]->Last;
2631       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2632                                                   : LastOfChild.TotalLength + 1;
2633     }
2634     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2635         (Prev->Children.size() == 1 &&
2636          Prev->Children[0]->First->MustBreakBefore) ||
2637         Current->IsMultiline)
2638       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2639     else
2640       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2641                              ChildSize + Current->SpacesRequiredBefore;
2642 
2643     if (Current->is(TT_CtorInitializerColon))
2644       InFunctionDecl = false;
2645 
2646     // FIXME: Only calculate this if CanBreakBefore is true once static
2647     // initializers etc. are sorted out.
2648     // FIXME: Move magic numbers to a better place.
2649 
2650     // Reduce penalty for aligning ObjC method arguments using the colon
2651     // alignment as this is the canonical way (still prefer fitting everything
2652     // into one line if possible). Trying to fit a whole expression into one
2653     // line should not force other line breaks (e.g. when ObjC method
2654     // expression is a part of other expression).
2655     Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
2656     if (Style.Language == FormatStyle::LK_ObjC &&
2657         Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
2658       if (Current->ParameterIndex == 1)
2659         Current->SplitPenalty += 5 * Current->BindingStrength;
2660     } else {
2661       Current->SplitPenalty += 20 * Current->BindingStrength;
2662     }
2663 
2664     Current = Current->Next;
2665   }
2666 
2667   calculateUnbreakableTailLengths(Line);
2668   unsigned IndentLevel = Line.Level;
2669   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2670     if (Current->Role)
2671       Current->Role->precomputeFormattingInfos(Current);
2672     if (Current->MatchingParen &&
2673         Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
2674         IndentLevel > 0)
2675       --IndentLevel;
2676     Current->IndentLevel = IndentLevel;
2677     if (Current->opensBlockOrBlockTypeList(Style))
2678       ++IndentLevel;
2679   }
2680 
2681   LLVM_DEBUG({ printDebugInfo(Line); });
2682 }
2683 
2684 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2685   unsigned UnbreakableTailLength = 0;
2686   FormatToken *Current = Line.Last;
2687   while (Current) {
2688     Current->UnbreakableTailLength = UnbreakableTailLength;
2689     if (Current->CanBreakBefore ||
2690         Current->isOneOf(tok::comment, tok::string_literal)) {
2691       UnbreakableTailLength = 0;
2692     } else {
2693       UnbreakableTailLength +=
2694           Current->ColumnWidth + Current->SpacesRequiredBefore;
2695     }
2696     Current = Current->Previous;
2697   }
2698 }
2699 
2700 void TokenAnnotator::calculateArrayInitializerColumnList(AnnotatedLine &Line) {
2701   if (Line.First == Line.Last)
2702     return;
2703   auto *CurrentToken = Line.First;
2704   CurrentToken->ArrayInitializerLineStart = true;
2705   unsigned Depth = 0;
2706   while (CurrentToken != nullptr && CurrentToken != Line.Last) {
2707     if (CurrentToken->is(tok::l_brace)) {
2708       CurrentToken->IsArrayInitializer = true;
2709       if (CurrentToken->Next != nullptr)
2710         CurrentToken->Next->MustBreakBefore = true;
2711       CurrentToken =
2712           calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1);
2713     } else {
2714       CurrentToken = CurrentToken->Next;
2715     }
2716   }
2717 }
2718 
2719 FormatToken *TokenAnnotator::calculateInitializerColumnList(
2720     AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) {
2721   while (CurrentToken != nullptr && CurrentToken != Line.Last) {
2722     if (CurrentToken->is(tok::l_brace))
2723       ++Depth;
2724     else if (CurrentToken->is(tok::r_brace))
2725       --Depth;
2726     if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) {
2727       CurrentToken = CurrentToken->Next;
2728       if (CurrentToken == nullptr)
2729         break;
2730       CurrentToken->StartsColumn = true;
2731       CurrentToken = CurrentToken->Previous;
2732     }
2733     CurrentToken = CurrentToken->Next;
2734   }
2735   return CurrentToken;
2736 }
2737 
2738 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2739                                       const FormatToken &Tok,
2740                                       bool InFunctionDecl) {
2741   const FormatToken &Left = *Tok.Previous;
2742   const FormatToken &Right = Tok;
2743 
2744   if (Left.is(tok::semi))
2745     return 0;
2746 
2747   if (Style.Language == FormatStyle::LK_Java) {
2748     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2749       return 1;
2750     if (Right.is(Keywords.kw_implements))
2751       return 2;
2752     if (Left.is(tok::comma) && Left.NestingLevel == 0)
2753       return 3;
2754   } else if (Style.isJavaScript()) {
2755     if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2756       return 100;
2757     if (Left.is(TT_JsTypeColon))
2758       return 35;
2759     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2760         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2761       return 100;
2762     // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2763     if (Left.opensScope() && Right.closesScope())
2764       return 200;
2765   }
2766 
2767   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2768     return 1;
2769   if (Right.is(tok::l_square)) {
2770     if (Style.Language == FormatStyle::LK_Proto)
2771       return 1;
2772     if (Left.is(tok::r_square))
2773       return 200;
2774     // Slightly prefer formatting local lambda definitions like functions.
2775     if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2776       return 35;
2777     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2778                        TT_ArrayInitializerLSquare,
2779                        TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2780       return 500;
2781   }
2782 
2783   if (Left.is(tok::coloncolon) ||
2784       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2785     return 500;
2786   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2787       Right.is(tok::kw_operator)) {
2788     if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2789       return 3;
2790     if (Left.is(TT_StartOfName))
2791       return 110;
2792     if (InFunctionDecl && Right.NestingLevel == 0)
2793       return Style.PenaltyReturnTypeOnItsOwnLine;
2794     return 200;
2795   }
2796   if (Right.is(TT_PointerOrReference))
2797     return 190;
2798   if (Right.is(TT_LambdaArrow))
2799     return 110;
2800   if (Left.is(tok::equal) && Right.is(tok::l_brace))
2801     return 160;
2802   if (Left.is(TT_CastRParen))
2803     return 100;
2804   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2805     return 5000;
2806   if (Left.is(tok::comment))
2807     return 1000;
2808 
2809   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2810                    TT_CtorInitializerColon))
2811     return 2;
2812 
2813   if (Right.isMemberAccess()) {
2814     // Breaking before the "./->" of a chained call/member access is reasonably
2815     // cheap, as formatting those with one call per line is generally
2816     // desirable. In particular, it should be cheaper to break before the call
2817     // than it is to break inside a call's parameters, which could lead to weird
2818     // "hanging" indents. The exception is the very last "./->" to support this
2819     // frequent pattern:
2820     //
2821     //   aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2822     //       dddddddd);
2823     //
2824     // which might otherwise be blown up onto many lines. Here, clang-format
2825     // won't produce "hanging" indents anyway as there is no other trailing
2826     // call.
2827     //
2828     // Also apply higher penalty is not a call as that might lead to a wrapping
2829     // like:
2830     //
2831     //   aaaaaaa
2832     //       .aaaaaaaaa.bbbbbbbb(cccccccc);
2833     return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2834                ? 150
2835                : 35;
2836   }
2837 
2838   if (Right.is(TT_TrailingAnnotation) &&
2839       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2840     // Moving trailing annotations to the next line is fine for ObjC method
2841     // declarations.
2842     if (Line.startsWith(TT_ObjCMethodSpecifier))
2843       return 10;
2844     // Generally, breaking before a trailing annotation is bad unless it is
2845     // function-like. It seems to be especially preferable to keep standard
2846     // annotations (i.e. "const", "final" and "override") on the same line.
2847     // Use a slightly higher penalty after ")" so that annotations like
2848     // "const override" are kept together.
2849     bool is_short_annotation = Right.TokenText.size() < 10;
2850     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2851   }
2852 
2853   // In for-loops, prefer breaking at ',' and ';'.
2854   if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2855     return 4;
2856 
2857   // In Objective-C method expressions, prefer breaking before "param:" over
2858   // breaking after it.
2859   if (Right.is(TT_SelectorName))
2860     return 0;
2861   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2862     return Line.MightBeFunctionDecl ? 50 : 500;
2863 
2864   // In Objective-C type declarations, avoid breaking after the category's
2865   // open paren (we'll prefer breaking after the protocol list's opening
2866   // angle bracket, if present).
2867   if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
2868       Left.Previous->isOneOf(tok::identifier, tok::greater))
2869     return 500;
2870 
2871   if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
2872     return Style.PenaltyBreakOpenParenthesis;
2873   if (Left.is(tok::l_paren) && InFunctionDecl &&
2874       Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2875     return 100;
2876   if (Left.is(tok::l_paren) && Left.Previous &&
2877       (Left.Previous->is(tok::kw_for) || Left.Previous->isIf()))
2878     return 1000;
2879   if (Left.is(tok::equal) && InFunctionDecl)
2880     return 110;
2881   if (Right.is(tok::r_brace))
2882     return 1;
2883   if (Left.is(TT_TemplateOpener))
2884     return 100;
2885   if (Left.opensScope()) {
2886     // If we aren't aligning after opening parens/braces we can always break
2887     // here unless the style does not want us to place all arguments on the
2888     // next line.
2889     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign &&
2890         (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine))
2891       return 0;
2892     if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
2893       return 19;
2894     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2895                                    : 19;
2896   }
2897   if (Left.is(TT_JavaAnnotation))
2898     return 50;
2899 
2900   if (Left.is(TT_UnaryOperator))
2901     return 60;
2902   if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2903       Left.Previous->isLabelString() &&
2904       (Left.NextOperator || Left.OperatorIndex != 0))
2905     return 50;
2906   if (Right.is(tok::plus) && Left.isLabelString() &&
2907       (Right.NextOperator || Right.OperatorIndex != 0))
2908     return 25;
2909   if (Left.is(tok::comma))
2910     return 1;
2911   if (Right.is(tok::lessless) && Left.isLabelString() &&
2912       (Right.NextOperator || Right.OperatorIndex != 1))
2913     return 25;
2914   if (Right.is(tok::lessless)) {
2915     // Breaking at a << is really cheap.
2916     if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2917       // Slightly prefer to break before the first one in log-like statements.
2918       return 2;
2919     return 1;
2920   }
2921   if (Left.ClosesTemplateDeclaration)
2922     return Style.PenaltyBreakTemplateDeclaration;
2923   if (Left.is(TT_ConditionalExpr))
2924     return prec::Conditional;
2925   prec::Level Level = Left.getPrecedence();
2926   if (Level == prec::Unknown)
2927     Level = Right.getPrecedence();
2928   if (Level == prec::Assignment)
2929     return Style.PenaltyBreakAssignment;
2930   if (Level != prec::Unknown)
2931     return Level;
2932 
2933   return 3;
2934 }
2935 
2936 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
2937   if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
2938     return true;
2939   if (Right.is(TT_OverloadedOperatorLParen) &&
2940       Style.SpaceBeforeParensOptions.AfterOverloadedOperator)
2941     return true;
2942   if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
2943       Right.ParameterCount > 0)
2944     return true;
2945   return false;
2946 }
2947 
2948 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2949                                           const FormatToken &Left,
2950                                           const FormatToken &Right) {
2951   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2952     return true;
2953   if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon))
2954     return false;
2955   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2956     return true;
2957   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2958       Left.Tok.getObjCKeywordID() == tok::objc_property)
2959     return true;
2960   if (Right.is(tok::hashhash))
2961     return Left.is(tok::hash);
2962   if (Left.isOneOf(tok::hashhash, tok::hash))
2963     return Right.is(tok::hash);
2964   if ((Left.is(tok::l_paren) && Right.is(tok::r_paren)) ||
2965       (Left.is(tok::l_brace) && Left.isNot(BK_Block) &&
2966        Right.is(tok::r_brace) && Right.isNot(BK_Block)))
2967     return Style.SpaceInEmptyParentheses;
2968   if (Style.SpacesInConditionalStatement) {
2969     if (Left.is(tok::l_paren) && Left.Previous &&
2970         isKeywordWithCondition(*Left.Previous))
2971       return true;
2972     if (Right.is(tok::r_paren) && Right.MatchingParen &&
2973         Right.MatchingParen->Previous &&
2974         isKeywordWithCondition(*Right.MatchingParen->Previous))
2975       return true;
2976   }
2977 
2978   // auto{x} auto(x)
2979   if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
2980     return false;
2981 
2982   // operator co_await(x)
2983   if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && Left.Previous &&
2984       Left.Previous->is(tok::kw_operator))
2985     return false;
2986   // co_await (x), co_yield (x), co_return (x)
2987   if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) &&
2988       Right.isNot(tok::semi))
2989     return true;
2990   // requires clause Concept1<T> && Concept2<T>
2991   if (Left.is(TT_ConstraintJunctions) && Right.is(tok::identifier))
2992     return true;
2993 
2994   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2995     return (Right.is(TT_CastRParen) ||
2996             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2997                ? Style.SpacesInCStyleCastParentheses
2998                : Style.SpacesInParentheses;
2999   if (Right.isOneOf(tok::semi, tok::comma))
3000     return false;
3001   if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
3002     bool IsLightweightGeneric = Right.MatchingParen &&
3003                                 Right.MatchingParen->Next &&
3004                                 Right.MatchingParen->Next->is(tok::colon);
3005     return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
3006   }
3007   if (Right.is(tok::less) && Left.is(tok::kw_template))
3008     return Style.SpaceAfterTemplateKeyword;
3009   if (Left.isOneOf(tok::exclaim, tok::tilde))
3010     return false;
3011   if (Left.is(tok::at) &&
3012       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
3013                     tok::numeric_constant, tok::l_paren, tok::l_brace,
3014                     tok::kw_true, tok::kw_false))
3015     return false;
3016   if (Left.is(tok::colon))
3017     return !Left.is(TT_ObjCMethodExpr);
3018   if (Left.is(tok::coloncolon))
3019     return false;
3020   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
3021     if (Style.Language == FormatStyle::LK_TextProto ||
3022         (Style.Language == FormatStyle::LK_Proto &&
3023          (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
3024       // Format empty list as `<>`.
3025       if (Left.is(tok::less) && Right.is(tok::greater))
3026         return false;
3027       return !Style.Cpp11BracedListStyle;
3028     }
3029     return false;
3030   }
3031   if (Right.is(tok::ellipsis))
3032     return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
3033                                     Left.Previous->is(tok::kw_case));
3034   if (Left.is(tok::l_square) && Right.is(tok::amp))
3035     return Style.SpacesInSquareBrackets;
3036   if (Right.is(TT_PointerOrReference)) {
3037     if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
3038       if (!Left.MatchingParen)
3039         return true;
3040       FormatToken *TokenBeforeMatchingParen =
3041           Left.MatchingParen->getPreviousNonComment();
3042       if (!TokenBeforeMatchingParen || !Left.is(TT_TypeDeclarationParen))
3043         return true;
3044     }
3045     // Add a space if the previous token is a pointer qualifier or the closing
3046     // parenthesis of __attribute__(()) expression and the style requires spaces
3047     // after pointer qualifiers.
3048     if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After ||
3049          Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
3050         (Left.is(TT_AttributeParen) || Left.canBePointerOrReferenceQualifier()))
3051       return true;
3052     if (Left.Tok.isLiteral())
3053       return true;
3054     // for (auto a = 0, b = 0; const auto & c : {1, 2, 3})
3055     if (Left.isTypeOrIdentifier() && Right.Next && Right.Next->Next &&
3056         Right.Next->Next->is(TT_RangeBasedForLoopColon))
3057       return getTokenPointerOrReferenceAlignment(Right) !=
3058              FormatStyle::PAS_Left;
3059     return (
3060         (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
3061          (getTokenPointerOrReferenceAlignment(Right) != FormatStyle::PAS_Left ||
3062           (Line.IsMultiVariableDeclStmt &&
3063            (Left.NestingLevel == 0 ||
3064             (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
3065   }
3066   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
3067       (!Left.is(TT_PointerOrReference) ||
3068        (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right &&
3069         !Line.IsMultiVariableDeclStmt)))
3070     return true;
3071   if (Left.is(TT_PointerOrReference)) {
3072     // Add a space if the next token is a pointer qualifier and the style
3073     // requires spaces before pointer qualifiers.
3074     if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before ||
3075          Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
3076         Right.canBePointerOrReferenceQualifier())
3077       return true;
3078     // & 1
3079     if (Right.Tok.isLiteral())
3080       return true;
3081     // & /* comment
3082     if (Right.is(TT_BlockComment))
3083       return true;
3084     // foo() -> const Bar * override/final
3085     if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
3086         !Right.is(TT_StartOfName))
3087       return true;
3088     // & {
3089     if (Right.is(tok::l_brace) && Right.is(BK_Block))
3090       return true;
3091     // for (auto a = 0, b = 0; const auto& c : {1, 2, 3})
3092     if (Left.Previous && Left.Previous->isTypeOrIdentifier() && Right.Next &&
3093         Right.Next->is(TT_RangeBasedForLoopColon))
3094       return getTokenPointerOrReferenceAlignment(Left) !=
3095              FormatStyle::PAS_Right;
3096     return !Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
3097                           tok::l_paren) &&
3098            (getTokenPointerOrReferenceAlignment(Left) !=
3099                 FormatStyle::PAS_Right &&
3100             !Line.IsMultiVariableDeclStmt) &&
3101            Left.Previous &&
3102            !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon,
3103                                    tok::l_square);
3104   }
3105   // Ensure right pointer alignment with ellipsis e.g. int *...P
3106   if (Left.is(tok::ellipsis) && Left.Previous &&
3107       Left.Previous->isOneOf(tok::star, tok::amp, tok::ampamp))
3108     return Style.PointerAlignment != FormatStyle::PAS_Right;
3109 
3110   if (Right.is(tok::star) && Left.is(tok::l_paren))
3111     return false;
3112   if (Left.is(tok::star) && Right.isOneOf(tok::star, tok::amp, tok::ampamp))
3113     return false;
3114   if (Right.isOneOf(tok::star, tok::amp, tok::ampamp)) {
3115     const FormatToken *Previous = &Left;
3116     while (Previous && !Previous->is(tok::kw_operator)) {
3117       if (Previous->is(tok::identifier) || Previous->isSimpleTypeSpecifier()) {
3118         Previous = Previous->getPreviousNonComment();
3119         continue;
3120       }
3121       if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) {
3122         Previous = Previous->MatchingParen->getPreviousNonComment();
3123         continue;
3124       }
3125       if (Previous->is(tok::coloncolon)) {
3126         Previous = Previous->getPreviousNonComment();
3127         continue;
3128       }
3129       break;
3130     }
3131     // Space between the type and the * in:
3132     //   operator void*()
3133     //   operator char*()
3134     //   operator void const*()
3135     //   operator void volatile*()
3136     //   operator /*comment*/ const char*()
3137     //   operator volatile /*comment*/ char*()
3138     //   operator Foo*()
3139     //   operator C<T>*()
3140     //   operator std::Foo*()
3141     //   operator C<T>::D<U>*()
3142     // dependent on PointerAlignment style.
3143     if (Previous) {
3144       if (Previous->endsSequence(tok::kw_operator))
3145         return (Style.PointerAlignment != FormatStyle::PAS_Left);
3146       if (Previous->is(tok::kw_const) || Previous->is(tok::kw_volatile))
3147         return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
3148                (Style.SpaceAroundPointerQualifiers ==
3149                 FormatStyle::SAPQ_After) ||
3150                (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
3151     }
3152   }
3153   const auto SpaceRequiredForArrayInitializerLSquare =
3154       [](const FormatToken &LSquareTok, const FormatStyle &Style) {
3155         return Style.SpacesInContainerLiterals ||
3156                ((Style.Language == FormatStyle::LK_Proto ||
3157                  Style.Language == FormatStyle::LK_TextProto) &&
3158                 !Style.Cpp11BracedListStyle &&
3159                 LSquareTok.endsSequence(tok::l_square, tok::colon,
3160                                         TT_SelectorName));
3161       };
3162   if (Left.is(tok::l_square))
3163     return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
3164             SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
3165            (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare,
3166                          TT_LambdaLSquare) &&
3167             Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
3168   if (Right.is(tok::r_square))
3169     return Right.MatchingParen &&
3170            ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
3171              SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
3172                                                      Style)) ||
3173             (Style.SpacesInSquareBrackets &&
3174              Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
3175                                           TT_StructuredBindingLSquare,
3176                                           TT_LambdaLSquare)) ||
3177             Right.MatchingParen->is(TT_AttributeParen));
3178   if (Right.is(tok::l_square) &&
3179       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
3180                      TT_DesignatedInitializerLSquare,
3181                      TT_StructuredBindingLSquare, TT_AttributeSquare) &&
3182       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral) &&
3183       !(!Left.is(tok::r_square) && Style.SpaceBeforeSquareBrackets &&
3184         Right.is(TT_ArraySubscriptLSquare)))
3185     return false;
3186   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
3187     return !Left.Children.empty(); // No spaces in "{}".
3188   if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
3189       (Right.is(tok::r_brace) && Right.MatchingParen &&
3190        Right.MatchingParen->isNot(BK_Block)))
3191     return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true;
3192   if (Left.is(TT_BlockComment))
3193     // No whitespace in x(/*foo=*/1), except for JavaScript.
3194     return Style.isJavaScript() || !Left.TokenText.endswith("=*/");
3195 
3196   // Space between template and attribute.
3197   // e.g. template <typename T> [[nodiscard]] ...
3198   if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeSquare))
3199     return true;
3200   // Space before parentheses common for all languages
3201   if (Right.is(tok::l_paren)) {
3202     if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen))
3203       return spaceRequiredBeforeParens(Right);
3204     if (Left.is(tok::kw_requires))
3205       return spaceRequiredBeforeParens(Right);
3206     if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
3207         (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
3208       return true;
3209     if (Left.is(TT_ForEachMacro))
3210       return (Style.SpaceBeforeParensOptions.AfterForeachMacros ||
3211               spaceRequiredBeforeParens(Right));
3212     if (Left.is(TT_IfMacro))
3213       return (Style.SpaceBeforeParensOptions.AfterIfMacros ||
3214               spaceRequiredBeforeParens(Right));
3215     if (Line.Type == LT_ObjCDecl)
3216       return true;
3217     if (Left.is(tok::semi))
3218       return true;
3219     if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch,
3220                      tok::kw_case, TT_ForEachMacro, TT_ObjCForIn))
3221       return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3222              spaceRequiredBeforeParens(Right);
3223     if (Left.isIf(Line.Type != LT_PreprocessorDirective))
3224       return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3225              spaceRequiredBeforeParens(Right);
3226 
3227     // TODO add Operator overloading specific Options to
3228     // SpaceBeforeParensOptions
3229     if (Right.is(TT_OverloadedOperatorLParen))
3230       return spaceRequiredBeforeParens(Right);
3231     // Function declaration or definition
3232     if (Line.MightBeFunctionDecl && (Left.is(TT_FunctionDeclarationName))) {
3233       if (Line.mightBeFunctionDefinition())
3234         return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
3235                spaceRequiredBeforeParens(Right);
3236       else
3237         return Style.SpaceBeforeParensOptions.AfterFunctionDeclarationName ||
3238                spaceRequiredBeforeParens(Right);
3239     }
3240     // Lambda
3241     if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) &&
3242         Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare))
3243       return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
3244              spaceRequiredBeforeParens(Right);
3245     if (!Left.Previous || Left.Previous->isNot(tok::period)) {
3246       if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch))
3247         return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3248                spaceRequiredBeforeParens(Right);
3249       if (Left.isOneOf(tok::kw_new, tok::kw_delete) ||
3250           (Left.is(tok::r_square) && Left.MatchingParen &&
3251            Left.MatchingParen->Previous &&
3252            Left.MatchingParen->Previous->is(tok::kw_delete)))
3253         return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
3254                spaceRequiredBeforeParens(Right);
3255     }
3256     if (Line.Type != LT_PreprocessorDirective &&
3257         (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
3258          Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier()))
3259       return spaceRequiredBeforeParens(Right);
3260     return false;
3261   }
3262   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
3263     return false;
3264   if (Right.is(TT_UnaryOperator))
3265     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
3266            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
3267   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
3268                     tok::r_paren) ||
3269        Left.isSimpleTypeSpecifier()) &&
3270       Right.is(tok::l_brace) && Right.getNextNonComment() &&
3271       Right.isNot(BK_Block))
3272     return false;
3273   if (Left.is(tok::period) || Right.is(tok::period))
3274     return false;
3275   // u#str, U#str, L#str, u8#str
3276   // uR#str, UR#str, LR#str, u8R#str
3277   if (Right.is(tok::hash) && Left.is(tok::identifier) &&
3278       (Left.TokenText == "L" || Left.TokenText == "u" ||
3279        Left.TokenText == "U" || Left.TokenText == "u8" ||
3280        Left.TokenText == "LR" || Left.TokenText == "uR" ||
3281        Left.TokenText == "UR" || Left.TokenText == "u8R"))
3282     return false;
3283   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
3284       Left.MatchingParen->Previous &&
3285       (Left.MatchingParen->Previous->is(tok::period) ||
3286        Left.MatchingParen->Previous->is(tok::coloncolon)))
3287     // Java call to generic function with explicit type:
3288     // A.<B<C<...>>>DoSomething();
3289     // A::<B<C<...>>>DoSomething();  // With a Java 8 method reference.
3290     return false;
3291   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
3292     return false;
3293   if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
3294     // Objective-C dictionary literal -> no space after opening brace.
3295     return false;
3296   if (Right.is(tok::r_brace) && Right.MatchingParen &&
3297       Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
3298     // Objective-C dictionary literal -> no space before closing brace.
3299     return false;
3300   if (Right.getType() == TT_TrailingAnnotation &&
3301       Right.isOneOf(tok::amp, tok::ampamp) &&
3302       Left.isOneOf(tok::kw_const, tok::kw_volatile) &&
3303       (!Right.Next || Right.Next->is(tok::semi)))
3304     // Match const and volatile ref-qualifiers without any additional
3305     // qualifiers such as
3306     // void Fn() const &;
3307     return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
3308 
3309   return true;
3310 }
3311 
3312 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
3313                                          const FormatToken &Right) {
3314   const FormatToken &Left = *Right.Previous;
3315 
3316   // If the token is finalized don't touch it (as it could be in a
3317   // clang-format-off section).
3318   if (Left.Finalized)
3319     return Right.hasWhitespaceBefore();
3320 
3321   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
3322     return true; // Never ever merge two identifiers.
3323 
3324   // Leave a space between * and /* to avoid C4138 `comment end` found outside
3325   // of comment.
3326   if (Left.is(tok::star) && Right.is(tok::comment))
3327     return true;
3328 
3329   if (Style.isCpp()) {
3330     // Space between import <iostream>.
3331     // or import .....;
3332     if (Left.is(Keywords.kw_import) && Right.isOneOf(tok::less, tok::ellipsis))
3333       return true;
3334     // Space between `module :` and `import :`.
3335     if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) &&
3336         Right.is(TT_ModulePartitionColon))
3337       return true;
3338     // No space between import foo:bar but keep a space between import :bar;
3339     if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon))
3340       return false;
3341     // No space between :bar;
3342     if (Left.is(TT_ModulePartitionColon) &&
3343         Right.isOneOf(tok::identifier, tok::kw_private))
3344       return false;
3345     if (Left.is(tok::ellipsis) && Right.is(tok::identifier) &&
3346         Line.First->is(Keywords.kw_import))
3347       return false;
3348     // Space in __attribute__((attr)) ::type.
3349     if (Left.is(TT_AttributeParen) && Right.is(tok::coloncolon))
3350       return true;
3351 
3352     if (Left.is(tok::kw_operator))
3353       return Right.is(tok::coloncolon);
3354     if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) &&
3355         !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
3356       return true;
3357     if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) &&
3358         Right.is(TT_TemplateOpener))
3359       return true;
3360   } else if (Style.Language == FormatStyle::LK_Proto ||
3361              Style.Language == FormatStyle::LK_TextProto) {
3362     if (Right.is(tok::period) &&
3363         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
3364                      Keywords.kw_repeated, Keywords.kw_extend))
3365       return true;
3366     if (Right.is(tok::l_paren) &&
3367         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
3368       return true;
3369     if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
3370       return true;
3371     // Slashes occur in text protocol extension syntax: [type/type] { ... }.
3372     if (Left.is(tok::slash) || Right.is(tok::slash))
3373       return false;
3374     if (Left.MatchingParen &&
3375         Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
3376         Right.isOneOf(tok::l_brace, tok::less))
3377       return !Style.Cpp11BracedListStyle;
3378     // A percent is probably part of a formatting specification, such as %lld.
3379     if (Left.is(tok::percent))
3380       return false;
3381     // Preserve the existence of a space before a percent for cases like 0x%04x
3382     // and "%d %d"
3383     if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
3384       return Right.hasWhitespaceBefore();
3385   } else if (Style.isJson()) {
3386     if (Right.is(tok::colon))
3387       return false;
3388   } else if (Style.isCSharp()) {
3389     // Require spaces around '{' and  before '}' unless they appear in
3390     // interpolated strings. Interpolated strings are merged into a single token
3391     // so cannot have spaces inserted by this function.
3392 
3393     // No space between 'this' and '['
3394     if (Left.is(tok::kw_this) && Right.is(tok::l_square))
3395       return false;
3396 
3397     // No space between 'new' and '('
3398     if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
3399       return false;
3400 
3401     // Space before { (including space within '{ {').
3402     if (Right.is(tok::l_brace))
3403       return true;
3404 
3405     // Spaces inside braces.
3406     if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
3407       return true;
3408 
3409     if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
3410       return true;
3411 
3412     // Spaces around '=>'.
3413     if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow))
3414       return true;
3415 
3416     // No spaces around attribute target colons
3417     if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
3418       return false;
3419 
3420     // space between type and variable e.g. Dictionary<string,string> foo;
3421     if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
3422       return true;
3423 
3424     // spaces inside square brackets.
3425     if (Left.is(tok::l_square) || Right.is(tok::r_square))
3426       return Style.SpacesInSquareBrackets;
3427 
3428     // No space before ? in nullable types.
3429     if (Right.is(TT_CSharpNullable))
3430       return false;
3431 
3432     // No space before null forgiving '!'.
3433     if (Right.is(TT_NonNullAssertion))
3434       return false;
3435 
3436     // No space between consecutive commas '[,,]'.
3437     if (Left.is(tok::comma) && Right.is(tok::comma))
3438       return false;
3439 
3440     // space after var in `var (key, value)`
3441     if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
3442       return true;
3443 
3444     // space between keywords and paren e.g. "using ("
3445     if (Right.is(tok::l_paren))
3446       if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
3447                        Keywords.kw_lock))
3448         return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3449                spaceRequiredBeforeParens(Right);
3450 
3451     // space between method modifier and opening parenthesis of a tuple return
3452     // type
3453     if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
3454                      tok::kw_virtual, tok::kw_extern, tok::kw_static,
3455                      Keywords.kw_internal, Keywords.kw_abstract,
3456                      Keywords.kw_sealed, Keywords.kw_override,
3457                      Keywords.kw_async, Keywords.kw_unsafe) &&
3458         Right.is(tok::l_paren))
3459       return true;
3460   } else if (Style.isJavaScript()) {
3461     if (Left.is(TT_FatArrow))
3462       return true;
3463     // for await ( ...
3464     if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
3465         Left.Previous->is(tok::kw_for))
3466       return true;
3467     if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
3468         Right.MatchingParen) {
3469       const FormatToken *Next = Right.MatchingParen->getNextNonComment();
3470       // An async arrow function, for example: `x = async () => foo();`,
3471       // as opposed to calling a function called async: `x = async();`
3472       if (Next && Next->is(TT_FatArrow))
3473         return true;
3474     }
3475     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
3476         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
3477       return false;
3478     // In tagged template literals ("html`bar baz`"), there is no space between
3479     // the tag identifier and the template string.
3480     if (Keywords.IsJavaScriptIdentifier(Left,
3481                                         /* AcceptIdentifierName= */ false) &&
3482         Right.is(TT_TemplateString))
3483       return false;
3484     if (Right.is(tok::star) &&
3485         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
3486       return false;
3487     if (Right.isOneOf(tok::l_brace, tok::l_square) &&
3488         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
3489                      Keywords.kw_extends, Keywords.kw_implements))
3490       return true;
3491     if (Right.is(tok::l_paren)) {
3492       // JS methods can use some keywords as names (e.g. `delete()`).
3493       if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
3494         return false;
3495       // Valid JS method names can include keywords, e.g. `foo.delete()` or
3496       // `bar.instanceof()`. Recognize call positions by preceding period.
3497       if (Left.Previous && Left.Previous->is(tok::period) &&
3498           Left.Tok.getIdentifierInfo())
3499         return false;
3500       // Additional unary JavaScript operators that need a space after.
3501       if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
3502                        tok::kw_void))
3503         return true;
3504     }
3505     // `foo as const;` casts into a const type.
3506     if (Left.endsSequence(tok::kw_const, Keywords.kw_as))
3507       return false;
3508     if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
3509                       tok::kw_const) ||
3510          // "of" is only a keyword if it appears after another identifier
3511          // (e.g. as "const x of y" in a for loop), or after a destructuring
3512          // operation (const [x, y] of z, const {a, b} of c).
3513          (Left.is(Keywords.kw_of) && Left.Previous &&
3514           (Left.Previous->Tok.is(tok::identifier) ||
3515            Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
3516         (!Left.Previous || !Left.Previous->is(tok::period)))
3517       return true;
3518     if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
3519         Left.Previous->is(tok::period) && Right.is(tok::l_paren))
3520       return false;
3521     if (Left.is(Keywords.kw_as) &&
3522         Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
3523       return true;
3524     if (Left.is(tok::kw_default) && Left.Previous &&
3525         Left.Previous->is(tok::kw_export))
3526       return true;
3527     if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
3528       return true;
3529     if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
3530       return false;
3531     if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
3532       return false;
3533     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
3534         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
3535       return false;
3536     if (Left.is(tok::ellipsis))
3537       return false;
3538     if (Left.is(TT_TemplateCloser) &&
3539         !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
3540                        Keywords.kw_implements, Keywords.kw_extends))
3541       // Type assertions ('<type>expr') are not followed by whitespace. Other
3542       // locations that should have whitespace following are identified by the
3543       // above set of follower tokens.
3544       return false;
3545     if (Right.is(TT_NonNullAssertion))
3546       return false;
3547     if (Left.is(TT_NonNullAssertion) &&
3548         Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
3549       return true; // "x! as string", "x! in y"
3550   } else if (Style.Language == FormatStyle::LK_Java) {
3551     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
3552       return true;
3553     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
3554       return Style.SpaceBeforeParensOptions.AfterControlStatements ||
3555              spaceRequiredBeforeParens(Right);
3556     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
3557                       tok::kw_protected) ||
3558          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
3559                       Keywords.kw_native)) &&
3560         Right.is(TT_TemplateOpener))
3561       return true;
3562   }
3563   if (Left.is(TT_ImplicitStringLiteral))
3564     return Right.hasWhitespaceBefore();
3565   if (Line.Type == LT_ObjCMethodDecl) {
3566     if (Left.is(TT_ObjCMethodSpecifier))
3567       return true;
3568     if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
3569       // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
3570       // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
3571       // method declaration.
3572       return false;
3573   }
3574   if (Line.Type == LT_ObjCProperty &&
3575       (Right.is(tok::equal) || Left.is(tok::equal)))
3576     return false;
3577 
3578   if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
3579       Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
3580     return true;
3581   if (Left.is(tok::comma) && !Right.is(TT_OverloadedOperatorLParen))
3582     return true;
3583   if (Right.is(tok::comma))
3584     return false;
3585   if (Right.is(TT_ObjCBlockLParen))
3586     return true;
3587   if (Right.is(TT_CtorInitializerColon))
3588     return Style.SpaceBeforeCtorInitializerColon;
3589   if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
3590     return false;
3591   if (Right.is(TT_RangeBasedForLoopColon) &&
3592       !Style.SpaceBeforeRangeBasedForLoopColon)
3593     return false;
3594   if (Left.is(TT_BitFieldColon))
3595     return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
3596            Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
3597   if (Right.is(tok::colon)) {
3598     if (Line.First->isOneOf(tok::kw_default, tok::kw_case))
3599       return Style.SpaceBeforeCaseColon;
3600     if (!Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
3601       return false;
3602     if (Right.is(TT_ObjCMethodExpr))
3603       return false;
3604     if (Left.is(tok::question))
3605       return false;
3606     if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
3607       return false;
3608     if (Right.is(TT_DictLiteral))
3609       return Style.SpacesInContainerLiterals;
3610     if (Right.is(TT_AttributeColon))
3611       return false;
3612     if (Right.is(TT_CSharpNamedArgumentColon))
3613       return false;
3614     if (Right.is(TT_BitFieldColon))
3615       return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
3616              Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
3617     return true;
3618   }
3619   // Do not merge "- -" into "--".
3620   if ((Left.isOneOf(tok::minus, tok::minusminus) &&
3621        Right.isOneOf(tok::minus, tok::minusminus)) ||
3622       (Left.isOneOf(tok::plus, tok::plusplus) &&
3623        Right.isOneOf(tok::plus, tok::plusplus)))
3624     return true;
3625   if (Left.is(TT_UnaryOperator)) {
3626     if (!Right.is(tok::l_paren)) {
3627       // The alternative operators for ~ and ! are "compl" and "not".
3628       // If they are used instead, we do not want to combine them with
3629       // the token to the right, unless that is a left paren.
3630       if (Left.is(tok::exclaim) && Left.TokenText == "not")
3631         return true;
3632       if (Left.is(tok::tilde) && Left.TokenText == "compl")
3633         return true;
3634       // Lambda captures allow for a lone &, so "&]" needs to be properly
3635       // handled.
3636       if (Left.is(tok::amp) && Right.is(tok::r_square))
3637         return Style.SpacesInSquareBrackets;
3638     }
3639     return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
3640            Right.is(TT_BinaryOperator);
3641   }
3642 
3643   // If the next token is a binary operator or a selector name, we have
3644   // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
3645   if (Left.is(TT_CastRParen))
3646     return Style.SpaceAfterCStyleCast ||
3647            Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
3648 
3649   auto ShouldAddSpacesInAngles = [this, &Right]() {
3650     if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always)
3651       return true;
3652     if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave)
3653       return Right.hasWhitespaceBefore();
3654     return false;
3655   };
3656 
3657   if (Left.is(tok::greater) && Right.is(tok::greater)) {
3658     if (Style.Language == FormatStyle::LK_TextProto ||
3659         (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
3660       return !Style.Cpp11BracedListStyle;
3661     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
3662            ((Style.Standard < FormatStyle::LS_Cpp11) ||
3663             ShouldAddSpacesInAngles());
3664   }
3665   if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
3666       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
3667       (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
3668     return false;
3669   if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
3670       Right.getPrecedence() == prec::Assignment)
3671     return false;
3672   if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) &&
3673       (Left.is(tok::identifier) || Left.is(tok::kw_this)))
3674     return false;
3675   if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
3676     // Generally don't remove existing spaces between an identifier and "::".
3677     // The identifier might actually be a macro name such as ALWAYS_INLINE. If
3678     // this turns out to be too lenient, add analysis of the identifier itself.
3679     return Right.hasWhitespaceBefore();
3680   if (Right.is(tok::coloncolon) &&
3681       !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren))
3682     // Put a space between < and :: in vector< ::std::string >
3683     return (Left.is(TT_TemplateOpener) &&
3684             ((Style.Standard < FormatStyle::LS_Cpp11) ||
3685              ShouldAddSpacesInAngles())) ||
3686            !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
3687                           tok::kw___super, TT_TemplateOpener,
3688                           TT_TemplateCloser)) ||
3689            (Left.is(tok::l_paren) && Style.SpacesInParentheses);
3690   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
3691     return ShouldAddSpacesInAngles();
3692   // Space before TT_StructuredBindingLSquare.
3693   if (Right.is(TT_StructuredBindingLSquare))
3694     return !Left.isOneOf(tok::amp, tok::ampamp) ||
3695            getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right;
3696   // Space before & or && following a TT_StructuredBindingLSquare.
3697   if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
3698       Right.isOneOf(tok::amp, tok::ampamp))
3699     return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
3700   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
3701       (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
3702        !Right.is(tok::r_paren)))
3703     return true;
3704   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
3705       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
3706     return false;
3707   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
3708       Line.startsWith(tok::hash))
3709     return true;
3710   if (Right.is(TT_TrailingUnaryOperator))
3711     return false;
3712   if (Left.is(TT_RegexLiteral))
3713     return false;
3714   return spaceRequiredBetween(Line, Left, Right);
3715 }
3716 
3717 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
3718 static bool isAllmanBrace(const FormatToken &Tok) {
3719   return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
3720          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
3721 }
3722 
3723 // Returns 'true' if 'Tok' is a function argument.
3724 static bool IsFunctionArgument(const FormatToken &Tok) {
3725   return Tok.MatchingParen && Tok.MatchingParen->Next &&
3726          Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren);
3727 }
3728 
3729 static bool
3730 isItAnEmptyLambdaAllowed(const FormatToken &Tok,
3731                          FormatStyle::ShortLambdaStyle ShortLambdaOption) {
3732   return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
3733 }
3734 
3735 static bool isAllmanLambdaBrace(const FormatToken &Tok) {
3736   return (Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
3737           !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral));
3738 }
3739 
3740 // Returns the first token on the line that is not a comment.
3741 static const FormatToken *getFirstNonComment(const AnnotatedLine &Line) {
3742   const FormatToken *Next = Line.First;
3743   if (!Next)
3744     return Next;
3745   if (Next->is(tok::comment))
3746     Next = Next->getNextNonComment();
3747   return Next;
3748 }
3749 
3750 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
3751                                      const FormatToken &Right) {
3752   const FormatToken &Left = *Right.Previous;
3753   if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
3754     return true;
3755 
3756   if (Style.isCSharp()) {
3757     if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) &&
3758         Style.BraceWrapping.AfterFunction)
3759       return true;
3760     if (Right.is(TT_CSharpNamedArgumentColon) ||
3761         Left.is(TT_CSharpNamedArgumentColon))
3762       return false;
3763     if (Right.is(TT_CSharpGenericTypeConstraint))
3764       return true;
3765     if (Right.Next && Right.Next->is(TT_FatArrow) &&
3766         (Right.is(tok::numeric_constant) ||
3767          (Right.is(tok::identifier) && Right.TokenText == "_")))
3768       return true;
3769 
3770     // Break after C# [...] and before public/protected/private/internal.
3771     if (Left.is(TT_AttributeSquare) && Left.is(tok::r_square) &&
3772         (Right.isAccessSpecifier(/*ColonRequired=*/false) ||
3773          Right.is(Keywords.kw_internal)))
3774       return true;
3775     // Break between ] and [ but only when there are really 2 attributes.
3776     if (Left.is(TT_AttributeSquare) && Right.is(TT_AttributeSquare) &&
3777         Left.is(tok::r_square) && Right.is(tok::l_square))
3778       return true;
3779 
3780   } else if (Style.isJavaScript()) {
3781     // FIXME: This might apply to other languages and token kinds.
3782     if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
3783         Left.Previous->is(tok::string_literal))
3784       return true;
3785     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
3786         Left.Previous && Left.Previous->is(tok::equal) &&
3787         Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
3788                             tok::kw_const) &&
3789         // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
3790         // above.
3791         !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
3792       // Object literals on the top level of a file are treated as "enum-style".
3793       // Each key/value pair is put on a separate line, instead of bin-packing.
3794       return true;
3795     if (Left.is(tok::l_brace) && Line.Level == 0 &&
3796         (Line.startsWith(tok::kw_enum) ||
3797          Line.startsWith(tok::kw_const, tok::kw_enum) ||
3798          Line.startsWith(tok::kw_export, tok::kw_enum) ||
3799          Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
3800       // JavaScript top-level enum key/value pairs are put on separate lines
3801       // instead of bin-packing.
3802       return true;
3803     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous &&
3804         Left.Previous->is(TT_FatArrow)) {
3805       // JS arrow function (=> {...}).
3806       switch (Style.AllowShortLambdasOnASingleLine) {
3807       case FormatStyle::SLS_All:
3808         return false;
3809       case FormatStyle::SLS_None:
3810         return true;
3811       case FormatStyle::SLS_Empty:
3812         return !Left.Children.empty();
3813       case FormatStyle::SLS_Inline:
3814         // allow one-lining inline (e.g. in function call args) and empty arrow
3815         // functions.
3816         return (Left.NestingLevel == 0 && Line.Level == 0) &&
3817                !Left.Children.empty();
3818       }
3819       llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
3820     }
3821 
3822     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
3823         !Left.Children.empty())
3824       // Support AllowShortFunctionsOnASingleLine for JavaScript.
3825       return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
3826              Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
3827              (Left.NestingLevel == 0 && Line.Level == 0 &&
3828               Style.AllowShortFunctionsOnASingleLine &
3829                   FormatStyle::SFS_InlineOnly);
3830   } else if (Style.Language == FormatStyle::LK_Java) {
3831     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
3832         Right.Next->is(tok::string_literal))
3833       return true;
3834   } else if (Style.Language == FormatStyle::LK_Cpp ||
3835              Style.Language == FormatStyle::LK_ObjC ||
3836              Style.Language == FormatStyle::LK_Proto ||
3837              Style.Language == FormatStyle::LK_TableGen ||
3838              Style.Language == FormatStyle::LK_TextProto) {
3839     if (Left.isStringLiteral() && Right.isStringLiteral())
3840       return true;
3841   }
3842 
3843   // Basic JSON newline processing.
3844   if (Style.isJson()) {
3845     // Always break after a JSON record opener.
3846     // {
3847     // }
3848     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace))
3849       return true;
3850     // Always break after a JSON array opener.
3851     // [
3852     // ]
3853     if (Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) &&
3854         !Right.is(tok::r_square))
3855       return true;
3856     // Always break after successive entries.
3857     // 1,
3858     // 2
3859     if (Left.is(tok::comma))
3860       return true;
3861   }
3862 
3863   // If the last token before a '}', ']', or ')' is a comma or a trailing
3864   // comment, the intention is to insert a line break after it in order to make
3865   // shuffling around entries easier. Import statements, especially in
3866   // JavaScript, can be an exception to this rule.
3867   if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
3868     const FormatToken *BeforeClosingBrace = nullptr;
3869     if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
3870          (Style.isJavaScript() && Left.is(tok::l_paren))) &&
3871         Left.isNot(BK_Block) && Left.MatchingParen)
3872       BeforeClosingBrace = Left.MatchingParen->Previous;
3873     else if (Right.MatchingParen &&
3874              (Right.MatchingParen->isOneOf(tok::l_brace,
3875                                            TT_ArrayInitializerLSquare) ||
3876               (Style.isJavaScript() && Right.MatchingParen->is(tok::l_paren))))
3877       BeforeClosingBrace = &Left;
3878     if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
3879                                BeforeClosingBrace->isTrailingComment()))
3880       return true;
3881   }
3882 
3883   if (Right.is(tok::comment))
3884     return Left.isNot(BK_BracedInit) && Left.isNot(TT_CtorInitializerColon) &&
3885            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
3886   if (Left.isTrailingComment())
3887     return true;
3888   if (Left.IsUnterminatedLiteral)
3889     return true;
3890   if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&
3891       Right.Next->is(tok::string_literal))
3892     return true;
3893   // Can break after template<> declaration
3894   if (Left.ClosesTemplateDeclaration && Left.MatchingParen &&
3895       Left.MatchingParen->NestingLevel == 0) {
3896     // Put concepts on the next line e.g.
3897     // template<typename T>
3898     // concept ...
3899     if (Right.is(tok::kw_concept))
3900       return Style.BreakBeforeConceptDeclarations;
3901     return (Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes);
3902   }
3903   if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) {
3904     if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon &&
3905         (Left.is(TT_CtorInitializerComma) || Right.is(TT_CtorInitializerColon)))
3906       return true;
3907 
3908     if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
3909         Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma))
3910       return true;
3911   }
3912   if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine &&
3913       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3914       Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon))
3915     return true;
3916   // Break only if we have multiple inheritance.
3917   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
3918       Right.is(TT_InheritanceComma))
3919     return true;
3920   if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
3921       Left.is(TT_InheritanceComma))
3922     return true;
3923   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
3924     // Multiline raw string literals are special wrt. line breaks. The author
3925     // has made a deliberate choice and might have aligned the contents of the
3926     // string literal accordingly. Thus, we try keep existing line breaks.
3927     return Right.IsMultiline && Right.NewlinesBefore > 0;
3928   if ((Left.is(tok::l_brace) || (Left.is(tok::less) && Left.Previous &&
3929                                  Left.Previous->is(tok::equal))) &&
3930       Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
3931     // Don't put enums or option definitions onto single lines in protocol
3932     // buffers.
3933     return true;
3934   }
3935   if (Right.is(TT_InlineASMBrace))
3936     return Right.HasUnescapedNewline;
3937 
3938   if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
3939     auto FirstNonComment = getFirstNonComment(Line);
3940     bool AccessSpecifier =
3941         FirstNonComment &&
3942         FirstNonComment->isOneOf(Keywords.kw_internal, tok::kw_public,
3943                                  tok::kw_private, tok::kw_protected);
3944 
3945     if (Style.BraceWrapping.AfterEnum) {
3946       if (Line.startsWith(tok::kw_enum) ||
3947           Line.startsWith(tok::kw_typedef, tok::kw_enum))
3948         return true;
3949       // Ensure BraceWrapping for `public enum A {`.
3950       if (AccessSpecifier && FirstNonComment->Next &&
3951           FirstNonComment->Next->is(tok::kw_enum))
3952         return true;
3953     }
3954 
3955     // Ensure BraceWrapping for `public interface A {`.
3956     if (Style.BraceWrapping.AfterClass &&
3957         ((AccessSpecifier && FirstNonComment->Next &&
3958           FirstNonComment->Next->is(Keywords.kw_interface)) ||
3959          Line.startsWith(Keywords.kw_interface)))
3960       return true;
3961 
3962     return (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
3963            (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
3964   }
3965 
3966   if (Left.is(TT_ObjCBlockLBrace) &&
3967       Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
3968     return true;
3969 
3970   // Ensure wrapping after __attribute__((XX)) and @interface etc.
3971   if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
3972     return true;
3973 
3974   if (Left.is(TT_LambdaLBrace)) {
3975     if (IsFunctionArgument(Left) &&
3976         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
3977       return false;
3978 
3979     if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
3980         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
3981         (!Left.Children.empty() &&
3982          Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty))
3983       return true;
3984   }
3985 
3986   if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) &&
3987       Left.isOneOf(tok::star, tok::amp, tok::ampamp, TT_TemplateCloser))
3988     return true;
3989 
3990   // Put multiple Java annotation on a new line.
3991   if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
3992       Left.is(TT_LeadingJavaAnnotation) &&
3993       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
3994       (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
3995     return true;
3996 
3997   if (Right.is(TT_ProtoExtensionLSquare))
3998     return true;
3999 
4000   // In text proto instances if a submessage contains at least 2 entries and at
4001   // least one of them is a submessage, like A { ... B { ... } ... },
4002   // put all of the entries of A on separate lines by forcing the selector of
4003   // the submessage B to be put on a newline.
4004   //
4005   // Example: these can stay on one line:
4006   // a { scalar_1: 1 scalar_2: 2 }
4007   // a { b { key: value } }
4008   //
4009   // and these entries need to be on a new line even if putting them all in one
4010   // line is under the column limit:
4011   // a {
4012   //   scalar: 1
4013   //   b { key: value }
4014   // }
4015   //
4016   // We enforce this by breaking before a submessage field that has previous
4017   // siblings, *and* breaking before a field that follows a submessage field.
4018   //
4019   // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
4020   // the TT_SelectorName there, but we don't want to break inside the brackets.
4021   //
4022   // Another edge case is @submessage { key: value }, which is a common
4023   // substitution placeholder. In this case we want to keep `@` and `submessage`
4024   // together.
4025   //
4026   // We ensure elsewhere that extensions are always on their own line.
4027   if ((Style.Language == FormatStyle::LK_Proto ||
4028        Style.Language == FormatStyle::LK_TextProto) &&
4029       Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
4030     // Keep `@submessage` together in:
4031     // @submessage { key: value }
4032     if (Left.is(tok::at))
4033       return false;
4034     // Look for the scope opener after selector in cases like:
4035     // selector { ...
4036     // selector: { ...
4037     // selector: @base { ...
4038     FormatToken *LBrace = Right.Next;
4039     if (LBrace && LBrace->is(tok::colon)) {
4040       LBrace = LBrace->Next;
4041       if (LBrace && LBrace->is(tok::at)) {
4042         LBrace = LBrace->Next;
4043         if (LBrace)
4044           LBrace = LBrace->Next;
4045       }
4046     }
4047     if (LBrace &&
4048         // The scope opener is one of {, [, <:
4049         // selector { ... }
4050         // selector [ ... ]
4051         // selector < ... >
4052         //
4053         // In case of selector { ... }, the l_brace is TT_DictLiteral.
4054         // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
4055         // so we check for immediately following r_brace.
4056         ((LBrace->is(tok::l_brace) &&
4057           (LBrace->is(TT_DictLiteral) ||
4058            (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
4059          LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
4060       // If Left.ParameterCount is 0, then this submessage entry is not the
4061       // first in its parent submessage, and we want to break before this entry.
4062       // If Left.ParameterCount is greater than 0, then its parent submessage
4063       // might contain 1 or more entries and we want to break before this entry
4064       // if it contains at least 2 entries. We deal with this case later by
4065       // detecting and breaking before the next entry in the parent submessage.
4066       if (Left.ParameterCount == 0)
4067         return true;
4068       // However, if this submessage is the first entry in its parent
4069       // submessage, Left.ParameterCount might be 1 in some cases.
4070       // We deal with this case later by detecting an entry
4071       // following a closing paren of this submessage.
4072     }
4073 
4074     // If this is an entry immediately following a submessage, it will be
4075     // preceded by a closing paren of that submessage, like in:
4076     //     left---.  .---right
4077     //            v  v
4078     // sub: { ... } key: value
4079     // If there was a comment between `}` an `key` above, then `key` would be
4080     // put on a new line anyways.
4081     if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
4082       return true;
4083   }
4084 
4085   // Deal with lambda arguments in C++ - we want consistent line breaks whether
4086   // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
4087   // as aggressive line breaks are placed when the lambda is not the last arg.
4088   if ((Style.Language == FormatStyle::LK_Cpp ||
4089        Style.Language == FormatStyle::LK_ObjC) &&
4090       Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
4091       !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
4092     // Multiple lambdas in the same function call force line breaks.
4093     if (Left.BlockParameterCount > 1)
4094       return true;
4095 
4096     // A lambda followed by another arg forces a line break.
4097     if (!Left.Role)
4098       return false;
4099     auto Comma = Left.Role->lastComma();
4100     if (!Comma)
4101       return false;
4102     auto Next = Comma->getNextNonComment();
4103     if (!Next)
4104       return false;
4105     if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
4106       return true;
4107   }
4108 
4109   return false;
4110 }
4111 
4112 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
4113                                     const FormatToken &Right) {
4114   const FormatToken &Left = *Right.Previous;
4115   // Language-specific stuff.
4116   if (Style.isCSharp()) {
4117     if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
4118         Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon))
4119       return false;
4120     // Only break after commas for generic type constraints.
4121     if (Line.First->is(TT_CSharpGenericTypeConstraint))
4122       return Left.is(TT_CSharpGenericTypeConstraintComma);
4123     // Keep nullable operators attached to their identifiers.
4124     if (Right.is(TT_CSharpNullable))
4125       return false;
4126   } else if (Style.Language == FormatStyle::LK_Java) {
4127     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
4128                      Keywords.kw_implements))
4129       return false;
4130     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
4131                       Keywords.kw_implements))
4132       return true;
4133   } else if (Style.isJavaScript()) {
4134     const FormatToken *NonComment = Right.getPreviousNonComment();
4135     if (NonComment &&
4136         NonComment->isOneOf(
4137             tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
4138             tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
4139             tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
4140             Keywords.kw_readonly, Keywords.kw_override, Keywords.kw_abstract,
4141             Keywords.kw_get, Keywords.kw_set, Keywords.kw_async,
4142             Keywords.kw_await))
4143       return false; // Otherwise automatic semicolon insertion would trigger.
4144     if (Right.NestingLevel == 0 &&
4145         (Left.Tok.getIdentifierInfo() ||
4146          Left.isOneOf(tok::r_square, tok::r_paren)) &&
4147         Right.isOneOf(tok::l_square, tok::l_paren))
4148       return false; // Otherwise automatic semicolon insertion would trigger.
4149     if (NonComment && NonComment->is(tok::identifier) &&
4150         NonComment->TokenText == "asserts")
4151       return false;
4152     if (Left.is(TT_FatArrow) && Right.is(tok::l_brace))
4153       return false;
4154     if (Left.is(TT_JsTypeColon))
4155       return true;
4156     // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
4157     if (Left.is(tok::exclaim) && Right.is(tok::colon))
4158       return false;
4159     // Look for is type annotations like:
4160     // function f(): a is B { ... }
4161     // Do not break before is in these cases.
4162     if (Right.is(Keywords.kw_is)) {
4163       const FormatToken *Next = Right.getNextNonComment();
4164       // If `is` is followed by a colon, it's likely that it's a dict key, so
4165       // ignore it for this check.
4166       // For example this is common in Polymer:
4167       // Polymer({
4168       //   is: 'name',
4169       //   ...
4170       // });
4171       if (!Next || !Next->is(tok::colon))
4172         return false;
4173     }
4174     if (Left.is(Keywords.kw_in))
4175       return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
4176     if (Right.is(Keywords.kw_in))
4177       return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
4178     if (Right.is(Keywords.kw_as))
4179       return false; // must not break before as in 'x as type' casts
4180     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
4181       // extends and infer can appear as keywords in conditional types:
4182       //   https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
4183       // do not break before them, as the expressions are subject to ASI.
4184       return false;
4185     }
4186     if (Left.is(Keywords.kw_as))
4187       return true;
4188     if (Left.is(TT_NonNullAssertion))
4189       return true;
4190     if (Left.is(Keywords.kw_declare) &&
4191         Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
4192                       Keywords.kw_function, tok::kw_class, tok::kw_enum,
4193                       Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
4194                       Keywords.kw_let, tok::kw_const))
4195       // See grammar for 'declare' statements at:
4196       // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10
4197       return false;
4198     if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
4199         Right.isOneOf(tok::identifier, tok::string_literal))
4200       return false; // must not break in "module foo { ...}"
4201     if (Right.is(TT_TemplateString) && Right.closesScope())
4202       return false;
4203     // Don't split tagged template literal so there is a break between the tag
4204     // identifier and template string.
4205     if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
4206       return false;
4207     if (Left.is(TT_TemplateString) && Left.opensScope())
4208       return true;
4209   }
4210 
4211   if (Left.is(tok::at))
4212     return false;
4213   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
4214     return false;
4215   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
4216     return !Right.is(tok::l_paren);
4217   if (Right.is(TT_PointerOrReference))
4218     return Line.IsMultiVariableDeclStmt ||
4219            (getTokenPointerOrReferenceAlignment(Right) ==
4220                 FormatStyle::PAS_Right &&
4221             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
4222   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
4223       Right.is(tok::kw_operator))
4224     return true;
4225   if (Left.is(TT_PointerOrReference))
4226     return false;
4227   if (Right.isTrailingComment())
4228     // We rely on MustBreakBefore being set correctly here as we should not
4229     // change the "binding" behavior of a comment.
4230     // The first comment in a braced lists is always interpreted as belonging to
4231     // the first list element. Otherwise, it should be placed outside of the
4232     // list.
4233     return Left.is(BK_BracedInit) ||
4234            (Left.is(TT_CtorInitializerColon) &&
4235             Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
4236   if (Left.is(tok::question) && Right.is(tok::colon))
4237     return false;
4238   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
4239     return Style.BreakBeforeTernaryOperators;
4240   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
4241     return !Style.BreakBeforeTernaryOperators;
4242   if (Left.is(TT_InheritanceColon))
4243     return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
4244   if (Right.is(TT_InheritanceColon))
4245     return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
4246   if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
4247       Left.isNot(TT_SelectorName))
4248     return true;
4249 
4250   if (Right.is(tok::colon) &&
4251       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
4252     return false;
4253   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
4254     if (Style.Language == FormatStyle::LK_Proto ||
4255         Style.Language == FormatStyle::LK_TextProto) {
4256       if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
4257         return false;
4258       // Prevent cases like:
4259       //
4260       // submessage:
4261       //     { key: valueeeeeeeeeeee }
4262       //
4263       // when the snippet does not fit into one line.
4264       // Prefer:
4265       //
4266       // submessage: {
4267       //   key: valueeeeeeeeeeee
4268       // }
4269       //
4270       // instead, even if it is longer by one line.
4271       //
4272       // Note that this allows allows the "{" to go over the column limit
4273       // when the column limit is just between ":" and "{", but that does
4274       // not happen too often and alternative formattings in this case are
4275       // not much better.
4276       //
4277       // The code covers the cases:
4278       //
4279       // submessage: { ... }
4280       // submessage: < ... >
4281       // repeated: [ ... ]
4282       if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
4283            Right.is(TT_DictLiteral)) ||
4284           Right.is(TT_ArrayInitializerLSquare))
4285         return false;
4286     }
4287     return true;
4288   }
4289   if (Right.is(tok::r_square) && Right.MatchingParen &&
4290       Right.MatchingParen->is(TT_ProtoExtensionLSquare))
4291     return false;
4292   if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
4293                                     Right.Next->is(TT_ObjCMethodExpr)))
4294     return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
4295   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
4296     return true;
4297   if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
4298     return true;
4299   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
4300                     TT_OverloadedOperator))
4301     return false;
4302   if (Left.is(TT_RangeBasedForLoopColon))
4303     return true;
4304   if (Right.is(TT_RangeBasedForLoopColon))
4305     return false;
4306   if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
4307     return true;
4308   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
4309       Left.is(tok::kw_operator))
4310     return false;
4311   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
4312       Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
4313     return false;
4314   if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
4315       !Style.Cpp11BracedListStyle)
4316     return false;
4317   if (Left.is(tok::l_paren) &&
4318       Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen))
4319     return false;
4320   if (Left.is(tok::l_paren) && Left.Previous &&
4321       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
4322     return false;
4323   if (Right.is(TT_ImplicitStringLiteral))
4324     return false;
4325 
4326   if (Right.is(TT_TemplateCloser))
4327     return false;
4328   if (Right.is(tok::r_square) && Right.MatchingParen &&
4329       Right.MatchingParen->is(TT_LambdaLSquare))
4330     return false;
4331 
4332   // We only break before r_brace if there was a corresponding break before
4333   // the l_brace, which is tracked by BreakBeforeClosingBrace.
4334   if (Right.is(tok::r_brace))
4335     return Right.MatchingParen && Right.MatchingParen->is(BK_Block);
4336 
4337   // We only break before r_paren if we're in a block indented context.
4338   if (Right.is(tok::r_paren)) {
4339     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) {
4340       return Right.MatchingParen &&
4341              !(Right.MatchingParen->Previous &&
4342                (Right.MatchingParen->Previous->is(tok::kw_for) ||
4343                 Right.MatchingParen->Previous->isIf()));
4344     }
4345 
4346     return false;
4347   }
4348 
4349   // Allow breaking after a trailing annotation, e.g. after a method
4350   // declaration.
4351   if (Left.is(TT_TrailingAnnotation))
4352     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
4353                           tok::less, tok::coloncolon);
4354 
4355   if (Right.is(tok::kw___attribute) ||
4356       (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
4357     return !Left.is(TT_AttributeSquare);
4358 
4359   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
4360     return true;
4361 
4362   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
4363     return true;
4364 
4365   if (Left.is(TT_CtorInitializerColon))
4366     return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
4367   if (Right.is(TT_CtorInitializerColon))
4368     return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
4369   if (Left.is(TT_CtorInitializerComma) &&
4370       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
4371     return false;
4372   if (Right.is(TT_CtorInitializerComma) &&
4373       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
4374     return true;
4375   if (Left.is(TT_InheritanceComma) &&
4376       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
4377     return false;
4378   if (Right.is(TT_InheritanceComma) &&
4379       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
4380     return true;
4381   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
4382       (Left.is(tok::less) && Right.is(tok::less)))
4383     return false;
4384   if (Right.is(TT_BinaryOperator) &&
4385       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
4386       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
4387        Right.getPrecedence() != prec::Assignment))
4388     return true;
4389   if (Left.is(TT_ArrayInitializerLSquare))
4390     return true;
4391   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
4392     return true;
4393   if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
4394       !Left.isOneOf(tok::arrowstar, tok::lessless) &&
4395       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
4396       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
4397        Left.getPrecedence() == prec::Assignment))
4398     return true;
4399   if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
4400       (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
4401     return false;
4402 
4403   auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
4404   if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) {
4405     if (isAllmanLambdaBrace(Left))
4406       return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption);
4407     if (isAllmanLambdaBrace(Right))
4408       return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption);
4409   }
4410 
4411   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
4412                       tok::kw_class, tok::kw_struct, tok::comment) ||
4413          Right.isMemberAccess() ||
4414          Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
4415                        tok::colon, tok::l_square, tok::at) ||
4416          (Left.is(tok::r_paren) &&
4417           Right.isOneOf(tok::identifier, tok::kw_const)) ||
4418          (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
4419          (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
4420 }
4421 
4422 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
4423   llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
4424   const FormatToken *Tok = Line.First;
4425   while (Tok) {
4426     llvm::errs() << " M=" << Tok->MustBreakBefore
4427                  << " C=" << Tok->CanBreakBefore
4428                  << " T=" << getTokenTypeName(Tok->getType())
4429                  << " S=" << Tok->SpacesRequiredBefore
4430                  << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
4431                  << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
4432                  << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
4433                  << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
4434     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
4435       llvm::errs() << Tok->FakeLParens[i] << "/";
4436     llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
4437     llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
4438     llvm::errs() << " Text='" << Tok->TokenText << "'\n";
4439     if (!Tok->Next)
4440       assert(Tok == Line.Last);
4441     Tok = Tok->Next;
4442   }
4443   llvm::errs() << "----\n";
4444 }
4445 
4446 FormatStyle::PointerAlignmentStyle
4447 TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) {
4448   assert(Reference.isOneOf(tok::amp, tok::ampamp));
4449   switch (Style.ReferenceAlignment) {
4450   case FormatStyle::RAS_Pointer:
4451     return Style.PointerAlignment;
4452   case FormatStyle::RAS_Left:
4453     return FormatStyle::PAS_Left;
4454   case FormatStyle::RAS_Right:
4455     return FormatStyle::PAS_Right;
4456   case FormatStyle::RAS_Middle:
4457     return FormatStyle::PAS_Middle;
4458   }
4459   assert(0); //"Unhandled value of ReferenceAlignment"
4460   return Style.PointerAlignment;
4461 }
4462 
4463 FormatStyle::PointerAlignmentStyle
4464 TokenAnnotator::getTokenPointerOrReferenceAlignment(
4465     const FormatToken &PointerOrReference) {
4466   if (PointerOrReference.isOneOf(tok::amp, tok::ampamp)) {
4467     switch (Style.ReferenceAlignment) {
4468     case FormatStyle::RAS_Pointer:
4469       return Style.PointerAlignment;
4470     case FormatStyle::RAS_Left:
4471       return FormatStyle::PAS_Left;
4472     case FormatStyle::RAS_Right:
4473       return FormatStyle::PAS_Right;
4474     case FormatStyle::RAS_Middle:
4475       return FormatStyle::PAS_Middle;
4476     }
4477   }
4478   assert(PointerOrReference.is(tok::star));
4479   return Style.PointerAlignment;
4480 }
4481 
4482 } // namespace format
4483 } // namespace clang
4484