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