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