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