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