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