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       if (Tok->is(Keywords.kw_where) && Tok->Next &&
1051           Tok->Next->isNot(tok::l_paren)) {
1052         Tok->Type = TT_CSharpGenericTypeConstraint;
1053         parseCSharpGenericTypeConstraint();
1054       }
1055       break;
1056     default:
1057       break;
1058     }
1059     return true;
1060   }
1061 
1062   void parseCSharpGenericTypeConstraint() {
1063     while (CurrentToken) {
1064       if (CurrentToken->is(tok::less)) {
1065         // parseAngle is too greedy and will consume the whole line.
1066         CurrentToken->Type = TT_TemplateOpener;
1067         next();
1068       } else if (CurrentToken->is(tok::greater)) {
1069         CurrentToken->Type = TT_TemplateCloser;
1070         next();
1071       } else if (CurrentToken->is(tok::comma)) {
1072         CurrentToken->Type = TT_CSharpGenericTypeConstraintComma;
1073         next();
1074       } else if (CurrentToken->is(Keywords.kw_where)) {
1075         CurrentToken->Type = TT_CSharpGenericTypeConstraint;
1076         next();
1077       } else if (CurrentToken->is(tok::colon)) {
1078         CurrentToken->Type = TT_CSharpGenericTypeConstraintColon;
1079         next();
1080       } else {
1081         next();
1082       }
1083     }
1084   }
1085 
1086   void parseIncludeDirective() {
1087     if (CurrentToken && CurrentToken->is(tok::less)) {
1088       next();
1089       while (CurrentToken) {
1090         // Mark tokens up to the trailing line comments as implicit string
1091         // literals.
1092         if (CurrentToken->isNot(tok::comment) &&
1093             !CurrentToken->TokenText.startswith("//"))
1094           CurrentToken->Type = TT_ImplicitStringLiteral;
1095         next();
1096       }
1097     }
1098   }
1099 
1100   void parseWarningOrError() {
1101     next();
1102     // We still want to format the whitespace left of the first token of the
1103     // warning or error.
1104     next();
1105     while (CurrentToken) {
1106       CurrentToken->Type = TT_ImplicitStringLiteral;
1107       next();
1108     }
1109   }
1110 
1111   void parsePragma() {
1112     next(); // Consume "pragma".
1113     if (CurrentToken &&
1114         CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
1115       bool IsMark = CurrentToken->is(Keywords.kw_mark);
1116       next(); // Consume "mark".
1117       next(); // Consume first token (so we fix leading whitespace).
1118       while (CurrentToken) {
1119         if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
1120           CurrentToken->Type = TT_ImplicitStringLiteral;
1121         next();
1122       }
1123     }
1124   }
1125 
1126   void parseHasInclude() {
1127     if (!CurrentToken || !CurrentToken->is(tok::l_paren))
1128       return;
1129     next(); // '('
1130     parseIncludeDirective();
1131     next(); // ')'
1132   }
1133 
1134   LineType parsePreprocessorDirective() {
1135     bool IsFirstToken = CurrentToken->IsFirst;
1136     LineType Type = LT_PreprocessorDirective;
1137     next();
1138     if (!CurrentToken)
1139       return Type;
1140 
1141     if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
1142       // JavaScript files can contain shebang lines of the form:
1143       // #!/usr/bin/env node
1144       // Treat these like C++ #include directives.
1145       while (CurrentToken) {
1146         // Tokens cannot be comments here.
1147         CurrentToken->Type = TT_ImplicitStringLiteral;
1148         next();
1149       }
1150       return LT_ImportStatement;
1151     }
1152 
1153     if (CurrentToken->Tok.is(tok::numeric_constant)) {
1154       CurrentToken->SpacesRequiredBefore = 1;
1155       return Type;
1156     }
1157     // Hashes in the middle of a line can lead to any strange token
1158     // sequence.
1159     if (!CurrentToken->Tok.getIdentifierInfo())
1160       return Type;
1161     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
1162     case tok::pp_include:
1163     case tok::pp_include_next:
1164     case tok::pp_import:
1165       next();
1166       parseIncludeDirective();
1167       Type = LT_ImportStatement;
1168       break;
1169     case tok::pp_error:
1170     case tok::pp_warning:
1171       parseWarningOrError();
1172       break;
1173     case tok::pp_pragma:
1174       parsePragma();
1175       break;
1176     case tok::pp_if:
1177     case tok::pp_elif:
1178       Contexts.back().IsExpression = true;
1179       next();
1180       parseLine();
1181       break;
1182     default:
1183       break;
1184     }
1185     while (CurrentToken) {
1186       FormatToken *Tok = CurrentToken;
1187       next();
1188       if (Tok->is(tok::l_paren))
1189         parseParens();
1190       else if (Tok->isOneOf(Keywords.kw___has_include,
1191                             Keywords.kw___has_include_next))
1192         parseHasInclude();
1193     }
1194     return Type;
1195   }
1196 
1197 public:
1198   LineType parseLine() {
1199     if (!CurrentToken)
1200       return LT_Invalid;
1201     NonTemplateLess.clear();
1202     if (CurrentToken->is(tok::hash))
1203       return parsePreprocessorDirective();
1204 
1205     // Directly allow to 'import <string-literal>' to support protocol buffer
1206     // definitions (github.com/google/protobuf) or missing "#" (either way we
1207     // should not break the line).
1208     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
1209     if ((Style.Language == FormatStyle::LK_Java &&
1210          CurrentToken->is(Keywords.kw_package)) ||
1211         (Info && Info->getPPKeywordID() == tok::pp_import &&
1212          CurrentToken->Next &&
1213          CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
1214                                      tok::kw_static))) {
1215       next();
1216       parseIncludeDirective();
1217       return LT_ImportStatement;
1218     }
1219 
1220     // If this line starts and ends in '<' and '>', respectively, it is likely
1221     // part of "#define <a/b.h>".
1222     if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
1223       parseIncludeDirective();
1224       return LT_ImportStatement;
1225     }
1226 
1227     // In .proto files, top-level options and package statements are very
1228     // similar to import statements and should not be line-wrapped.
1229     if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
1230         CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
1231       next();
1232       if (CurrentToken && CurrentToken->is(tok::identifier)) {
1233         while (CurrentToken)
1234           next();
1235         return LT_ImportStatement;
1236       }
1237     }
1238 
1239     bool KeywordVirtualFound = false;
1240     bool ImportStatement = false;
1241 
1242     // import {...} from '...';
1243     if (Style.Language == FormatStyle::LK_JavaScript &&
1244         CurrentToken->is(Keywords.kw_import))
1245       ImportStatement = true;
1246 
1247     while (CurrentToken) {
1248       if (CurrentToken->is(tok::kw_virtual))
1249         KeywordVirtualFound = true;
1250       if (Style.Language == FormatStyle::LK_JavaScript) {
1251         // export {...} from '...';
1252         // An export followed by "from 'some string';" is a re-export from
1253         // another module identified by a URI and is treated as a
1254         // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
1255         // Just "export {...};" or "export class ..." should not be treated as
1256         // an import in this sense.
1257         if (Line.First->is(tok::kw_export) &&
1258             CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
1259             CurrentToken->Next->isStringLiteral())
1260           ImportStatement = true;
1261         if (isClosureImportStatement(*CurrentToken))
1262           ImportStatement = true;
1263       }
1264       if (!consumeToken())
1265         return LT_Invalid;
1266     }
1267     if (KeywordVirtualFound)
1268       return LT_VirtualFunctionDecl;
1269     if (ImportStatement)
1270       return LT_ImportStatement;
1271 
1272     if (Line.startsWith(TT_ObjCMethodSpecifier)) {
1273       if (Contexts.back().FirstObjCSelectorName)
1274         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
1275             Contexts.back().LongestObjCSelectorName;
1276       return LT_ObjCMethodDecl;
1277     }
1278 
1279     return LT_Other;
1280   }
1281 
1282 private:
1283   bool isClosureImportStatement(const FormatToken &Tok) {
1284     // FIXME: Closure-library specific stuff should not be hard-coded but be
1285     // configurable.
1286     return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
1287            Tok.Next->Next &&
1288            (Tok.Next->Next->TokenText == "module" ||
1289             Tok.Next->Next->TokenText == "provide" ||
1290             Tok.Next->Next->TokenText == "require" ||
1291             Tok.Next->Next->TokenText == "requireType" ||
1292             Tok.Next->Next->TokenText == "forwardDeclare") &&
1293            Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
1294   }
1295 
1296   void resetTokenMetadata(FormatToken *Token) {
1297     if (!Token)
1298       return;
1299 
1300     // Reset token type in case we have already looked at it and then
1301     // recovered from an error (e.g. failure to find the matching >).
1302     if (!CurrentToken->isOneOf(
1303             TT_LambdaLSquare, TT_LambdaLBrace, TT_ForEachMacro,
1304             TT_TypenameMacro, TT_FunctionLBrace, TT_ImplicitStringLiteral,
1305             TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow, TT_NamespaceMacro,
1306             TT_OverloadedOperator, TT_RegexLiteral, TT_TemplateString,
1307             TT_ObjCStringLiteral))
1308       CurrentToken->Type = TT_Unknown;
1309     CurrentToken->Role.reset();
1310     CurrentToken->MatchingParen = nullptr;
1311     CurrentToken->FakeLParens.clear();
1312     CurrentToken->FakeRParens = 0;
1313   }
1314 
1315   void next() {
1316     if (CurrentToken) {
1317       CurrentToken->NestingLevel = Contexts.size() - 1;
1318       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
1319       modifyContext(*CurrentToken);
1320       determineTokenType(*CurrentToken);
1321       CurrentToken = CurrentToken->Next;
1322     }
1323 
1324     resetTokenMetadata(CurrentToken);
1325   }
1326 
1327   /// A struct to hold information valid in a specific context, e.g.
1328   /// a pair of parenthesis.
1329   struct Context {
1330     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
1331             bool IsExpression)
1332         : ContextKind(ContextKind), BindingStrength(BindingStrength),
1333           IsExpression(IsExpression) {}
1334 
1335     tok::TokenKind ContextKind;
1336     unsigned BindingStrength;
1337     bool IsExpression;
1338     unsigned LongestObjCSelectorName = 0;
1339     bool ColonIsForRangeExpr = false;
1340     bool ColonIsDictLiteral = false;
1341     bool ColonIsObjCMethodExpr = false;
1342     FormatToken *FirstObjCSelectorName = nullptr;
1343     FormatToken *FirstStartOfName = nullptr;
1344     bool CanBeExpression = true;
1345     bool InTemplateArgument = false;
1346     bool InCtorInitializer = false;
1347     bool InInheritanceList = false;
1348     bool CaretFound = false;
1349     bool IsForEachMacro = false;
1350     bool InCpp11AttributeSpecifier = false;
1351     bool InCSharpAttributeSpecifier = false;
1352   };
1353 
1354   /// Puts a new \c Context onto the stack \c Contexts for the lifetime
1355   /// of each instance.
1356   struct ScopedContextCreator {
1357     AnnotatingParser &P;
1358 
1359     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1360                          unsigned Increase)
1361         : P(P) {
1362       P.Contexts.push_back(Context(ContextKind,
1363                                    P.Contexts.back().BindingStrength + Increase,
1364                                    P.Contexts.back().IsExpression));
1365     }
1366 
1367     ~ScopedContextCreator() { P.Contexts.pop_back(); }
1368   };
1369 
1370   void modifyContext(const FormatToken &Current) {
1371     if (Current.getPrecedence() == prec::Assignment &&
1372         !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1373         // Type aliases use `type X = ...;` in TypeScript and can be exported
1374         // using `export type ...`.
1375         !(Style.Language == FormatStyle::LK_JavaScript &&
1376           (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1377            Line.startsWith(tok::kw_export, Keywords.kw_type,
1378                            tok::identifier))) &&
1379         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1380       Contexts.back().IsExpression = true;
1381       if (!Line.startsWith(TT_UnaryOperator)) {
1382         for (FormatToken *Previous = Current.Previous;
1383              Previous && Previous->Previous &&
1384              !Previous->Previous->isOneOf(tok::comma, tok::semi);
1385              Previous = Previous->Previous) {
1386           if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1387             Previous = Previous->MatchingParen;
1388             if (!Previous)
1389               break;
1390           }
1391           if (Previous->opensScope())
1392             break;
1393           if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1394               Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1395               Previous->Previous && Previous->Previous->isNot(tok::equal))
1396             Previous->Type = TT_PointerOrReference;
1397         }
1398       }
1399     } else if (Current.is(tok::lessless) &&
1400                (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1401       Contexts.back().IsExpression = true;
1402     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1403       Contexts.back().IsExpression = true;
1404     } else if (Current.is(TT_TrailingReturnArrow)) {
1405       Contexts.back().IsExpression = false;
1406     } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1407       Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1408     } else if (Current.Previous &&
1409                Current.Previous->is(TT_CtorInitializerColon)) {
1410       Contexts.back().IsExpression = true;
1411       Contexts.back().InCtorInitializer = true;
1412     } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1413       Contexts.back().InInheritanceList = true;
1414     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1415       for (FormatToken *Previous = Current.Previous;
1416            Previous && Previous->isOneOf(tok::star, tok::amp);
1417            Previous = Previous->Previous)
1418         Previous->Type = TT_PointerOrReference;
1419       if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1420         Contexts.back().IsExpression = false;
1421     } else if (Current.is(tok::kw_new)) {
1422       Contexts.back().CanBeExpression = false;
1423     } else if (Current.is(tok::semi) ||
1424                (Current.is(tok::exclaim) && Current.Previous &&
1425                 !Current.Previous->is(tok::kw_operator))) {
1426       // This should be the condition or increment in a for-loop.
1427       // But not operator !() (can't use TT_OverloadedOperator here as its not
1428       // been annotated yet).
1429       Contexts.back().IsExpression = true;
1430     }
1431   }
1432 
1433   static FormatToken *untilMatchingParen(FormatToken *Current) {
1434     // Used when `MatchingParen` is not yet established.
1435     int ParenLevel = 0;
1436     while (Current) {
1437       if (Current->is(tok::l_paren))
1438         ParenLevel++;
1439       if (Current->is(tok::r_paren))
1440         ParenLevel--;
1441       if (ParenLevel < 1)
1442         break;
1443       Current = Current->Next;
1444     }
1445     return Current;
1446   }
1447 
1448   static bool isDeductionGuide(FormatToken &Current) {
1449     // Look for a deduction guide template<T> A(...) -> A<...>;
1450     if (Current.Previous && Current.Previous->is(tok::r_paren) &&
1451         Current.startsSequence(tok::arrow, tok::identifier, tok::less)) {
1452       // Find the TemplateCloser.
1453       FormatToken *TemplateCloser = Current.Next->Next;
1454       int NestingLevel = 0;
1455       while (TemplateCloser) {
1456         // Skip over an expressions in parens  A<(3 < 2)>;
1457         if (TemplateCloser->is(tok::l_paren)) {
1458           // No Matching Paren yet so skip to matching paren
1459           TemplateCloser = untilMatchingParen(TemplateCloser);
1460         }
1461         if (TemplateCloser->is(tok::less))
1462           NestingLevel++;
1463         if (TemplateCloser->is(tok::greater))
1464           NestingLevel--;
1465         if (NestingLevel < 1)
1466           break;
1467         TemplateCloser = TemplateCloser->Next;
1468       }
1469       // Assuming we have found the end of the template ensure its followed
1470       // with a semi-colon.
1471       if (TemplateCloser && TemplateCloser->Next &&
1472           TemplateCloser->Next->is(tok::semi) &&
1473           Current.Previous->MatchingParen) {
1474         // Determine if the identifier `A` prior to the A<..>; is the same as
1475         // prior to the A(..)
1476         FormatToken *LeadingIdentifier =
1477             Current.Previous->MatchingParen->Previous;
1478 
1479         // Differentiate a deduction guide by seeing the
1480         // > of the template prior to the leading identifier.
1481         if (LeadingIdentifier) {
1482           FormatToken *PriorLeadingIdentifier = LeadingIdentifier->Previous;
1483           // Skip back past explicit decoration
1484           if (PriorLeadingIdentifier &&
1485               PriorLeadingIdentifier->is(tok::kw_explicit))
1486             PriorLeadingIdentifier = PriorLeadingIdentifier->Previous;
1487 
1488           return (PriorLeadingIdentifier &&
1489                   PriorLeadingIdentifier->is(TT_TemplateCloser) &&
1490                   LeadingIdentifier->TokenText == Current.Next->TokenText);
1491         }
1492       }
1493     }
1494     return false;
1495   }
1496 
1497   void determineTokenType(FormatToken &Current) {
1498     if (!Current.is(TT_Unknown))
1499       // The token type is already known.
1500       return;
1501 
1502     if (Style.isCSharp() && CurrentToken->is(tok::question)) {
1503       if (CurrentToken->TokenText == "??") {
1504         Current.Type = TT_CSharpNullCoalescing;
1505         return;
1506       }
1507       if (CurrentToken->TokenText == "?.") {
1508         Current.Type = TT_CSharpNullConditional;
1509         return;
1510       }
1511       if (CurrentToken->TokenText == "?[") {
1512         Current.Type = TT_CSharpNullConditionalLSquare;
1513         return;
1514       }
1515     }
1516 
1517     if (Style.Language == FormatStyle::LK_JavaScript) {
1518       if (Current.is(tok::exclaim)) {
1519         if (Current.Previous &&
1520             (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1521                                        tok::r_paren, tok::r_square,
1522                                        tok::r_brace) ||
1523              Current.Previous->Tok.isLiteral())) {
1524           Current.Type = TT_JsNonNullAssertion;
1525           return;
1526         }
1527         if (Current.Next &&
1528             Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1529           Current.Type = TT_JsNonNullAssertion;
1530           return;
1531         }
1532       }
1533     }
1534 
1535     // Line.MightBeFunctionDecl can only be true after the parentheses of a
1536     // function declaration have been found. In this case, 'Current' is a
1537     // trailing token of this declaration and thus cannot be a name.
1538     if (Current.is(Keywords.kw_instanceof)) {
1539       Current.Type = TT_BinaryOperator;
1540     } else if (isStartOfName(Current) &&
1541                (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1542       Contexts.back().FirstStartOfName = &Current;
1543       Current.Type = TT_StartOfName;
1544     } else if (Current.is(tok::semi)) {
1545       // Reset FirstStartOfName after finding a semicolon so that a for loop
1546       // with multiple increment statements is not confused with a for loop
1547       // having multiple variable declarations.
1548       Contexts.back().FirstStartOfName = nullptr;
1549     } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1550       AutoFound = true;
1551     } else if (Current.is(tok::arrow) &&
1552                Style.Language == FormatStyle::LK_Java) {
1553       Current.Type = TT_LambdaArrow;
1554     } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1555                Current.NestingLevel == 0 &&
1556                !Current.Previous->is(tok::kw_operator)) {
1557       // not auto operator->() -> xxx;
1558       Current.Type = TT_TrailingReturnArrow;
1559 
1560     } else if (isDeductionGuide(Current)) {
1561       // Deduction guides trailing arrow " A(...) -> A<T>;".
1562       Current.Type = TT_TrailingReturnArrow;
1563     } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1564       Current.Type = determineStarAmpUsage(Current,
1565                                            Contexts.back().CanBeExpression &&
1566                                                Contexts.back().IsExpression,
1567                                            Contexts.back().InTemplateArgument);
1568     } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1569       Current.Type = determinePlusMinusCaretUsage(Current);
1570       if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1571         Contexts.back().CaretFound = true;
1572     } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1573       Current.Type = determineIncrementUsage(Current);
1574     } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1575       Current.Type = TT_UnaryOperator;
1576     } else if (Current.is(tok::question)) {
1577       if (Style.Language == FormatStyle::LK_JavaScript &&
1578           Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1579         // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1580         // on the interface, not a ternary expression.
1581         Current.Type = TT_JsTypeOptionalQuestion;
1582       } else {
1583         Current.Type = TT_ConditionalExpr;
1584       }
1585     } else if (Current.isBinaryOperator() &&
1586                (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
1587                (!Current.is(tok::greater) &&
1588                 Style.Language != FormatStyle::LK_TextProto)) {
1589       Current.Type = TT_BinaryOperator;
1590     } else if (Current.is(tok::comment)) {
1591       if (Current.TokenText.startswith("/*")) {
1592         if (Current.TokenText.endswith("*/"))
1593           Current.Type = TT_BlockComment;
1594         else
1595           // The lexer has for some reason determined a comment here. But we
1596           // cannot really handle it, if it isn't properly terminated.
1597           Current.Tok.setKind(tok::unknown);
1598       } else {
1599         Current.Type = TT_LineComment;
1600       }
1601     } else if (Current.is(tok::r_paren)) {
1602       if (rParenEndsCast(Current))
1603         Current.Type = TT_CastRParen;
1604       if (Current.MatchingParen && Current.Next &&
1605           !Current.Next->isBinaryOperator() &&
1606           !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1607                                  tok::comma, tok::period, tok::arrow,
1608                                  tok::coloncolon))
1609         if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1610           // Make sure this isn't the return type of an Obj-C block declaration
1611           if (AfterParen->Tok.isNot(tok::caret)) {
1612             if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1613               if (BeforeParen->is(tok::identifier) &&
1614                   !BeforeParen->is(TT_TypenameMacro) &&
1615                   BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1616                   (!BeforeParen->Previous ||
1617                    BeforeParen->Previous->ClosesTemplateDeclaration))
1618                 Current.Type = TT_FunctionAnnotationRParen;
1619           }
1620         }
1621     } else if (Current.is(tok::at) && Current.Next &&
1622                Style.Language != FormatStyle::LK_JavaScript &&
1623                Style.Language != FormatStyle::LK_Java) {
1624       // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1625       // marks declarations and properties that need special formatting.
1626       switch (Current.Next->Tok.getObjCKeywordID()) {
1627       case tok::objc_interface:
1628       case tok::objc_implementation:
1629       case tok::objc_protocol:
1630         Current.Type = TT_ObjCDecl;
1631         break;
1632       case tok::objc_property:
1633         Current.Type = TT_ObjCProperty;
1634         break;
1635       default:
1636         break;
1637       }
1638     } else if (Current.is(tok::period)) {
1639       FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1640       if (PreviousNoComment &&
1641           PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1642         Current.Type = TT_DesignatedInitializerPeriod;
1643       else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1644                Current.Previous->isOneOf(TT_JavaAnnotation,
1645                                          TT_LeadingJavaAnnotation)) {
1646         Current.Type = Current.Previous->Type;
1647       }
1648     } else if (canBeObjCSelectorComponent(Current) &&
1649                // FIXME(bug 36976): ObjC return types shouldn't use
1650                // TT_CastRParen.
1651                Current.Previous && Current.Previous->is(TT_CastRParen) &&
1652                Current.Previous->MatchingParen &&
1653                Current.Previous->MatchingParen->Previous &&
1654                Current.Previous->MatchingParen->Previous->is(
1655                    TT_ObjCMethodSpecifier)) {
1656       // This is the first part of an Objective-C selector name. (If there's no
1657       // colon after this, this is the only place which annotates the identifier
1658       // as a selector.)
1659       Current.Type = TT_SelectorName;
1660     } else if (Current.isOneOf(tok::identifier, tok::kw_const,
1661                                tok::kw_noexcept) &&
1662                Current.Previous &&
1663                !Current.Previous->isOneOf(tok::equal, tok::at) &&
1664                Line.MightBeFunctionDecl && Contexts.size() == 1) {
1665       // Line.MightBeFunctionDecl can only be true after the parentheses of a
1666       // function declaration have been found.
1667       Current.Type = TT_TrailingAnnotation;
1668     } else if ((Style.Language == FormatStyle::LK_Java ||
1669                 Style.Language == FormatStyle::LK_JavaScript) &&
1670                Current.Previous) {
1671       if (Current.Previous->is(tok::at) &&
1672           Current.isNot(Keywords.kw_interface)) {
1673         const FormatToken &AtToken = *Current.Previous;
1674         const FormatToken *Previous = AtToken.getPreviousNonComment();
1675         if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1676           Current.Type = TT_LeadingJavaAnnotation;
1677         else
1678           Current.Type = TT_JavaAnnotation;
1679       } else if (Current.Previous->is(tok::period) &&
1680                  Current.Previous->isOneOf(TT_JavaAnnotation,
1681                                            TT_LeadingJavaAnnotation)) {
1682         Current.Type = Current.Previous->Type;
1683       }
1684     }
1685   }
1686 
1687   /// Take a guess at whether \p Tok starts a name of a function or
1688   /// variable declaration.
1689   ///
1690   /// This is a heuristic based on whether \p Tok is an identifier following
1691   /// something that is likely a type.
1692   bool isStartOfName(const FormatToken &Tok) {
1693     if (Tok.isNot(tok::identifier) || !Tok.Previous)
1694       return false;
1695 
1696     if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1697                               Keywords.kw_as))
1698       return false;
1699     if (Style.Language == FormatStyle::LK_JavaScript &&
1700         Tok.Previous->is(Keywords.kw_in))
1701       return false;
1702 
1703     // Skip "const" as it does not have an influence on whether this is a name.
1704     FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1705     while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1706       PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1707 
1708     if (!PreviousNotConst)
1709       return false;
1710 
1711     bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1712                        PreviousNotConst->Previous &&
1713                        PreviousNotConst->Previous->is(tok::hash);
1714 
1715     if (PreviousNotConst->is(TT_TemplateCloser))
1716       return PreviousNotConst && PreviousNotConst->MatchingParen &&
1717              PreviousNotConst->MatchingParen->Previous &&
1718              PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1719              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1720 
1721     if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1722         PreviousNotConst->MatchingParen->Previous &&
1723         PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1724       return true;
1725 
1726     return (!IsPPKeyword &&
1727             PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1728            PreviousNotConst->is(TT_PointerOrReference) ||
1729            PreviousNotConst->isSimpleTypeSpecifier();
1730   }
1731 
1732   /// Determine whether ')' is ending a cast.
1733   bool rParenEndsCast(const FormatToken &Tok) {
1734     // C-style casts are only used in C++, C# and Java.
1735     if (!Style.isCSharp() && !Style.isCpp() &&
1736         Style.Language != FormatStyle::LK_Java)
1737       return false;
1738 
1739     // Empty parens aren't casts and there are no casts at the end of the line.
1740     if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1741       return false;
1742 
1743     FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1744     if (LeftOfParens) {
1745       // If there is a closing parenthesis left of the current parentheses,
1746       // look past it as these might be chained casts.
1747       if (LeftOfParens->is(tok::r_paren)) {
1748         if (!LeftOfParens->MatchingParen ||
1749             !LeftOfParens->MatchingParen->Previous)
1750           return false;
1751         LeftOfParens = LeftOfParens->MatchingParen->Previous;
1752       }
1753 
1754       // If there is an identifier (or with a few exceptions a keyword) right
1755       // before the parentheses, this is unlikely to be a cast.
1756       if (LeftOfParens->Tok.getIdentifierInfo() &&
1757           !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1758                                  tok::kw_delete))
1759         return false;
1760 
1761       // Certain other tokens right before the parentheses are also signals that
1762       // this cannot be a cast.
1763       if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1764                                 TT_TemplateCloser, tok::ellipsis))
1765         return false;
1766     }
1767 
1768     if (Tok.Next->is(tok::question))
1769       return false;
1770 
1771     // Functions which end with decorations like volatile, noexcept are unlikely
1772     // to be casts.
1773     if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
1774                           tok::kw_throw, tok::arrow, Keywords.kw_override,
1775                           Keywords.kw_final) ||
1776         isCpp11AttributeSpecifier(*Tok.Next))
1777       return false;
1778 
1779     // As Java has no function types, a "(" after the ")" likely means that this
1780     // is a cast.
1781     if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1782       return true;
1783 
1784     // If a (non-string) literal follows, this is likely a cast.
1785     if (Tok.Next->isNot(tok::string_literal) &&
1786         (Tok.Next->Tok.isLiteral() ||
1787          Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1788       return true;
1789 
1790     // Heuristically try to determine whether the parentheses contain a type.
1791     bool ParensAreType =
1792         !Tok.Previous ||
1793         Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1794         Tok.Previous->isSimpleTypeSpecifier();
1795     bool ParensCouldEndDecl =
1796         Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1797     if (ParensAreType && !ParensCouldEndDecl)
1798       return true;
1799 
1800     // At this point, we heuristically assume that there are no casts at the
1801     // start of the line. We assume that we have found most cases where there
1802     // are by the logic above, e.g. "(void)x;".
1803     if (!LeftOfParens)
1804       return false;
1805 
1806     // Certain token types inside the parentheses mean that this can't be a
1807     // cast.
1808     for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1809          Token = Token->Next)
1810       if (Token->is(TT_BinaryOperator))
1811         return false;
1812 
1813     // If the following token is an identifier or 'this', this is a cast. All
1814     // cases where this can be something else are handled above.
1815     if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1816       return true;
1817 
1818     if (!Tok.Next->Next)
1819       return false;
1820 
1821     // If the next token after the parenthesis is a unary operator, assume
1822     // that this is cast, unless there are unexpected tokens inside the
1823     // parenthesis.
1824     bool NextIsUnary =
1825         Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1826     if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1827         !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1828       return false;
1829     // Search for unexpected tokens.
1830     for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1831          Prev = Prev->Previous) {
1832       if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1833         return false;
1834     }
1835     return true;
1836   }
1837 
1838   /// Return the type of the given token assuming it is * or &.
1839   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1840                                   bool InTemplateArgument) {
1841     if (Style.Language == FormatStyle::LK_JavaScript)
1842       return TT_BinaryOperator;
1843 
1844     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1845     if (!PrevToken)
1846       return TT_UnaryOperator;
1847 
1848     const FormatToken *NextToken = Tok.getNextNonComment();
1849     if (!NextToken ||
1850         NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const,
1851                            tok::kw_noexcept) ||
1852         (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1853       return TT_PointerOrReference;
1854 
1855     if (PrevToken->is(tok::coloncolon))
1856       return TT_PointerOrReference;
1857 
1858     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1859                            tok::comma, tok::semi, tok::kw_return, tok::colon,
1860                            tok::equal, tok::kw_delete, tok::kw_sizeof,
1861                            tok::kw_throw) ||
1862         PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1863                            TT_UnaryOperator, TT_CastRParen))
1864       return TT_UnaryOperator;
1865 
1866     if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1867       return TT_PointerOrReference;
1868     if (NextToken->is(tok::kw_operator) && !IsExpression)
1869       return TT_PointerOrReference;
1870     if (NextToken->isOneOf(tok::comma, tok::semi))
1871       return TT_PointerOrReference;
1872 
1873     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1874       FormatToken *TokenBeforeMatchingParen =
1875           PrevToken->MatchingParen->getPreviousNonComment();
1876       if (TokenBeforeMatchingParen &&
1877           TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype,
1878                                             TT_TypenameMacro))
1879         return TT_PointerOrReference;
1880     }
1881 
1882     if (PrevToken->Tok.isLiteral() ||
1883         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1884                            tok::kw_false, tok::r_brace) ||
1885         NextToken->Tok.isLiteral() ||
1886         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1887         NextToken->isUnaryOperator() ||
1888         // If we know we're in a template argument, there are no named
1889         // declarations. Thus, having an identifier on the right-hand side
1890         // indicates a binary operator.
1891         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1892       return TT_BinaryOperator;
1893 
1894     // "&&(" is quite unlikely to be two successive unary "&".
1895     if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren))
1896       return TT_BinaryOperator;
1897 
1898     // This catches some cases where evaluation order is used as control flow:
1899     //   aaa && aaa->f();
1900     if (NextToken->Tok.isAnyIdentifier()) {
1901       const FormatToken *NextNextToken = NextToken->getNextNonComment();
1902       if (NextNextToken && NextNextToken->is(tok::arrow))
1903         return TT_BinaryOperator;
1904     }
1905 
1906     // It is very unlikely that we are going to find a pointer or reference type
1907     // definition on the RHS of an assignment.
1908     if (IsExpression && !Contexts.back().CaretFound)
1909       return TT_BinaryOperator;
1910 
1911     return TT_PointerOrReference;
1912   }
1913 
1914   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1915     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1916     if (!PrevToken)
1917       return TT_UnaryOperator;
1918 
1919     if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
1920       // This must be a sequence of leading unary operators.
1921       return TT_UnaryOperator;
1922 
1923     // Use heuristics to recognize unary operators.
1924     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1925                            tok::question, tok::colon, tok::kw_return,
1926                            tok::kw_case, tok::at, tok::l_brace, tok::kw_throw,
1927                            tok::kw_co_return, tok::kw_co_yield))
1928       return TT_UnaryOperator;
1929 
1930     // There can't be two consecutive binary operators.
1931     if (PrevToken->is(TT_BinaryOperator))
1932       return TT_UnaryOperator;
1933 
1934     // Fall back to marking the token as binary operator.
1935     return TT_BinaryOperator;
1936   }
1937 
1938   /// Determine whether ++/-- are pre- or post-increments/-decrements.
1939   TokenType determineIncrementUsage(const FormatToken &Tok) {
1940     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1941     if (!PrevToken || PrevToken->is(TT_CastRParen))
1942       return TT_UnaryOperator;
1943     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1944       return TT_TrailingUnaryOperator;
1945 
1946     return TT_UnaryOperator;
1947   }
1948 
1949   SmallVector<Context, 8> Contexts;
1950 
1951   const FormatStyle &Style;
1952   AnnotatedLine &Line;
1953   FormatToken *CurrentToken;
1954   bool AutoFound;
1955   const AdditionalKeywords &Keywords;
1956 
1957   // Set of "<" tokens that do not open a template parameter list. If parseAngle
1958   // determines that a specific token can't be a template opener, it will make
1959   // same decision irrespective of the decisions for tokens leading up to it.
1960   // Store this information to prevent this from causing exponential runtime.
1961   llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1962 };
1963 
1964 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1965 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1966 
1967 /// Parses binary expressions by inserting fake parenthesis based on
1968 /// operator precedence.
1969 class ExpressionParser {
1970 public:
1971   ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1972                    AnnotatedLine &Line)
1973       : Style(Style), Keywords(Keywords), Current(Line.First) {}
1974 
1975   /// Parse expressions with the given operator precedence.
1976   void parse(int Precedence = 0) {
1977     // Skip 'return' and ObjC selector colons as they are not part of a binary
1978     // expression.
1979     while (Current && (Current->is(tok::kw_return) ||
1980                        (Current->is(tok::colon) &&
1981                         Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1982       next();
1983 
1984     if (!Current || Precedence > PrecedenceArrowAndPeriod)
1985       return;
1986 
1987     // Conditional expressions need to be parsed separately for proper nesting.
1988     if (Precedence == prec::Conditional) {
1989       parseConditionalExpr();
1990       return;
1991     }
1992 
1993     // Parse unary operators, which all have a higher precedence than binary
1994     // operators.
1995     if (Precedence == PrecedenceUnaryOperator) {
1996       parseUnaryOperator();
1997       return;
1998     }
1999 
2000     FormatToken *Start = Current;
2001     FormatToken *LatestOperator = nullptr;
2002     unsigned OperatorIndex = 0;
2003 
2004     while (Current) {
2005       // Consume operators with higher precedence.
2006       parse(Precedence + 1);
2007 
2008       int CurrentPrecedence = getCurrentPrecedence();
2009 
2010       if (Current && Current->is(TT_SelectorName) &&
2011           Precedence == CurrentPrecedence) {
2012         if (LatestOperator)
2013           addFakeParenthesis(Start, prec::Level(Precedence));
2014         Start = Current;
2015       }
2016 
2017       // At the end of the line or when an operator with higher precedence is
2018       // found, insert fake parenthesis and return.
2019       if (!Current ||
2020           (Current->closesScope() &&
2021            (Current->MatchingParen || Current->is(TT_TemplateString))) ||
2022           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
2023           (CurrentPrecedence == prec::Conditional &&
2024            Precedence == prec::Assignment && Current->is(tok::colon))) {
2025         break;
2026       }
2027 
2028       // Consume scopes: (), [], <> and {}
2029       if (Current->opensScope()) {
2030         // In fragment of a JavaScript template string can look like '}..${' and
2031         // thus close a scope and open a new one at the same time.
2032         while (Current && (!Current->closesScope() || Current->opensScope())) {
2033           next();
2034           parse();
2035         }
2036         next();
2037       } else {
2038         // Operator found.
2039         if (CurrentPrecedence == Precedence) {
2040           if (LatestOperator)
2041             LatestOperator->NextOperator = Current;
2042           LatestOperator = Current;
2043           Current->OperatorIndex = OperatorIndex;
2044           ++OperatorIndex;
2045         }
2046         next(/*SkipPastLeadingComments=*/Precedence > 0);
2047       }
2048     }
2049 
2050     if (LatestOperator && (Current || Precedence > 0)) {
2051       // LatestOperator->LastOperator = true;
2052       if (Precedence == PrecedenceArrowAndPeriod) {
2053         // Call expressions don't have a binary operator precedence.
2054         addFakeParenthesis(Start, prec::Unknown);
2055       } else {
2056         addFakeParenthesis(Start, prec::Level(Precedence));
2057       }
2058     }
2059   }
2060 
2061 private:
2062   /// Gets the precedence (+1) of the given token for binary operators
2063   /// and other tokens that we treat like binary operators.
2064   int getCurrentPrecedence() {
2065     if (Current) {
2066       const FormatToken *NextNonComment = Current->getNextNonComment();
2067       if (Current->is(TT_ConditionalExpr))
2068         return prec::Conditional;
2069       if (NextNonComment && Current->is(TT_SelectorName) &&
2070           (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
2071            ((Style.Language == FormatStyle::LK_Proto ||
2072              Style.Language == FormatStyle::LK_TextProto) &&
2073             NextNonComment->is(tok::less))))
2074         return prec::Assignment;
2075       if (Current->is(TT_JsComputedPropertyName))
2076         return prec::Assignment;
2077       if (Current->is(TT_LambdaArrow))
2078         return prec::Comma;
2079       if (Current->is(TT_JsFatArrow))
2080         return prec::Assignment;
2081       if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
2082           (Current->is(tok::comment) && NextNonComment &&
2083            NextNonComment->is(TT_SelectorName)))
2084         return 0;
2085       if (Current->is(TT_RangeBasedForLoopColon))
2086         return prec::Comma;
2087       if ((Style.Language == FormatStyle::LK_Java ||
2088            Style.Language == FormatStyle::LK_JavaScript) &&
2089           Current->is(Keywords.kw_instanceof))
2090         return prec::Relational;
2091       if (Style.Language == FormatStyle::LK_JavaScript &&
2092           Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
2093         return prec::Relational;
2094       if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
2095         return Current->getPrecedence();
2096       if (Current->isOneOf(tok::period, tok::arrow))
2097         return PrecedenceArrowAndPeriod;
2098       if ((Style.Language == FormatStyle::LK_Java ||
2099            Style.Language == FormatStyle::LK_JavaScript) &&
2100           Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
2101                            Keywords.kw_throws))
2102         return 0;
2103     }
2104     return -1;
2105   }
2106 
2107   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
2108     Start->FakeLParens.push_back(Precedence);
2109     if (Precedence > prec::Unknown)
2110       Start->StartsBinaryExpression = true;
2111     if (Current) {
2112       FormatToken *Previous = Current->Previous;
2113       while (Previous->is(tok::comment) && Previous->Previous)
2114         Previous = Previous->Previous;
2115       ++Previous->FakeRParens;
2116       if (Precedence > prec::Unknown)
2117         Previous->EndsBinaryExpression = true;
2118     }
2119   }
2120 
2121   /// Parse unary operator expressions and surround them with fake
2122   /// parentheses if appropriate.
2123   void parseUnaryOperator() {
2124     llvm::SmallVector<FormatToken *, 2> Tokens;
2125     while (Current && Current->is(TT_UnaryOperator)) {
2126       Tokens.push_back(Current);
2127       next();
2128     }
2129     parse(PrecedenceArrowAndPeriod);
2130     for (FormatToken *Token : llvm::reverse(Tokens))
2131       // The actual precedence doesn't matter.
2132       addFakeParenthesis(Token, prec::Unknown);
2133   }
2134 
2135   void parseConditionalExpr() {
2136     while (Current && Current->isTrailingComment()) {
2137       next();
2138     }
2139     FormatToken *Start = Current;
2140     parse(prec::LogicalOr);
2141     if (!Current || !Current->is(tok::question))
2142       return;
2143     next();
2144     parse(prec::Assignment);
2145     if (!Current || Current->isNot(TT_ConditionalExpr))
2146       return;
2147     next();
2148     parse(prec::Assignment);
2149     addFakeParenthesis(Start, prec::Conditional);
2150   }
2151 
2152   void next(bool SkipPastLeadingComments = true) {
2153     if (Current)
2154       Current = Current->Next;
2155     while (Current &&
2156            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
2157            Current->isTrailingComment())
2158       Current = Current->Next;
2159   }
2160 
2161   const FormatStyle &Style;
2162   const AdditionalKeywords &Keywords;
2163   FormatToken *Current;
2164 };
2165 
2166 } // end anonymous namespace
2167 
2168 void TokenAnnotator::setCommentLineLevels(
2169     SmallVectorImpl<AnnotatedLine *> &Lines) {
2170   const AnnotatedLine *NextNonCommentLine = nullptr;
2171   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
2172                                                           E = Lines.rend();
2173        I != E; ++I) {
2174     bool CommentLine = true;
2175     for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
2176       if (!Tok->is(tok::comment)) {
2177         CommentLine = false;
2178         break;
2179       }
2180     }
2181 
2182     // If the comment is currently aligned with the line immediately following
2183     // it, that's probably intentional and we should keep it.
2184     if (NextNonCommentLine && CommentLine &&
2185         NextNonCommentLine->First->NewlinesBefore <= 1 &&
2186         NextNonCommentLine->First->OriginalColumn ==
2187             (*I)->First->OriginalColumn) {
2188       // Align comments for preprocessor lines with the # in column 0 if
2189       // preprocessor lines are not indented. Otherwise, align with the next
2190       // line.
2191       (*I)->Level =
2192           (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
2193            (NextNonCommentLine->Type == LT_PreprocessorDirective ||
2194             NextNonCommentLine->Type == LT_ImportStatement))
2195               ? 0
2196               : NextNonCommentLine->Level;
2197     } else {
2198       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
2199     }
2200 
2201     setCommentLineLevels((*I)->Children);
2202   }
2203 }
2204 
2205 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
2206   unsigned Result = 0;
2207   for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
2208     Result = std::max(Result, Tok->NestingLevel);
2209   return Result;
2210 }
2211 
2212 void TokenAnnotator::annotate(AnnotatedLine &Line) {
2213   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2214                                                   E = Line.Children.end();
2215        I != E; ++I) {
2216     annotate(**I);
2217   }
2218   AnnotatingParser Parser(Style, Line, Keywords);
2219   Line.Type = Parser.parseLine();
2220 
2221   // With very deep nesting, ExpressionParser uses lots of stack and the
2222   // formatting algorithm is very slow. We're not going to do a good job here
2223   // anyway - it's probably generated code being formatted by mistake.
2224   // Just skip the whole line.
2225   if (maxNestingDepth(Line) > 50)
2226     Line.Type = LT_Invalid;
2227 
2228   if (Line.Type == LT_Invalid)
2229     return;
2230 
2231   ExpressionParser ExprParser(Style, Keywords, Line);
2232   ExprParser.parse();
2233 
2234   if (Line.startsWith(TT_ObjCMethodSpecifier))
2235     Line.Type = LT_ObjCMethodDecl;
2236   else if (Line.startsWith(TT_ObjCDecl))
2237     Line.Type = LT_ObjCDecl;
2238   else if (Line.startsWith(TT_ObjCProperty))
2239     Line.Type = LT_ObjCProperty;
2240 
2241   Line.First->SpacesRequiredBefore = 1;
2242   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
2243 }
2244 
2245 // This function heuristically determines whether 'Current' starts the name of a
2246 // function declaration.
2247 static bool isFunctionDeclarationName(const FormatToken &Current,
2248                                       const AnnotatedLine &Line) {
2249   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
2250     for (; Next; Next = Next->Next) {
2251       if (Next->is(TT_OverloadedOperatorLParen))
2252         return Next;
2253       if (Next->is(TT_OverloadedOperator))
2254         continue;
2255       if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
2256         // For 'new[]' and 'delete[]'.
2257         if (Next->Next &&
2258             Next->Next->startsSequence(tok::l_square, tok::r_square))
2259           Next = Next->Next->Next;
2260         continue;
2261       }
2262       if (Next->startsSequence(tok::l_square, tok::r_square)) {
2263         // For operator[]().
2264         Next = Next->Next;
2265         continue;
2266       }
2267       if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) &&
2268           Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) {
2269         // For operator void*(), operator char*(), operator Foo*().
2270         Next = Next->Next;
2271         continue;
2272       }
2273 
2274       break;
2275     }
2276     return nullptr;
2277   };
2278 
2279   // Find parentheses of parameter list.
2280   const FormatToken *Next = Current.Next;
2281   if (Current.is(tok::kw_operator)) {
2282     if (Current.Previous && Current.Previous->is(tok::coloncolon))
2283       return false;
2284     Next = skipOperatorName(Next);
2285   } else {
2286     if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
2287       return false;
2288     for (; Next; Next = Next->Next) {
2289       if (Next->is(TT_TemplateOpener)) {
2290         Next = Next->MatchingParen;
2291       } else if (Next->is(tok::coloncolon)) {
2292         Next = Next->Next;
2293         if (!Next)
2294           return false;
2295         if (Next->is(tok::kw_operator)) {
2296           Next = skipOperatorName(Next->Next);
2297           break;
2298         }
2299         if (!Next->is(tok::identifier))
2300           return false;
2301       } else if (Next->is(tok::l_paren)) {
2302         break;
2303       } else {
2304         return false;
2305       }
2306     }
2307   }
2308 
2309   // Check whether parameter list can belong to a function declaration.
2310   if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
2311     return false;
2312   // If the lines ends with "{", this is likely an function definition.
2313   if (Line.Last->is(tok::l_brace))
2314     return true;
2315   if (Next->Next == Next->MatchingParen)
2316     return true; // Empty parentheses.
2317   // If there is an &/&& after the r_paren, this is likely a function.
2318   if (Next->MatchingParen->Next &&
2319       Next->MatchingParen->Next->is(TT_PointerOrReference))
2320     return true;
2321   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
2322        Tok = Tok->Next) {
2323     if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
2324       Tok = Tok->MatchingParen;
2325       continue;
2326     }
2327     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
2328         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
2329       return true;
2330     if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
2331         Tok->Tok.isLiteral())
2332       return false;
2333   }
2334   return false;
2335 }
2336 
2337 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
2338   assert(Line.MightBeFunctionDecl);
2339 
2340   if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
2341        Style.AlwaysBreakAfterReturnType ==
2342            FormatStyle::RTBS_TopLevelDefinitions) &&
2343       Line.Level > 0)
2344     return false;
2345 
2346   switch (Style.AlwaysBreakAfterReturnType) {
2347   case FormatStyle::RTBS_None:
2348     return false;
2349   case FormatStyle::RTBS_All:
2350   case FormatStyle::RTBS_TopLevel:
2351     return true;
2352   case FormatStyle::RTBS_AllDefinitions:
2353   case FormatStyle::RTBS_TopLevelDefinitions:
2354     return Line.mightBeFunctionDefinition();
2355   }
2356 
2357   return false;
2358 }
2359 
2360 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2361   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2362                                                   E = Line.Children.end();
2363        I != E; ++I) {
2364     calculateFormattingInformation(**I);
2365   }
2366 
2367   Line.First->TotalLength =
2368       Line.First->IsMultiline ? Style.ColumnLimit
2369                               : Line.FirstStartColumn + Line.First->ColumnWidth;
2370   FormatToken *Current = Line.First->Next;
2371   bool InFunctionDecl = Line.MightBeFunctionDecl;
2372   while (Current) {
2373     if (isFunctionDeclarationName(*Current, Line))
2374       Current->Type = TT_FunctionDeclarationName;
2375     if (Current->is(TT_LineComment)) {
2376       if (Current->Previous->BlockKind == BK_BracedInit &&
2377           Current->Previous->opensScope())
2378         Current->SpacesRequiredBefore =
2379             (Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1;
2380       else
2381         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2382 
2383       // If we find a trailing comment, iterate backwards to determine whether
2384       // it seems to relate to a specific parameter. If so, break before that
2385       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2386       // to the previous line in:
2387       //   SomeFunction(a,
2388       //                b, // comment
2389       //                c);
2390       if (!Current->HasUnescapedNewline) {
2391         for (FormatToken *Parameter = Current->Previous; Parameter;
2392              Parameter = Parameter->Previous) {
2393           if (Parameter->isOneOf(tok::comment, tok::r_brace))
2394             break;
2395           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2396             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2397                 Parameter->HasUnescapedNewline)
2398               Parameter->MustBreakBefore = true;
2399             break;
2400           }
2401         }
2402       }
2403     } else if (Current->SpacesRequiredBefore == 0 &&
2404                spaceRequiredBefore(Line, *Current)) {
2405       Current->SpacesRequiredBefore = 1;
2406     }
2407 
2408     Current->MustBreakBefore =
2409         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2410 
2411     if (!Current->MustBreakBefore && InFunctionDecl &&
2412         Current->is(TT_FunctionDeclarationName))
2413       Current->MustBreakBefore = mustBreakForReturnType(Line);
2414 
2415     Current->CanBreakBefore =
2416         Current->MustBreakBefore || canBreakBefore(Line, *Current);
2417     unsigned ChildSize = 0;
2418     if (Current->Previous->Children.size() == 1) {
2419       FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
2420       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2421                                                   : LastOfChild.TotalLength + 1;
2422     }
2423     const FormatToken *Prev = Current->Previous;
2424     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2425         (Prev->Children.size() == 1 &&
2426          Prev->Children[0]->First->MustBreakBefore) ||
2427         Current->IsMultiline)
2428       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2429     else
2430       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2431                              ChildSize + Current->SpacesRequiredBefore;
2432 
2433     if (Current->is(TT_CtorInitializerColon))
2434       InFunctionDecl = false;
2435 
2436     // FIXME: Only calculate this if CanBreakBefore is true once static
2437     // initializers etc. are sorted out.
2438     // FIXME: Move magic numbers to a better place.
2439 
2440     // Reduce penalty for aligning ObjC method arguments using the colon
2441     // alignment as this is the canonical way (still prefer fitting everything
2442     // into one line if possible). Trying to fit a whole expression into one
2443     // line should not force other line breaks (e.g. when ObjC method
2444     // expression is a part of other expression).
2445     Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
2446     if (Style.Language == FormatStyle::LK_ObjC &&
2447         Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
2448       if (Current->ParameterIndex == 1)
2449         Current->SplitPenalty += 5 * Current->BindingStrength;
2450     } else {
2451       Current->SplitPenalty += 20 * Current->BindingStrength;
2452     }
2453 
2454     Current = Current->Next;
2455   }
2456 
2457   calculateUnbreakableTailLengths(Line);
2458   unsigned IndentLevel = Line.Level;
2459   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2460     if (Current->Role)
2461       Current->Role->precomputeFormattingInfos(Current);
2462     if (Current->MatchingParen &&
2463         Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
2464       assert(IndentLevel > 0);
2465       --IndentLevel;
2466     }
2467     Current->IndentLevel = IndentLevel;
2468     if (Current->opensBlockOrBlockTypeList(Style))
2469       ++IndentLevel;
2470   }
2471 
2472   LLVM_DEBUG({ printDebugInfo(Line); });
2473 }
2474 
2475 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2476   unsigned UnbreakableTailLength = 0;
2477   FormatToken *Current = Line.Last;
2478   while (Current) {
2479     Current->UnbreakableTailLength = UnbreakableTailLength;
2480     if (Current->CanBreakBefore ||
2481         Current->isOneOf(tok::comment, tok::string_literal)) {
2482       UnbreakableTailLength = 0;
2483     } else {
2484       UnbreakableTailLength +=
2485           Current->ColumnWidth + Current->SpacesRequiredBefore;
2486     }
2487     Current = Current->Previous;
2488   }
2489 }
2490 
2491 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2492                                       const FormatToken &Tok,
2493                                       bool InFunctionDecl) {
2494   const FormatToken &Left = *Tok.Previous;
2495   const FormatToken &Right = Tok;
2496 
2497   if (Left.is(tok::semi))
2498     return 0;
2499 
2500   if (Style.Language == FormatStyle::LK_Java) {
2501     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2502       return 1;
2503     if (Right.is(Keywords.kw_implements))
2504       return 2;
2505     if (Left.is(tok::comma) && Left.NestingLevel == 0)
2506       return 3;
2507   } else if (Style.Language == FormatStyle::LK_JavaScript) {
2508     if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2509       return 100;
2510     if (Left.is(TT_JsTypeColon))
2511       return 35;
2512     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2513         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2514       return 100;
2515     // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2516     if (Left.opensScope() && Right.closesScope())
2517       return 200;
2518   }
2519 
2520   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2521     return 1;
2522   if (Right.is(tok::l_square)) {
2523     if (Style.Language == FormatStyle::LK_Proto)
2524       return 1;
2525     if (Left.is(tok::r_square))
2526       return 200;
2527     // Slightly prefer formatting local lambda definitions like functions.
2528     if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2529       return 35;
2530     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2531                        TT_ArrayInitializerLSquare,
2532                        TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2533       return 500;
2534   }
2535 
2536   if (Left.is(tok::coloncolon) ||
2537       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2538     return 500;
2539   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2540       Right.is(tok::kw_operator)) {
2541     if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2542       return 3;
2543     if (Left.is(TT_StartOfName))
2544       return 110;
2545     if (InFunctionDecl && Right.NestingLevel == 0)
2546       return Style.PenaltyReturnTypeOnItsOwnLine;
2547     return 200;
2548   }
2549   if (Right.is(TT_PointerOrReference))
2550     return 190;
2551   if (Right.is(TT_LambdaArrow))
2552     return 110;
2553   if (Left.is(tok::equal) && Right.is(tok::l_brace))
2554     return 160;
2555   if (Left.is(TT_CastRParen))
2556     return 100;
2557   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2558     return 5000;
2559   if (Left.is(tok::comment))
2560     return 1000;
2561 
2562   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2563                    TT_CtorInitializerColon))
2564     return 2;
2565 
2566   if (Right.isMemberAccess()) {
2567     // Breaking before the "./->" of a chained call/member access is reasonably
2568     // cheap, as formatting those with one call per line is generally
2569     // desirable. In particular, it should be cheaper to break before the call
2570     // than it is to break inside a call's parameters, which could lead to weird
2571     // "hanging" indents. The exception is the very last "./->" to support this
2572     // frequent pattern:
2573     //
2574     //   aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2575     //       dddddddd);
2576     //
2577     // which might otherwise be blown up onto many lines. Here, clang-format
2578     // won't produce "hanging" indents anyway as there is no other trailing
2579     // call.
2580     //
2581     // Also apply higher penalty is not a call as that might lead to a wrapping
2582     // like:
2583     //
2584     //   aaaaaaa
2585     //       .aaaaaaaaa.bbbbbbbb(cccccccc);
2586     return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2587                ? 150
2588                : 35;
2589   }
2590 
2591   if (Right.is(TT_TrailingAnnotation) &&
2592       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2593     // Moving trailing annotations to the next line is fine for ObjC method
2594     // declarations.
2595     if (Line.startsWith(TT_ObjCMethodSpecifier))
2596       return 10;
2597     // Generally, breaking before a trailing annotation is bad unless it is
2598     // function-like. It seems to be especially preferable to keep standard
2599     // annotations (i.e. "const", "final" and "override") on the same line.
2600     // Use a slightly higher penalty after ")" so that annotations like
2601     // "const override" are kept together.
2602     bool is_short_annotation = Right.TokenText.size() < 10;
2603     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2604   }
2605 
2606   // In for-loops, prefer breaking at ',' and ';'.
2607   if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2608     return 4;
2609 
2610   // In Objective-C method expressions, prefer breaking before "param:" over
2611   // breaking after it.
2612   if (Right.is(TT_SelectorName))
2613     return 0;
2614   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2615     return Line.MightBeFunctionDecl ? 50 : 500;
2616 
2617   // In Objective-C type declarations, avoid breaking after the category's
2618   // open paren (we'll prefer breaking after the protocol list's opening
2619   // angle bracket, if present).
2620   if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
2621       Left.Previous->isOneOf(tok::identifier, tok::greater))
2622     return 500;
2623 
2624   if (Left.is(tok::l_paren) && InFunctionDecl &&
2625       Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2626     return 100;
2627   if (Left.is(tok::l_paren) && Left.Previous &&
2628       (Left.Previous->is(tok::kw_for) || Left.Previous->isIf()))
2629     return 1000;
2630   if (Left.is(tok::equal) && InFunctionDecl)
2631     return 110;
2632   if (Right.is(tok::r_brace))
2633     return 1;
2634   if (Left.is(TT_TemplateOpener))
2635     return 100;
2636   if (Left.opensScope()) {
2637     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2638       return 0;
2639     if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
2640       return 19;
2641     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2642                                    : 19;
2643   }
2644   if (Left.is(TT_JavaAnnotation))
2645     return 50;
2646 
2647   if (Left.is(TT_UnaryOperator))
2648     return 60;
2649   if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2650       Left.Previous->isLabelString() &&
2651       (Left.NextOperator || Left.OperatorIndex != 0))
2652     return 50;
2653   if (Right.is(tok::plus) && Left.isLabelString() &&
2654       (Right.NextOperator || Right.OperatorIndex != 0))
2655     return 25;
2656   if (Left.is(tok::comma))
2657     return 1;
2658   if (Right.is(tok::lessless) && Left.isLabelString() &&
2659       (Right.NextOperator || Right.OperatorIndex != 1))
2660     return 25;
2661   if (Right.is(tok::lessless)) {
2662     // Breaking at a << is really cheap.
2663     if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2664       // Slightly prefer to break before the first one in log-like statements.
2665       return 2;
2666     return 1;
2667   }
2668   if (Left.ClosesTemplateDeclaration)
2669     return Style.PenaltyBreakTemplateDeclaration;
2670   if (Left.is(TT_ConditionalExpr))
2671     return prec::Conditional;
2672   prec::Level Level = Left.getPrecedence();
2673   if (Level == prec::Unknown)
2674     Level = Right.getPrecedence();
2675   if (Level == prec::Assignment)
2676     return Style.PenaltyBreakAssignment;
2677   if (Level != prec::Unknown)
2678     return Level;
2679 
2680   return 3;
2681 }
2682 
2683 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
2684   return Style.SpaceBeforeParens == FormatStyle::SBPO_Always ||
2685          (Style.SpaceBeforeParens == FormatStyle::SBPO_NonEmptyParentheses &&
2686           Right.ParameterCount > 0);
2687 }
2688 
2689 /// Returns \c true if the token is followed by a boolean condition, \c false
2690 /// otherwise.
2691 static bool isKeywordWithCondition(const FormatToken &Tok) {
2692   return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
2693                      tok::kw_constexpr, tok::kw_catch);
2694 }
2695 
2696 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2697                                           const FormatToken &Left,
2698                                           const FormatToken &Right) {
2699   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2700     return true;
2701   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2702     return true;
2703   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2704       Left.Tok.getObjCKeywordID() == tok::objc_property)
2705     return true;
2706   if (Right.is(tok::hashhash))
2707     return Left.is(tok::hash);
2708   if (Left.isOneOf(tok::hashhash, tok::hash))
2709     return Right.is(tok::hash);
2710   if ((Left.is(tok::l_paren) && Right.is(tok::r_paren)) ||
2711       (Left.is(tok::l_brace) && Left.BlockKind != BK_Block &&
2712        Right.is(tok::r_brace) && Right.BlockKind != BK_Block))
2713     return Style.SpaceInEmptyParentheses;
2714   if (Style.SpacesInConditionalStatement) {
2715     if (Left.is(tok::l_paren) && Left.Previous &&
2716         isKeywordWithCondition(*Left.Previous))
2717       return true;
2718     if (Right.is(tok::r_paren) && Right.MatchingParen &&
2719         Right.MatchingParen->Previous &&
2720         isKeywordWithCondition(*Right.MatchingParen->Previous))
2721       return true;
2722   }
2723   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2724     return (Right.is(TT_CastRParen) ||
2725             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2726                ? Style.SpacesInCStyleCastParentheses
2727                : Style.SpacesInParentheses;
2728   if (Right.isOneOf(tok::semi, tok::comma))
2729     return false;
2730   if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
2731     bool IsLightweightGeneric = Right.MatchingParen &&
2732                                 Right.MatchingParen->Next &&
2733                                 Right.MatchingParen->Next->is(tok::colon);
2734     return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
2735   }
2736   if (Right.is(tok::less) && Left.is(tok::kw_template))
2737     return Style.SpaceAfterTemplateKeyword;
2738   if (Left.isOneOf(tok::exclaim, tok::tilde))
2739     return false;
2740   if (Left.is(tok::at) &&
2741       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2742                     tok::numeric_constant, tok::l_paren, tok::l_brace,
2743                     tok::kw_true, tok::kw_false))
2744     return false;
2745   if (Left.is(tok::colon))
2746     return !Left.is(TT_ObjCMethodExpr);
2747   if (Left.is(tok::coloncolon))
2748     return false;
2749   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
2750     if (Style.Language == FormatStyle::LK_TextProto ||
2751         (Style.Language == FormatStyle::LK_Proto &&
2752          (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
2753       // Format empty list as `<>`.
2754       if (Left.is(tok::less) && Right.is(tok::greater))
2755         return false;
2756       return !Style.Cpp11BracedListStyle;
2757     }
2758     return false;
2759   }
2760   if (Right.is(tok::ellipsis))
2761     return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2762                                     Left.Previous->is(tok::kw_case));
2763   if (Left.is(tok::l_square) && Right.is(tok::amp))
2764     return Style.SpacesInSquareBrackets;
2765   if (Right.is(TT_PointerOrReference)) {
2766     if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2767       if (!Left.MatchingParen)
2768         return true;
2769       FormatToken *TokenBeforeMatchingParen =
2770           Left.MatchingParen->getPreviousNonComment();
2771       if (!TokenBeforeMatchingParen ||
2772           !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype,
2773                                              TT_TypenameMacro))
2774         return true;
2775     }
2776     return (Left.Tok.isLiteral() ||
2777             (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2778              (Style.PointerAlignment != FormatStyle::PAS_Left ||
2779               (Line.IsMultiVariableDeclStmt &&
2780                (Left.NestingLevel == 0 ||
2781                 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2782   }
2783   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2784       (!Left.is(TT_PointerOrReference) ||
2785        (Style.PointerAlignment != FormatStyle::PAS_Right &&
2786         !Line.IsMultiVariableDeclStmt)))
2787     return true;
2788   if (Left.is(TT_PointerOrReference))
2789     return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2790            (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2791             !Right.is(TT_StartOfName)) ||
2792            (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2793            (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2794                            tok::l_paren) &&
2795             (Style.PointerAlignment != FormatStyle::PAS_Right &&
2796              !Line.IsMultiVariableDeclStmt) &&
2797             Left.Previous &&
2798             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon,
2799                                     tok::l_square));
2800   if (Right.is(tok::star) && Left.is(tok::l_paren))
2801     return false;
2802   if (Right.isOneOf(tok::star, tok::amp, tok::ampamp) &&
2803       (Left.is(tok::identifier) || Left.isSimpleTypeSpecifier()) &&
2804       // Space between the type and the * in:
2805       //   operator void*()
2806       //   operator char*()
2807       //   operator /*comment*/ const char*()
2808       //   operator volatile /*comment*/ char*()
2809       //   operator Foo*()
2810       // dependent on PointerAlignment style.
2811       Left.Previous &&
2812       (Left.Previous->endsSequence(tok::kw_operator) ||
2813        Left.Previous->endsSequence(tok::kw_const, tok::kw_operator) ||
2814        Left.Previous->endsSequence(tok::kw_volatile, tok::kw_operator)))
2815     return (Style.PointerAlignment != FormatStyle::PAS_Left);
2816   const auto SpaceRequiredForArrayInitializerLSquare =
2817       [](const FormatToken &LSquareTok, const FormatStyle &Style) {
2818         return Style.SpacesInContainerLiterals ||
2819                ((Style.Language == FormatStyle::LK_Proto ||
2820                  Style.Language == FormatStyle::LK_TextProto) &&
2821                 !Style.Cpp11BracedListStyle &&
2822                 LSquareTok.endsSequence(tok::l_square, tok::colon,
2823                                         TT_SelectorName));
2824       };
2825   if (Left.is(tok::l_square))
2826     return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
2827             SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
2828            (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare,
2829                          TT_LambdaLSquare) &&
2830             Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2831   if (Right.is(tok::r_square))
2832     return Right.MatchingParen &&
2833            ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
2834              SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
2835                                                      Style)) ||
2836             (Style.SpacesInSquareBrackets &&
2837              Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2838                                           TT_StructuredBindingLSquare,
2839                                           TT_LambdaLSquare)) ||
2840             Right.MatchingParen->is(TT_AttributeParen));
2841   if (Right.is(tok::l_square) &&
2842       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2843                      TT_DesignatedInitializerLSquare,
2844                      TT_StructuredBindingLSquare, TT_AttributeSquare) &&
2845       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral) &&
2846       !(!Left.is(tok::r_square) && Style.SpaceBeforeSquareBrackets &&
2847         Right.is(TT_ArraySubscriptLSquare)))
2848     return false;
2849   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2850     return !Left.Children.empty(); // No spaces in "{}".
2851   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2852       (Right.is(tok::r_brace) && Right.MatchingParen &&
2853        Right.MatchingParen->BlockKind != BK_Block))
2854     return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true;
2855   if (Left.is(TT_BlockComment))
2856     // No whitespace in x(/*foo=*/1), except for JavaScript.
2857     return Style.Language == FormatStyle::LK_JavaScript ||
2858            !Left.TokenText.endswith("=*/");
2859   if (Right.is(tok::l_paren)) {
2860     if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
2861         (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
2862       return true;
2863     return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2864            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2865             (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while,
2866                           tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2867                           TT_ObjCForIn) ||
2868              Left.isIf(Line.Type != LT_PreprocessorDirective) ||
2869              (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2870                            tok::kw_new, tok::kw_delete) &&
2871               (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2872            (spaceRequiredBeforeParens(Right) &&
2873             (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2874              Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier() ||
2875              (Left.is(tok::r_square) && Left.MatchingParen &&
2876               Left.MatchingParen->is(TT_LambdaLSquare))) &&
2877             Line.Type != LT_PreprocessorDirective);
2878   }
2879   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2880     return false;
2881   if (Right.is(TT_UnaryOperator))
2882     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2883            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2884   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2885                     tok::r_paren) ||
2886        Left.isSimpleTypeSpecifier()) &&
2887       Right.is(tok::l_brace) && Right.getNextNonComment() &&
2888       Right.BlockKind != BK_Block)
2889     return false;
2890   if (Left.is(tok::period) || Right.is(tok::period))
2891     return false;
2892   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2893     return false;
2894   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2895       Left.MatchingParen->Previous &&
2896       (Left.MatchingParen->Previous->is(tok::period) ||
2897        Left.MatchingParen->Previous->is(tok::coloncolon)))
2898     // Java call to generic function with explicit type:
2899     // A.<B<C<...>>>DoSomething();
2900     // A::<B<C<...>>>DoSomething();  // With a Java 8 method reference.
2901     return false;
2902   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2903     return false;
2904   if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
2905     // Objective-C dictionary literal -> no space after opening brace.
2906     return false;
2907   if (Right.is(tok::r_brace) && Right.MatchingParen &&
2908       Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
2909     // Objective-C dictionary literal -> no space before closing brace.
2910     return false;
2911   if (Right.Type == TT_TrailingAnnotation &&
2912       Right.isOneOf(tok::amp, tok::ampamp) &&
2913       Left.isOneOf(tok::kw_const, tok::kw_volatile) &&
2914       (!Right.Next || Right.Next->is(tok::semi)))
2915     // Match const and volatile ref-qualifiers without any additional
2916     // qualifiers such as
2917     // void Fn() const &;
2918     return Style.PointerAlignment != FormatStyle::PAS_Left;
2919   return true;
2920 }
2921 
2922 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2923                                          const FormatToken &Right) {
2924   const FormatToken &Left = *Right.Previous;
2925   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2926     return true; // Never ever merge two identifiers.
2927   if (Style.isCpp()) {
2928     if (Left.is(tok::kw_operator))
2929       return Right.is(tok::coloncolon);
2930     if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
2931         !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
2932       return true;
2933   } else if (Style.Language == FormatStyle::LK_Proto ||
2934              Style.Language == FormatStyle::LK_TextProto) {
2935     if (Right.is(tok::period) &&
2936         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2937                      Keywords.kw_repeated, Keywords.kw_extend))
2938       return true;
2939     if (Right.is(tok::l_paren) &&
2940         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2941       return true;
2942     if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2943       return true;
2944     // Slashes occur in text protocol extension syntax: [type/type] { ... }.
2945     if (Left.is(tok::slash) || Right.is(tok::slash))
2946       return false;
2947     if (Left.MatchingParen &&
2948         Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
2949         Right.isOneOf(tok::l_brace, tok::less))
2950       return !Style.Cpp11BracedListStyle;
2951     // A percent is probably part of a formatting specification, such as %lld.
2952     if (Left.is(tok::percent))
2953       return false;
2954     // Preserve the existence of a space before a percent for cases like 0x%04x
2955     // and "%d %d"
2956     if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
2957       return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
2958   } else if (Style.isCSharp()) {
2959     // Require spaces around '{' and  before '}' unless they appear in
2960     // interpolated strings. Interpolated strings are merged into a single token
2961     // so cannot have spaces inserted by this function.
2962 
2963     // No space between 'this' and '['
2964     if (Left.is(tok::kw_this) && Right.is(tok::l_square))
2965       return false;
2966 
2967     // No space between 'new' and '('
2968     if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
2969       return false;
2970 
2971     // Space before { (including space within '{ {').
2972     if (Right.is(tok::l_brace))
2973       return true;
2974 
2975     // Spaces inside braces.
2976     if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
2977       return true;
2978 
2979     if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
2980       return true;
2981 
2982     // Spaces around '=>'.
2983     if (Left.is(TT_JsFatArrow) || Right.is(TT_JsFatArrow))
2984       return true;
2985 
2986     // No spaces around attribute target colons
2987     if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
2988       return false;
2989 
2990     // space between type and variable e.g. Dictionary<string,string> foo;
2991     if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
2992       return true;
2993 
2994     // spaces inside square brackets.
2995     if (Left.is(tok::l_square) || Right.is(tok::r_square))
2996       return Style.SpacesInSquareBrackets;
2997 
2998     // No space before ? in nullable types.
2999     if (Right.is(TT_CSharpNullable))
3000       return false;
3001 
3002     // Require space after ? in nullable types except in generics and casts.
3003     if (Left.is(TT_CSharpNullable))
3004       return !Right.isOneOf(TT_TemplateCloser, tok::r_paren);
3005 
3006     // No space before or after '?.'.
3007     if (Left.is(TT_CSharpNullConditional) || Right.is(TT_CSharpNullConditional))
3008       return false;
3009 
3010     // Space before and after '??'.
3011     if (Left.is(TT_CSharpNullCoalescing) || Right.is(TT_CSharpNullCoalescing))
3012       return true;
3013 
3014     // No space before '?['.
3015     if (Right.is(TT_CSharpNullConditionalLSquare))
3016       return false;
3017 
3018     // No space between consecutive commas '[,,]'.
3019     if (Left.is(tok::comma) && Right.is(tok::comma))
3020       return false;
3021 
3022     // Possible space inside `?[ 0 ]`.
3023     if (Left.is(TT_CSharpNullConditionalLSquare))
3024       return Style.SpacesInSquareBrackets;
3025 
3026     // space between keywords and paren e.g. "using ("
3027     if (Right.is(tok::l_paren))
3028       if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when))
3029         return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements ||
3030                spaceRequiredBeforeParens(Right);
3031   } else if (Style.Language == FormatStyle::LK_JavaScript) {
3032     if (Left.is(TT_JsFatArrow))
3033       return true;
3034     // for await ( ...
3035     if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
3036         Left.Previous->is(tok::kw_for))
3037       return true;
3038     if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
3039         Right.MatchingParen) {
3040       const FormatToken *Next = Right.MatchingParen->getNextNonComment();
3041       // An async arrow function, for example: `x = async () => foo();`,
3042       // as opposed to calling a function called async: `x = async();`
3043       if (Next && Next->is(TT_JsFatArrow))
3044         return true;
3045     }
3046     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
3047         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
3048       return false;
3049     // In tagged template literals ("html`bar baz`"), there is no space between
3050     // the tag identifier and the template string. getIdentifierInfo makes sure
3051     // that the identifier is not a pseudo keyword like `yield`, either.
3052     if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
3053         Right.is(TT_TemplateString))
3054       return false;
3055     if (Right.is(tok::star) &&
3056         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
3057       return false;
3058     if (Right.isOneOf(tok::l_brace, tok::l_square) &&
3059         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
3060                      Keywords.kw_extends, Keywords.kw_implements))
3061       return true;
3062     if (Right.is(tok::l_paren)) {
3063       // JS methods can use some keywords as names (e.g. `delete()`).
3064       if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
3065         return false;
3066       // Valid JS method names can include keywords, e.g. `foo.delete()` or
3067       // `bar.instanceof()`. Recognize call positions by preceding period.
3068       if (Left.Previous && Left.Previous->is(tok::period) &&
3069           Left.Tok.getIdentifierInfo())
3070         return false;
3071       // Additional unary JavaScript operators that need a space after.
3072       if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
3073                        tok::kw_void))
3074         return true;
3075     }
3076     // `foo as const;` casts into a const type.
3077     if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
3078       return false;
3079     }
3080     if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
3081                       tok::kw_const) ||
3082          // "of" is only a keyword if it appears after another identifier
3083          // (e.g. as "const x of y" in a for loop), or after a destructuring
3084          // operation (const [x, y] of z, const {a, b} of c).
3085          (Left.is(Keywords.kw_of) && Left.Previous &&
3086           (Left.Previous->Tok.is(tok::identifier) ||
3087            Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
3088         (!Left.Previous || !Left.Previous->is(tok::period)))
3089       return true;
3090     if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
3091         Left.Previous->is(tok::period) && Right.is(tok::l_paren))
3092       return false;
3093     if (Left.is(Keywords.kw_as) &&
3094         Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
3095       return true;
3096     if (Left.is(tok::kw_default) && Left.Previous &&
3097         Left.Previous->is(tok::kw_export))
3098       return true;
3099     if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
3100       return true;
3101     if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
3102       return false;
3103     if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
3104       return false;
3105     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
3106         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
3107       return false;
3108     if (Left.is(tok::ellipsis))
3109       return false;
3110     if (Left.is(TT_TemplateCloser) &&
3111         !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
3112                        Keywords.kw_implements, Keywords.kw_extends))
3113       // Type assertions ('<type>expr') are not followed by whitespace. Other
3114       // locations that should have whitespace following are identified by the
3115       // above set of follower tokens.
3116       return false;
3117     if (Right.is(TT_JsNonNullAssertion))
3118       return false;
3119     if (Left.is(TT_JsNonNullAssertion) &&
3120         Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
3121       return true; // "x! as string", "x! in y"
3122   } else if (Style.Language == FormatStyle::LK_Java) {
3123     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
3124       return true;
3125     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
3126       return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
3127     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
3128                       tok::kw_protected) ||
3129          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
3130                       Keywords.kw_native)) &&
3131         Right.is(TT_TemplateOpener))
3132       return true;
3133   }
3134   if (Left.is(TT_ImplicitStringLiteral))
3135     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
3136   if (Line.Type == LT_ObjCMethodDecl) {
3137     if (Left.is(TT_ObjCMethodSpecifier))
3138       return true;
3139     if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
3140       // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
3141       // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
3142       // method declaration.
3143       return false;
3144   }
3145   if (Line.Type == LT_ObjCProperty &&
3146       (Right.is(tok::equal) || Left.is(tok::equal)))
3147     return false;
3148 
3149   if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
3150       Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
3151     return true;
3152   if (Right.is(TT_OverloadedOperatorLParen))
3153     return spaceRequiredBeforeParens(Right);
3154   if (Left.is(tok::comma))
3155     return true;
3156   if (Right.is(tok::comma))
3157     return false;
3158   if (Right.is(TT_ObjCBlockLParen))
3159     return true;
3160   if (Right.is(TT_CtorInitializerColon))
3161     return Style.SpaceBeforeCtorInitializerColon;
3162   if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
3163     return false;
3164   if (Right.is(TT_RangeBasedForLoopColon) &&
3165       !Style.SpaceBeforeRangeBasedForLoopColon)
3166     return false;
3167   if (Right.is(tok::colon)) {
3168     if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
3169         !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
3170       return false;
3171     if (Right.is(TT_ObjCMethodExpr))
3172       return false;
3173     if (Left.is(tok::question))
3174       return false;
3175     if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
3176       return false;
3177     if (Right.is(TT_DictLiteral))
3178       return Style.SpacesInContainerLiterals;
3179     if (Right.is(TT_AttributeColon))
3180       return false;
3181     if (Right.is(TT_CSharpNamedArgumentColon))
3182       return false;
3183     return true;
3184   }
3185   if (Left.is(TT_UnaryOperator)) {
3186     if (!Right.is(tok::l_paren)) {
3187       // The alternative operators for ~ and ! are "compl" and "not".
3188       // If they are used instead, we do not want to combine them with
3189       // the token to the right, unless that is a left paren.
3190       if (Left.is(tok::exclaim) && Left.TokenText == "not")
3191         return true;
3192       if (Left.is(tok::tilde) && Left.TokenText == "compl")
3193         return true;
3194       // Lambda captures allow for a lone &, so "&]" needs to be properly
3195       // handled.
3196       if (Left.is(tok::amp) && Right.is(tok::r_square))
3197         return Style.SpacesInSquareBrackets;
3198     }
3199     return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
3200            Right.is(TT_BinaryOperator);
3201   }
3202 
3203   // If the next token is a binary operator or a selector name, we have
3204   // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
3205   if (Left.is(TT_CastRParen))
3206     return Style.SpaceAfterCStyleCast ||
3207            Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
3208 
3209   if (Left.is(tok::greater) && Right.is(tok::greater)) {
3210     if (Style.Language == FormatStyle::LK_TextProto ||
3211         (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
3212       return !Style.Cpp11BracedListStyle;
3213     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
3214            (Style.Standard < FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
3215   }
3216   if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
3217       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
3218       (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
3219     return false;
3220   if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
3221       Right.getPrecedence() == prec::Assignment)
3222     return false;
3223   if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) &&
3224       (Left.is(tok::identifier) || Left.is(tok::kw_this)))
3225     return false;
3226   if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
3227     // Generally don't remove existing spaces between an identifier and "::".
3228     // The identifier might actually be a macro name such as ALWAYS_INLINE. If
3229     // this turns out to be too lenient, add analysis of the identifier itself.
3230     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
3231   if (Right.is(tok::coloncolon) &&
3232       !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren))
3233     return (Left.is(TT_TemplateOpener) &&
3234             Style.Standard < FormatStyle::LS_Cpp11) ||
3235            !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
3236                           tok::kw___super, TT_TemplateCloser,
3237                           TT_TemplateOpener)) ||
3238            (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
3239   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
3240     return Style.SpacesInAngles;
3241   // Space before TT_StructuredBindingLSquare.
3242   if (Right.is(TT_StructuredBindingLSquare))
3243     return !Left.isOneOf(tok::amp, tok::ampamp) ||
3244            Style.PointerAlignment != FormatStyle::PAS_Right;
3245   // Space before & or && following a TT_StructuredBindingLSquare.
3246   if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
3247       Right.isOneOf(tok::amp, tok::ampamp))
3248     return Style.PointerAlignment != FormatStyle::PAS_Left;
3249   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
3250       (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
3251        !Right.is(tok::r_paren)))
3252     return true;
3253   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
3254       Right.isNot(TT_FunctionTypeLParen))
3255     return spaceRequiredBeforeParens(Right);
3256   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
3257       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
3258     return false;
3259   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
3260       Line.startsWith(tok::hash))
3261     return true;
3262   if (Right.is(TT_TrailingUnaryOperator))
3263     return false;
3264   if (Left.is(TT_RegexLiteral))
3265     return false;
3266   return spaceRequiredBetween(Line, Left, Right);
3267 }
3268 
3269 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
3270 static bool isAllmanBrace(const FormatToken &Tok) {
3271   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
3272          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
3273 }
3274 
3275 // Returns 'true' if 'Tok' is an function argument.
3276 static bool IsFunctionArgument(const FormatToken &Tok) {
3277   return Tok.MatchingParen && Tok.MatchingParen->Next &&
3278          Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren);
3279 }
3280 
3281 static bool
3282 isItAnEmptyLambdaAllowed(const FormatToken &Tok,
3283                          FormatStyle::ShortLambdaStyle ShortLambdaOption) {
3284   return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
3285 }
3286 
3287 static bool
3288 isItAInlineLambdaAllowed(const FormatToken &Tok,
3289                          FormatStyle::ShortLambdaStyle ShortLambdaOption) {
3290   return (ShortLambdaOption == FormatStyle::SLS_Inline &&
3291           IsFunctionArgument(Tok)) ||
3292          (ShortLambdaOption == FormatStyle::SLS_All);
3293 }
3294 
3295 static bool isOneChildWithoutMustBreakBefore(const FormatToken &Tok) {
3296   if (Tok.Children.size() != 1)
3297     return false;
3298   FormatToken *curElt = Tok.Children[0]->First;
3299     while (curElt) {
3300       if (curElt->MustBreakBefore)
3301         return false;
3302       curElt = curElt->Next;
3303     }
3304   return true;
3305 }
3306 static bool
3307 isAllmanLambdaBrace(const FormatToken &Tok) {
3308   return (Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
3309       !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral));
3310 }
3311 
3312 static bool
3313 isAllmanBraceIncludedBreakableLambda(const FormatToken &Tok,
3314                             FormatStyle::ShortLambdaStyle ShortLambdaOption) {
3315   if (!isAllmanLambdaBrace(Tok))
3316     return false;
3317 
3318   if (isItAnEmptyLambdaAllowed(Tok, ShortLambdaOption))
3319     return false;
3320 
3321   return !isItAInlineLambdaAllowed(Tok, ShortLambdaOption) ||
3322          !isOneChildWithoutMustBreakBefore(Tok);
3323 }
3324 
3325 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
3326                                      const FormatToken &Right) {
3327   const FormatToken &Left = *Right.Previous;
3328   if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
3329     return true;
3330 
3331   if (Style.isCSharp()) {
3332     if (Right.is(TT_CSharpNamedArgumentColon) ||
3333         Left.is(TT_CSharpNamedArgumentColon))
3334       return false;
3335     if (Right.is(TT_CSharpGenericTypeConstraint))
3336       return true;
3337   } else if (Style.Language == FormatStyle::LK_JavaScript) {
3338     // FIXME: This might apply to other languages and token kinds.
3339     if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
3340         Left.Previous->is(tok::string_literal))
3341       return true;
3342     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
3343         Left.Previous && Left.Previous->is(tok::equal) &&
3344         Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
3345                             tok::kw_const) &&
3346         // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
3347         // above.
3348         !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
3349       // Object literals on the top level of a file are treated as "enum-style".
3350       // Each key/value pair is put on a separate line, instead of bin-packing.
3351       return true;
3352     if (Left.is(tok::l_brace) && Line.Level == 0 &&
3353         (Line.startsWith(tok::kw_enum) ||
3354          Line.startsWith(tok::kw_const, tok::kw_enum) ||
3355          Line.startsWith(tok::kw_export, tok::kw_enum) ||
3356          Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
3357       // JavaScript top-level enum key/value pairs are put on separate lines
3358       // instead of bin-packing.
3359       return true;
3360     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous &&
3361         Left.Previous->is(TT_JsFatArrow)) {
3362       // JS arrow function (=> {...}).
3363       switch (Style.AllowShortLambdasOnASingleLine) {
3364       case FormatStyle::SLS_All:
3365         return false;
3366       case FormatStyle::SLS_None:
3367         return true;
3368       case FormatStyle::SLS_Empty:
3369         return !Left.Children.empty();
3370       case FormatStyle::SLS_Inline:
3371         // allow one-lining inline (e.g. in function call args) and empty arrow
3372         // functions.
3373         return (Left.NestingLevel == 0 && Line.Level == 0) &&
3374                !Left.Children.empty();
3375       }
3376       llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
3377     }
3378 
3379     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
3380         !Left.Children.empty())
3381       // Support AllowShortFunctionsOnASingleLine for JavaScript.
3382       return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
3383              Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
3384              (Left.NestingLevel == 0 && Line.Level == 0 &&
3385               Style.AllowShortFunctionsOnASingleLine &
3386                   FormatStyle::SFS_InlineOnly);
3387   } else if (Style.Language == FormatStyle::LK_Java) {
3388     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
3389         Right.Next->is(tok::string_literal))
3390       return true;
3391   } else if (Style.Language == FormatStyle::LK_Cpp ||
3392              Style.Language == FormatStyle::LK_ObjC ||
3393              Style.Language == FormatStyle::LK_Proto ||
3394              Style.Language == FormatStyle::LK_TableGen ||
3395              Style.Language == FormatStyle::LK_TextProto) {
3396     if (Left.isStringLiteral() && Right.isStringLiteral())
3397       return true;
3398   }
3399 
3400   // If the last token before a '}', ']', or ')' is a comma or a trailing
3401   // comment, the intention is to insert a line break after it in order to make
3402   // shuffling around entries easier. Import statements, especially in
3403   // JavaScript, can be an exception to this rule.
3404   if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
3405     const FormatToken *BeforeClosingBrace = nullptr;
3406     if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
3407          (Style.Language == FormatStyle::LK_JavaScript &&
3408           Left.is(tok::l_paren))) &&
3409         Left.BlockKind != BK_Block && Left.MatchingParen)
3410       BeforeClosingBrace = Left.MatchingParen->Previous;
3411     else if (Right.MatchingParen &&
3412              (Right.MatchingParen->isOneOf(tok::l_brace,
3413                                            TT_ArrayInitializerLSquare) ||
3414               (Style.Language == FormatStyle::LK_JavaScript &&
3415                Right.MatchingParen->is(tok::l_paren))))
3416       BeforeClosingBrace = &Left;
3417     if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
3418                                BeforeClosingBrace->isTrailingComment()))
3419       return true;
3420   }
3421 
3422   if (Right.is(tok::comment))
3423     return Left.BlockKind != BK_BracedInit &&
3424            Left.isNot(TT_CtorInitializerColon) &&
3425            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
3426   if (Left.isTrailingComment())
3427     return true;
3428   if (Right.Previous->IsUnterminatedLiteral)
3429     return true;
3430   if (Right.is(tok::lessless) && Right.Next &&
3431       Right.Previous->is(tok::string_literal) &&
3432       Right.Next->is(tok::string_literal))
3433     return true;
3434   if (Right.Previous->ClosesTemplateDeclaration &&
3435       Right.Previous->MatchingParen &&
3436       Right.Previous->MatchingParen->NestingLevel == 0 &&
3437       Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
3438     return true;
3439   if (Right.is(TT_CtorInitializerComma) &&
3440       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3441       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
3442     return true;
3443   if (Right.is(TT_CtorInitializerColon) &&
3444       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3445       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
3446     return true;
3447   // Break only if we have multiple inheritance.
3448   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
3449       Right.is(TT_InheritanceComma))
3450     return true;
3451   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
3452     // Multiline raw string literals are special wrt. line breaks. The author
3453     // has made a deliberate choice and might have aligned the contents of the
3454     // string literal accordingly. Thus, we try keep existing line breaks.
3455     return Right.IsMultiline && Right.NewlinesBefore > 0;
3456   if ((Right.Previous->is(tok::l_brace) ||
3457        (Right.Previous->is(tok::less) && Right.Previous->Previous &&
3458         Right.Previous->Previous->is(tok::equal))) &&
3459       Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
3460     // Don't put enums or option definitions onto single lines in protocol
3461     // buffers.
3462     return true;
3463   }
3464   if (Right.is(TT_InlineASMBrace))
3465     return Right.HasUnescapedNewline;
3466 
3467   auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
3468   if (Style.BraceWrapping.BeforeLambdaBody &&
3469       (isAllmanBraceIncludedBreakableLambda(Left, ShortLambdaOption) ||
3470        isAllmanBraceIncludedBreakableLambda(Right, ShortLambdaOption))) {
3471       return true;
3472   }
3473 
3474   if (isAllmanBrace(Left) || isAllmanBrace(Right))
3475     return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
3476            (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
3477             Style.BraceWrapping.AfterEnum) ||
3478            (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
3479            (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
3480   if (Left.is(TT_ObjCBlockLBrace) &&
3481       Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
3482     return true;
3483 
3484   if (Left.is(TT_LambdaLBrace)) {
3485     if (IsFunctionArgument(Left) &&
3486         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
3487       return false;
3488 
3489     if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
3490         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
3491         (!Left.Children.empty() &&
3492          Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty))
3493       return true;
3494   }
3495 
3496   // Put multiple Java annotation on a new line.
3497   if ((Style.Language == FormatStyle::LK_Java ||
3498        Style.Language == FormatStyle::LK_JavaScript) &&
3499       Left.is(TT_LeadingJavaAnnotation) &&
3500       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
3501       (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
3502     return true;
3503 
3504   if (Right.is(TT_ProtoExtensionLSquare))
3505     return true;
3506 
3507   // In text proto instances if a submessage contains at least 2 entries and at
3508   // least one of them is a submessage, like A { ... B { ... } ... },
3509   // put all of the entries of A on separate lines by forcing the selector of
3510   // the submessage B to be put on a newline.
3511   //
3512   // Example: these can stay on one line:
3513   // a { scalar_1: 1 scalar_2: 2 }
3514   // a { b { key: value } }
3515   //
3516   // and these entries need to be on a new line even if putting them all in one
3517   // line is under the column limit:
3518   // a {
3519   //   scalar: 1
3520   //   b { key: value }
3521   // }
3522   //
3523   // We enforce this by breaking before a submessage field that has previous
3524   // siblings, *and* breaking before a field that follows a submessage field.
3525   //
3526   // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
3527   // the TT_SelectorName there, but we don't want to break inside the brackets.
3528   //
3529   // Another edge case is @submessage { key: value }, which is a common
3530   // substitution placeholder. In this case we want to keep `@` and `submessage`
3531   // together.
3532   //
3533   // We ensure elsewhere that extensions are always on their own line.
3534   if ((Style.Language == FormatStyle::LK_Proto ||
3535        Style.Language == FormatStyle::LK_TextProto) &&
3536       Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
3537     // Keep `@submessage` together in:
3538     // @submessage { key: value }
3539     if (Right.Previous && Right.Previous->is(tok::at))
3540       return false;
3541     // Look for the scope opener after selector in cases like:
3542     // selector { ...
3543     // selector: { ...
3544     // selector: @base { ...
3545     FormatToken *LBrace = Right.Next;
3546     if (LBrace && LBrace->is(tok::colon)) {
3547       LBrace = LBrace->Next;
3548       if (LBrace && LBrace->is(tok::at)) {
3549         LBrace = LBrace->Next;
3550         if (LBrace)
3551           LBrace = LBrace->Next;
3552       }
3553     }
3554     if (LBrace &&
3555         // The scope opener is one of {, [, <:
3556         // selector { ... }
3557         // selector [ ... ]
3558         // selector < ... >
3559         //
3560         // In case of selector { ... }, the l_brace is TT_DictLiteral.
3561         // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
3562         // so we check for immediately following r_brace.
3563         ((LBrace->is(tok::l_brace) &&
3564           (LBrace->is(TT_DictLiteral) ||
3565            (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
3566          LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
3567       // If Left.ParameterCount is 0, then this submessage entry is not the
3568       // first in its parent submessage, and we want to break before this entry.
3569       // If Left.ParameterCount is greater than 0, then its parent submessage
3570       // might contain 1 or more entries and we want to break before this entry
3571       // if it contains at least 2 entries. We deal with this case later by
3572       // detecting and breaking before the next entry in the parent submessage.
3573       if (Left.ParameterCount == 0)
3574         return true;
3575       // However, if this submessage is the first entry in its parent
3576       // submessage, Left.ParameterCount might be 1 in some cases.
3577       // We deal with this case later by detecting an entry
3578       // following a closing paren of this submessage.
3579     }
3580 
3581     // If this is an entry immediately following a submessage, it will be
3582     // preceded by a closing paren of that submessage, like in:
3583     //     left---.  .---right
3584     //            v  v
3585     // sub: { ... } key: value
3586     // If there was a comment between `}` an `key` above, then `key` would be
3587     // put on a new line anyways.
3588     if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
3589       return true;
3590   }
3591 
3592   // Deal with lambda arguments in C++ - we want consistent line breaks whether
3593   // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
3594   // as aggressive line breaks are placed when the lambda is not the last arg.
3595   if ((Style.Language == FormatStyle::LK_Cpp ||
3596        Style.Language == FormatStyle::LK_ObjC) &&
3597       Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
3598       !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
3599     // Multiple lambdas in the same function call force line breaks.
3600     if (Left.BlockParameterCount > 1)
3601       return true;
3602 
3603     // A lambda followed by another arg forces a line break.
3604     if (!Left.Role)
3605       return false;
3606     auto Comma = Left.Role->lastComma();
3607     if (!Comma)
3608       return false;
3609     auto Next = Comma->getNextNonComment();
3610     if (!Next)
3611       return false;
3612     if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
3613       return true;
3614   }
3615 
3616   return false;
3617 }
3618 
3619 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
3620                                     const FormatToken &Right) {
3621   const FormatToken &Left = *Right.Previous;
3622   // Language-specific stuff.
3623   if (Style.isCSharp()) {
3624     if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
3625         Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon))
3626       return false;
3627     // Only break after commas for generic type constraints.
3628     if (Line.First->is(TT_CSharpGenericTypeConstraint))
3629       return Left.is(TT_CSharpGenericTypeConstraintComma);
3630   } else if (Style.Language == FormatStyle::LK_Java) {
3631     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3632                      Keywords.kw_implements))
3633       return false;
3634     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3635                       Keywords.kw_implements))
3636       return true;
3637   } else if (Style.Language == FormatStyle::LK_JavaScript) {
3638     const FormatToken *NonComment = Right.getPreviousNonComment();
3639     if (NonComment &&
3640         NonComment->isOneOf(
3641             tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
3642             tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
3643             tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
3644             Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
3645             Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
3646       return false; // Otherwise automatic semicolon insertion would trigger.
3647     if (Right.NestingLevel == 0 &&
3648         (Left.Tok.getIdentifierInfo() ||
3649          Left.isOneOf(tok::r_square, tok::r_paren)) &&
3650         Right.isOneOf(tok::l_square, tok::l_paren))
3651       return false; // Otherwise automatic semicolon insertion would trigger.
3652     if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
3653       return false;
3654     if (Left.is(TT_JsTypeColon))
3655       return true;
3656     // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
3657     if (Left.is(tok::exclaim) && Right.is(tok::colon))
3658       return false;
3659     // Look for is type annotations like:
3660     // function f(): a is B { ... }
3661     // Do not break before is in these cases.
3662     if (Right.is(Keywords.kw_is)) {
3663       const FormatToken *Next = Right.getNextNonComment();
3664       // If `is` is followed by a colon, it's likely that it's a dict key, so
3665       // ignore it for this check.
3666       // For example this is common in Polymer:
3667       // Polymer({
3668       //   is: 'name',
3669       //   ...
3670       // });
3671       if (!Next || !Next->is(tok::colon))
3672         return false;
3673     }
3674     if (Left.is(Keywords.kw_in))
3675       return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
3676     if (Right.is(Keywords.kw_in))
3677       return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
3678     if (Right.is(Keywords.kw_as))
3679       return false; // must not break before as in 'x as type' casts
3680     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
3681       // extends and infer can appear as keywords in conditional types:
3682       //   https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
3683       // do not break before them, as the expressions are subject to ASI.
3684       return false;
3685     }
3686     if (Left.is(Keywords.kw_as))
3687       return true;
3688     if (Left.is(TT_JsNonNullAssertion))
3689       return true;
3690     if (Left.is(Keywords.kw_declare) &&
3691         Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
3692                       Keywords.kw_function, tok::kw_class, tok::kw_enum,
3693                       Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
3694                       Keywords.kw_let, tok::kw_const))
3695       // See grammar for 'declare' statements at:
3696       // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
3697       return false;
3698     if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
3699         Right.isOneOf(tok::identifier, tok::string_literal))
3700       return false; // must not break in "module foo { ...}"
3701     if (Right.is(TT_TemplateString) && Right.closesScope())
3702       return false;
3703     // Don't split tagged template literal so there is a break between the tag
3704     // identifier and template string.
3705     if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) {
3706       return false;
3707     }
3708     if (Left.is(TT_TemplateString) && Left.opensScope())
3709       return true;
3710   }
3711 
3712   if (Left.is(tok::at))
3713     return false;
3714   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
3715     return false;
3716   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
3717     return !Right.is(tok::l_paren);
3718   if (Right.is(TT_PointerOrReference))
3719     return Line.IsMultiVariableDeclStmt ||
3720            (Style.PointerAlignment == FormatStyle::PAS_Right &&
3721             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
3722   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
3723       Right.is(tok::kw_operator))
3724     return true;
3725   if (Left.is(TT_PointerOrReference))
3726     return false;
3727   if (Right.isTrailingComment())
3728     // We rely on MustBreakBefore being set correctly here as we should not
3729     // change the "binding" behavior of a comment.
3730     // The first comment in a braced lists is always interpreted as belonging to
3731     // the first list element. Otherwise, it should be placed outside of the
3732     // list.
3733     return Left.BlockKind == BK_BracedInit ||
3734            (Left.is(TT_CtorInitializerColon) &&
3735             Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
3736   if (Left.is(tok::question) && Right.is(tok::colon))
3737     return false;
3738   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
3739     return Style.BreakBeforeTernaryOperators;
3740   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
3741     return !Style.BreakBeforeTernaryOperators;
3742   if (Left.is(TT_InheritanceColon))
3743     return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
3744   if (Right.is(TT_InheritanceColon))
3745     return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
3746   if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
3747       Left.isNot(TT_SelectorName))
3748     return true;
3749 
3750   if (Right.is(tok::colon) &&
3751       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
3752     return false;
3753   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
3754     if (Style.Language == FormatStyle::LK_Proto ||
3755         Style.Language == FormatStyle::LK_TextProto) {
3756       if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
3757         return false;
3758       // Prevent cases like:
3759       //
3760       // submessage:
3761       //     { key: valueeeeeeeeeeee }
3762       //
3763       // when the snippet does not fit into one line.
3764       // Prefer:
3765       //
3766       // submessage: {
3767       //   key: valueeeeeeeeeeee
3768       // }
3769       //
3770       // instead, even if it is longer by one line.
3771       //
3772       // Note that this allows allows the "{" to go over the column limit
3773       // when the column limit is just between ":" and "{", but that does
3774       // not happen too often and alternative formattings in this case are
3775       // not much better.
3776       //
3777       // The code covers the cases:
3778       //
3779       // submessage: { ... }
3780       // submessage: < ... >
3781       // repeated: [ ... ]
3782       if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
3783            Right.is(TT_DictLiteral)) ||
3784           Right.is(TT_ArrayInitializerLSquare))
3785         return false;
3786     }
3787     return true;
3788   }
3789   if (Right.is(tok::r_square) && Right.MatchingParen &&
3790       Right.MatchingParen->is(TT_ProtoExtensionLSquare))
3791     return false;
3792   if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
3793                                     Right.Next->is(TT_ObjCMethodExpr)))
3794     return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
3795   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
3796     return true;
3797   if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
3798     return true;
3799   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
3800                     TT_OverloadedOperator))
3801     return false;
3802   if (Left.is(TT_RangeBasedForLoopColon))
3803     return true;
3804   if (Right.is(TT_RangeBasedForLoopColon))
3805     return false;
3806   if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
3807     return true;
3808   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
3809       Left.is(tok::kw_operator))
3810     return false;
3811   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
3812       Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
3813     return false;
3814   if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
3815       !Style.Cpp11BracedListStyle)
3816     return false;
3817   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
3818     return false;
3819   if (Left.is(tok::l_paren) && Left.Previous &&
3820       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
3821     return false;
3822   if (Right.is(TT_ImplicitStringLiteral))
3823     return false;
3824 
3825   if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
3826     return false;
3827   if (Right.is(tok::r_square) && Right.MatchingParen &&
3828       Right.MatchingParen->is(TT_LambdaLSquare))
3829     return false;
3830 
3831   // We only break before r_brace if there was a corresponding break before
3832   // the l_brace, which is tracked by BreakBeforeClosingBrace.
3833   if (Right.is(tok::r_brace))
3834     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
3835 
3836   // Allow breaking after a trailing annotation, e.g. after a method
3837   // declaration.
3838   if (Left.is(TT_TrailingAnnotation))
3839     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
3840                           tok::less, tok::coloncolon);
3841 
3842   if (Right.is(tok::kw___attribute) ||
3843       (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
3844     return true;
3845 
3846   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
3847     return true;
3848 
3849   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
3850     return true;
3851 
3852   if (Left.is(TT_CtorInitializerColon))
3853     return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
3854   if (Right.is(TT_CtorInitializerColon))
3855     return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
3856   if (Left.is(TT_CtorInitializerComma) &&
3857       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3858     return false;
3859   if (Right.is(TT_CtorInitializerComma) &&
3860       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3861     return true;
3862   if (Left.is(TT_InheritanceComma) &&
3863       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3864     return false;
3865   if (Right.is(TT_InheritanceComma) &&
3866       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3867     return true;
3868   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
3869       (Left.is(tok::less) && Right.is(tok::less)))
3870     return false;
3871   if (Right.is(TT_BinaryOperator) &&
3872       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
3873       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
3874        Right.getPrecedence() != prec::Assignment))
3875     return true;
3876   if (Left.is(TT_ArrayInitializerLSquare))
3877     return true;
3878   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
3879     return true;
3880   if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
3881       !Left.isOneOf(tok::arrowstar, tok::lessless) &&
3882       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
3883       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
3884        Left.getPrecedence() == prec::Assignment))
3885     return true;
3886   if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
3887       (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
3888     return false;
3889 
3890   auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
3891   if (Style.BraceWrapping.BeforeLambdaBody) {
3892     if (isAllmanLambdaBrace(Left))
3893       return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption);
3894     if (isAllmanLambdaBrace(Right))
3895       return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption);
3896   }
3897 
3898   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
3899                       tok::kw_class, tok::kw_struct, tok::comment) ||
3900          Right.isMemberAccess() ||
3901          Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
3902                        tok::colon, tok::l_square, tok::at) ||
3903          (Style.BraceWrapping.BeforeLambdaBody && Right.is(tok::l_brace)) ||
3904          (Left.is(tok::r_paren) &&
3905           Right.isOneOf(tok::identifier, tok::kw_const)) ||
3906          (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
3907          (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
3908 }
3909 
3910 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
3911   llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
3912   const FormatToken *Tok = Line.First;
3913   while (Tok) {
3914     llvm::errs() << " M=" << Tok->MustBreakBefore
3915                  << " C=" << Tok->CanBreakBefore
3916                  << " T=" << getTokenTypeName(Tok->Type)
3917                  << " S=" << Tok->SpacesRequiredBefore
3918                  << " B=" << Tok->BlockParameterCount
3919                  << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
3920                  << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
3921                  << " PPK=" << Tok->PackingKind << " FakeLParens=";
3922     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
3923       llvm::errs() << Tok->FakeLParens[i] << "/";
3924     llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
3925     llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
3926     llvm::errs() << " Text='" << Tok->TokenText << "'\n";
3927     if (!Tok->Next)
3928       assert(Tok == Line.Last);
3929     Tok = Tok->Next;
3930   }
3931   llvm::errs() << "----\n";
3932 }
3933 
3934 } // namespace format
3935 } // namespace clang
3936