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