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