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