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