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