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