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