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