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