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