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