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