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