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