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 && Contexts.size() == 1) {
530         Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
531         Line.IsMultiVariableDeclStmt = true;
532       }
533       if (Contexts.back().InCtorInitializer)
534         Tok->Type = TT_CtorInitializerComma;
535       if (Contexts.back().IsForEachMacro)
536         Contexts.back().IsExpression = true;
537       break;
538     default:
539       break;
540     }
541     return true;
542   }
543 
544   void parseIncludeDirective() {
545     if (CurrentToken && CurrentToken->is(tok::less)) {
546       next();
547       while (CurrentToken) {
548         if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
549           CurrentToken->Type = TT_ImplicitStringLiteral;
550         next();
551       }
552     }
553   }
554 
555   void parseWarningOrError() {
556     next();
557     // We still want to format the whitespace left of the first token of the
558     // warning or error.
559     next();
560     while (CurrentToken) {
561       CurrentToken->Type = TT_ImplicitStringLiteral;
562       next();
563     }
564   }
565 
566   void parsePragma() {
567     next(); // Consume "pragma".
568     if (CurrentToken && CurrentToken->TokenText == "mark") {
569       next(); // Consume "mark".
570       next(); // Consume first token (so we fix leading whitespace).
571       while (CurrentToken) {
572         CurrentToken->Type = TT_ImplicitStringLiteral;
573         next();
574       }
575     }
576   }
577 
578   LineType parsePreprocessorDirective() {
579     LineType Type = LT_PreprocessorDirective;
580     next();
581     if (!CurrentToken)
582       return Type;
583     if (CurrentToken->Tok.is(tok::numeric_constant)) {
584       CurrentToken->SpacesRequiredBefore = 1;
585       return Type;
586     }
587     // Hashes in the middle of a line can lead to any strange token
588     // sequence.
589     if (!CurrentToken->Tok.getIdentifierInfo())
590       return Type;
591     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
592     case tok::pp_include:
593     case tok::pp_import:
594       next();
595       parseIncludeDirective();
596       Type = LT_ImportStatement;
597       break;
598     case tok::pp_error:
599     case tok::pp_warning:
600       parseWarningOrError();
601       break;
602     case tok::pp_pragma:
603       parsePragma();
604       break;
605     case tok::pp_if:
606     case tok::pp_elif:
607       Contexts.back().IsExpression = true;
608       parseLine();
609       break;
610     default:
611       break;
612     }
613     while (CurrentToken)
614       next();
615     return Type;
616   }
617 
618 public:
619   LineType parseLine() {
620     if (CurrentToken->is(tok::hash)) {
621       return parsePreprocessorDirective();
622     }
623 
624     // Directly allow to 'import <string-literal>' to support protocol buffer
625     // definitions (code.google.com/p/protobuf) or missing "#" (either way we
626     // should not break the line).
627     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
628     if ((Style.Language == FormatStyle::LK_Java &&
629          CurrentToken->is(Keywords.kw_package)) ||
630         (Info && Info->getPPKeywordID() == tok::pp_import &&
631          CurrentToken->Next &&
632          CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
633                                      tok::kw_static))) {
634       next();
635       parseIncludeDirective();
636       return LT_ImportStatement;
637     }
638 
639     // If this line starts and ends in '<' and '>', respectively, it is likely
640     // part of "#define <a/b.h>".
641     if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
642       parseIncludeDirective();
643       return LT_ImportStatement;
644     }
645 
646     bool KeywordVirtualFound = false;
647     bool ImportStatement = false;
648     while (CurrentToken) {
649       if (CurrentToken->is(tok::kw_virtual))
650         KeywordVirtualFound = true;
651       if (IsImportStatement(*CurrentToken))
652         ImportStatement = true;
653       if (!consumeToken())
654         return LT_Invalid;
655     }
656     if (KeywordVirtualFound)
657       return LT_VirtualFunctionDecl;
658     if (ImportStatement)
659       return LT_ImportStatement;
660 
661     if (Line.First->is(TT_ObjCMethodSpecifier)) {
662       if (Contexts.back().FirstObjCSelectorName)
663         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
664             Contexts.back().LongestObjCSelectorName;
665       return LT_ObjCMethodDecl;
666     }
667 
668     return LT_Other;
669   }
670 
671 private:
672   bool IsImportStatement(const FormatToken &Tok) {
673     // FIXME: Closure-library specific stuff should not be hard-coded but be
674     // configurable.
675     return Style.Language == FormatStyle::LK_JavaScript &&
676            Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
677            Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
678                               Tok.Next->Next->TokenText == "require" ||
679                               Tok.Next->Next->TokenText == "provide") &&
680            Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
681   }
682 
683   void resetTokenMetadata(FormatToken *Token) {
684     if (!Token)
685       return;
686 
687     // Reset token type in case we have already looked at it and then
688     // recovered from an error (e.g. failure to find the matching >).
689     if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_FunctionLBrace,
690                                TT_ImplicitStringLiteral, TT_RegexLiteral,
691                                TT_TrailingReturnArrow))
692       CurrentToken->Type = TT_Unknown;
693     CurrentToken->Role.reset();
694     CurrentToken->MatchingParen = nullptr;
695     CurrentToken->FakeLParens.clear();
696     CurrentToken->FakeRParens = 0;
697   }
698 
699   void next() {
700     if (CurrentToken) {
701       CurrentToken->NestingLevel = Contexts.size() - 1;
702       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
703       modifyContext(*CurrentToken);
704       determineTokenType(*CurrentToken);
705       CurrentToken = CurrentToken->Next;
706     }
707 
708     resetTokenMetadata(CurrentToken);
709   }
710 
711   /// \brief A struct to hold information valid in a specific context, e.g.
712   /// a pair of parenthesis.
713   struct Context {
714     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
715             bool IsExpression)
716         : ContextKind(ContextKind), BindingStrength(BindingStrength),
717           LongestObjCSelectorName(0), ColonIsForRangeExpr(false),
718           ColonIsDictLiteral(false), ColonIsObjCMethodExpr(false),
719           FirstObjCSelectorName(nullptr), FirstStartOfName(nullptr),
720           IsExpression(IsExpression), CanBeExpression(true),
721           InTemplateArgument(false), InCtorInitializer(false),
722           CaretFound(false), IsForEachMacro(false) {}
723 
724     tok::TokenKind ContextKind;
725     unsigned BindingStrength;
726     unsigned LongestObjCSelectorName;
727     bool ColonIsForRangeExpr;
728     bool ColonIsDictLiteral;
729     bool ColonIsObjCMethodExpr;
730     FormatToken *FirstObjCSelectorName;
731     FormatToken *FirstStartOfName;
732     bool IsExpression;
733     bool CanBeExpression;
734     bool InTemplateArgument;
735     bool InCtorInitializer;
736     bool CaretFound;
737     bool IsForEachMacro;
738   };
739 
740   /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
741   /// of each instance.
742   struct ScopedContextCreator {
743     AnnotatingParser &P;
744 
745     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
746                          unsigned Increase)
747         : P(P) {
748       P.Contexts.push_back(Context(ContextKind,
749                                    P.Contexts.back().BindingStrength + Increase,
750                                    P.Contexts.back().IsExpression));
751     }
752 
753     ~ScopedContextCreator() { P.Contexts.pop_back(); }
754   };
755 
756   void modifyContext(const FormatToken &Current) {
757     if (Current.getPrecedence() == prec::Assignment &&
758         !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
759         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
760       Contexts.back().IsExpression = true;
761       if (!Line.First->is(TT_UnaryOperator)) {
762         for (FormatToken *Previous = Current.Previous;
763              Previous && !Previous->isOneOf(tok::comma, tok::semi);
764              Previous = Previous->Previous) {
765           if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
766             Previous = Previous->MatchingParen;
767             if (!Previous)
768               break;
769           }
770           if (Previous->opensScope())
771             break;
772           if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
773               Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
774               Previous->Previous && Previous->Previous->isNot(tok::equal))
775             Previous->Type = TT_PointerOrReference;
776         }
777       }
778     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
779       Contexts.back().IsExpression = true;
780     } else if (Current.is(TT_TrailingReturnArrow)) {
781       Contexts.back().IsExpression = false;
782     } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
783                !Line.InPPDirective &&
784                (!Current.Previous ||
785                 Current.Previous->isNot(tok::kw_decltype))) {
786       bool ParametersOfFunctionType =
787           Current.Previous && Current.Previous->is(tok::r_paren) &&
788           Current.Previous->MatchingParen &&
789           Current.Previous->MatchingParen->is(TT_FunctionTypeLParen);
790       bool IsForOrCatch = Current.Previous &&
791                           Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
792       Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
793     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
794       for (FormatToken *Previous = Current.Previous;
795            Previous && Previous->isOneOf(tok::star, tok::amp);
796            Previous = Previous->Previous)
797         Previous->Type = TT_PointerOrReference;
798       if (Line.MustBeDeclaration)
799         Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
800     } else if (Current.Previous &&
801                Current.Previous->is(TT_CtorInitializerColon)) {
802       Contexts.back().IsExpression = true;
803       Contexts.back().InCtorInitializer = true;
804     } else if (Current.is(tok::kw_new)) {
805       Contexts.back().CanBeExpression = false;
806     } else if (Current.is(tok::semi) || Current.is(tok::exclaim)) {
807       // This should be the condition or increment in a for-loop.
808       Contexts.back().IsExpression = true;
809     }
810   }
811 
812   void determineTokenType(FormatToken &Current) {
813     if (!Current.is(TT_Unknown))
814       // The token type is already known.
815       return;
816 
817     // Line.MightBeFunctionDecl can only be true after the parentheses of a
818     // function declaration have been found. In this case, 'Current' is a
819     // trailing token of this declaration and thus cannot be a name.
820     if (Current.is(Keywords.kw_instanceof)) {
821       Current.Type = TT_BinaryOperator;
822     } else if (isStartOfName(Current) &&
823                (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
824       Contexts.back().FirstStartOfName = &Current;
825       Current.Type = TT_StartOfName;
826     } else if (Current.is(tok::kw_auto)) {
827       AutoFound = true;
828     } else if (Current.is(tok::arrow) &&
829                Style.Language == FormatStyle::LK_Java) {
830       Current.Type = TT_LambdaArrow;
831     } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
832                Current.NestingLevel == 0) {
833       Current.Type = TT_TrailingReturnArrow;
834     } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
835       Current.Type =
836           determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
837                                              Contexts.back().IsExpression,
838                                 Contexts.back().InTemplateArgument);
839     } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
840       Current.Type = determinePlusMinusCaretUsage(Current);
841       if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
842         Contexts.back().CaretFound = true;
843     } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
844       Current.Type = determineIncrementUsage(Current);
845     } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
846       Current.Type = TT_UnaryOperator;
847     } else if (Current.is(tok::question)) {
848       Current.Type = TT_ConditionalExpr;
849     } else if (Current.isBinaryOperator() &&
850                (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
851       Current.Type = TT_BinaryOperator;
852     } else if (Current.is(tok::comment)) {
853       Current.Type =
854           Current.TokenText.startswith("/*") ? TT_BlockComment : TT_LineComment;
855     } else if (Current.is(tok::r_paren)) {
856       if (rParenEndsCast(Current))
857         Current.Type = TT_CastRParen;
858     } else if (Current.is(tok::at) && Current.Next) {
859       switch (Current.Next->Tok.getObjCKeywordID()) {
860       case tok::objc_interface:
861       case tok::objc_implementation:
862       case tok::objc_protocol:
863         Current.Type = TT_ObjCDecl;
864         break;
865       case tok::objc_property:
866         Current.Type = TT_ObjCProperty;
867         break;
868       default:
869         break;
870       }
871     } else if (Current.is(tok::period)) {
872       FormatToken *PreviousNoComment = Current.getPreviousNonComment();
873       if (PreviousNoComment &&
874           PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
875         Current.Type = TT_DesignatedInitializerPeriod;
876       else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
877                Current.Previous->isOneOf(TT_JavaAnnotation,
878                                          TT_LeadingJavaAnnotation)) {
879         Current.Type = Current.Previous->Type;
880       }
881     } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
882                Current.Previous &&
883                !Current.Previous->isOneOf(tok::equal, tok::at) &&
884                Line.MightBeFunctionDecl && Contexts.size() == 1) {
885       // Line.MightBeFunctionDecl can only be true after the parentheses of a
886       // function declaration have been found.
887       Current.Type = TT_TrailingAnnotation;
888     } else if ((Style.Language == FormatStyle::LK_Java ||
889                 Style.Language == FormatStyle::LK_JavaScript) &&
890                Current.Previous) {
891       if (Current.Previous->is(tok::at) &&
892           Current.isNot(Keywords.kw_interface)) {
893         const FormatToken &AtToken = *Current.Previous;
894         const FormatToken *Previous = AtToken.getPreviousNonComment();
895         if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
896           Current.Type = TT_LeadingJavaAnnotation;
897         else
898           Current.Type = TT_JavaAnnotation;
899       } else if (Current.Previous->is(tok::period) &&
900                  Current.Previous->isOneOf(TT_JavaAnnotation,
901                                            TT_LeadingJavaAnnotation)) {
902         Current.Type = Current.Previous->Type;
903       }
904     }
905   }
906 
907   /// \brief Take a guess at whether \p Tok starts a name of a function or
908   /// variable declaration.
909   ///
910   /// This is a heuristic based on whether \p Tok is an identifier following
911   /// something that is likely a type.
912   bool isStartOfName(const FormatToken &Tok) {
913     if (Tok.isNot(tok::identifier) || !Tok.Previous)
914       return false;
915 
916     if (Tok.Previous->is(TT_LeadingJavaAnnotation))
917       return false;
918 
919     // Skip "const" as it does not have an influence on whether this is a name.
920     FormatToken *PreviousNotConst = Tok.Previous;
921     while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
922       PreviousNotConst = PreviousNotConst->Previous;
923 
924     if (!PreviousNotConst)
925       return false;
926 
927     bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
928                        PreviousNotConst->Previous &&
929                        PreviousNotConst->Previous->is(tok::hash);
930 
931     if (PreviousNotConst->is(TT_TemplateCloser))
932       return PreviousNotConst && PreviousNotConst->MatchingParen &&
933              PreviousNotConst->MatchingParen->Previous &&
934              PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
935              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
936 
937     if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
938         PreviousNotConst->MatchingParen->Previous &&
939         PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
940       return true;
941 
942     return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
943            PreviousNotConst->is(TT_PointerOrReference) ||
944            PreviousNotConst->isSimpleTypeSpecifier();
945   }
946 
947   /// \brief Determine whether ')' is ending a cast.
948   bool rParenEndsCast(const FormatToken &Tok) {
949     FormatToken *LeftOfParens = nullptr;
950     if (Tok.MatchingParen)
951       LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
952     if (LeftOfParens && LeftOfParens->is(tok::r_paren) &&
953         LeftOfParens->MatchingParen)
954       LeftOfParens = LeftOfParens->MatchingParen->Previous;
955     if (LeftOfParens && LeftOfParens->is(tok::r_square) &&
956         LeftOfParens->MatchingParen &&
957         LeftOfParens->MatchingParen->is(TT_LambdaLSquare))
958       return false;
959     if (Tok.Next) {
960       if (Tok.Next->is(tok::question))
961         return false;
962       if (Style.Language == FormatStyle::LK_JavaScript &&
963           Tok.Next->is(Keywords.kw_in))
964         return false;
965       if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
966         return true;
967     }
968     bool IsCast = false;
969     bool ParensAreEmpty = Tok.Previous == Tok.MatchingParen;
970     bool ParensAreType =
971         !Tok.Previous ||
972         Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
973         Tok.Previous->isSimpleTypeSpecifier();
974     bool ParensCouldEndDecl =
975         Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
976     bool IsSizeOfOrAlignOf =
977         LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
978     if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
979         (Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression))
980       IsCast = true;
981     else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
982              (Tok.Next->Tok.isLiteral() ||
983               Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
984       IsCast = true;
985     // If there is an identifier after the (), it is likely a cast, unless
986     // there is also an identifier before the ().
987     else if (LeftOfParens && Tok.Next &&
988              (LeftOfParens->Tok.getIdentifierInfo() == nullptr ||
989               LeftOfParens->is(tok::kw_return)) &&
990              !LeftOfParens->isOneOf(TT_OverloadedOperator, tok::at,
991                                     TT_TemplateCloser)) {
992       if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
993         IsCast = true;
994       } else {
995         // Use heuristics to recognize c style casting.
996         FormatToken *Prev = Tok.Previous;
997         if (Prev && Prev->isOneOf(tok::amp, tok::star))
998           Prev = Prev->Previous;
999 
1000         if (Prev && Tok.Next && Tok.Next->Next) {
1001           bool NextIsUnary = Tok.Next->isUnaryOperator() ||
1002                              Tok.Next->isOneOf(tok::amp, tok::star);
1003           IsCast =
1004               NextIsUnary && !Tok.Next->is(tok::plus) &&
1005               Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant);
1006         }
1007 
1008         for (; Prev != Tok.MatchingParen; Prev = Prev->Previous) {
1009           if (!Prev || !Prev->isOneOf(tok::kw_const, tok::identifier)) {
1010             IsCast = false;
1011             break;
1012           }
1013         }
1014       }
1015     }
1016     return IsCast && !ParensAreEmpty;
1017   }
1018 
1019   /// \brief Return the type of the given token assuming it is * or &.
1020   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1021                                   bool InTemplateArgument) {
1022     if (Style.Language == FormatStyle::LK_JavaScript)
1023       return TT_BinaryOperator;
1024 
1025     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1026     if (!PrevToken)
1027       return TT_UnaryOperator;
1028 
1029     const FormatToken *NextToken = Tok.getNextNonComment();
1030     if (!NextToken ||
1031         (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1032       return TT_Unknown;
1033 
1034     if (PrevToken->is(tok::coloncolon))
1035       return TT_PointerOrReference;
1036 
1037     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1038                            tok::comma, tok::semi, tok::kw_return, tok::colon,
1039                            tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1040         PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1041                            TT_UnaryOperator, TT_CastRParen))
1042       return TT_UnaryOperator;
1043 
1044     if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1045       return TT_PointerOrReference;
1046     if (NextToken->isOneOf(tok::kw_operator, tok::comma, tok::semi))
1047       return TT_PointerOrReference;
1048 
1049     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1050         PrevToken->MatchingParen->Previous &&
1051         PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1052                                                     tok::kw_decltype))
1053       return TT_PointerOrReference;
1054 
1055     if (PrevToken->Tok.isLiteral() ||
1056         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1057                            tok::kw_false, tok::r_brace) ||
1058         NextToken->Tok.isLiteral() ||
1059         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1060         NextToken->isUnaryOperator() ||
1061         // If we know we're in a template argument, there are no named
1062         // declarations. Thus, having an identifier on the right-hand side
1063         // indicates a binary operator.
1064         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1065       return TT_BinaryOperator;
1066 
1067     // "&&(" is quite unlikely to be two successive unary "&".
1068     if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1069       return TT_BinaryOperator;
1070 
1071     // This catches some cases where evaluation order is used as control flow:
1072     //   aaa && aaa->f();
1073     const FormatToken *NextNextToken = NextToken->getNextNonComment();
1074     if (NextNextToken && NextNextToken->is(tok::arrow))
1075       return TT_BinaryOperator;
1076 
1077     // It is very unlikely that we are going to find a pointer or reference type
1078     // definition on the RHS of an assignment.
1079     if (IsExpression && !Contexts.back().CaretFound)
1080       return TT_BinaryOperator;
1081 
1082     return TT_PointerOrReference;
1083   }
1084 
1085   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1086     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1087     if (!PrevToken || PrevToken->is(TT_CastRParen))
1088       return TT_UnaryOperator;
1089 
1090     // Use heuristics to recognize unary operators.
1091     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1092                            tok::question, tok::colon, tok::kw_return,
1093                            tok::kw_case, tok::at, tok::l_brace))
1094       return TT_UnaryOperator;
1095 
1096     // There can't be two consecutive binary operators.
1097     if (PrevToken->is(TT_BinaryOperator))
1098       return TT_UnaryOperator;
1099 
1100     // Fall back to marking the token as binary operator.
1101     return TT_BinaryOperator;
1102   }
1103 
1104   /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1105   TokenType determineIncrementUsage(const FormatToken &Tok) {
1106     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1107     if (!PrevToken || PrevToken->is(TT_CastRParen))
1108       return TT_UnaryOperator;
1109     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1110       return TT_TrailingUnaryOperator;
1111 
1112     return TT_UnaryOperator;
1113   }
1114 
1115   SmallVector<Context, 8> Contexts;
1116 
1117   const FormatStyle &Style;
1118   AnnotatedLine &Line;
1119   FormatToken *CurrentToken;
1120   bool AutoFound;
1121   const AdditionalKeywords &Keywords;
1122 };
1123 
1124 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1125 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1126 
1127 /// \brief Parses binary expressions by inserting fake parenthesis based on
1128 /// operator precedence.
1129 class ExpressionParser {
1130 public:
1131   ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1132                    AnnotatedLine &Line)
1133       : Style(Style), Keywords(Keywords), Current(Line.First) {}
1134 
1135   /// \brief Parse expressions with the given operatore precedence.
1136   void parse(int Precedence = 0) {
1137     // Skip 'return' and ObjC selector colons as they are not part of a binary
1138     // expression.
1139     while (Current && (Current->is(tok::kw_return) ||
1140                        (Current->is(tok::colon) &&
1141                         Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1142       next();
1143 
1144     if (!Current || Precedence > PrecedenceArrowAndPeriod)
1145       return;
1146 
1147     // Conditional expressions need to be parsed separately for proper nesting.
1148     if (Precedence == prec::Conditional) {
1149       parseConditionalExpr();
1150       return;
1151     }
1152 
1153     // Parse unary operators, which all have a higher precedence than binary
1154     // operators.
1155     if (Precedence == PrecedenceUnaryOperator) {
1156       parseUnaryOperator();
1157       return;
1158     }
1159 
1160     FormatToken *Start = Current;
1161     FormatToken *LatestOperator = nullptr;
1162     unsigned OperatorIndex = 0;
1163 
1164     while (Current) {
1165       // Consume operators with higher precedence.
1166       parse(Precedence + 1);
1167 
1168       int CurrentPrecedence = getCurrentPrecedence();
1169 
1170       if (Current && Current->is(TT_SelectorName) &&
1171           Precedence == CurrentPrecedence) {
1172         if (LatestOperator)
1173           addFakeParenthesis(Start, prec::Level(Precedence));
1174         Start = Current;
1175       }
1176 
1177       // At the end of the line or when an operator with higher precedence is
1178       // found, insert fake parenthesis and return.
1179       if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1180           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1181           (CurrentPrecedence == prec::Conditional &&
1182            Precedence == prec::Assignment && Current->is(tok::colon))) {
1183         break;
1184       }
1185 
1186       // Consume scopes: (), [], <> and {}
1187       if (Current->opensScope()) {
1188         while (Current && !Current->closesScope()) {
1189           next();
1190           parse();
1191         }
1192         next();
1193       } else {
1194         // Operator found.
1195         if (CurrentPrecedence == Precedence) {
1196           LatestOperator = Current;
1197           Current->OperatorIndex = OperatorIndex;
1198           ++OperatorIndex;
1199         }
1200         next(/*SkipPastLeadingComments=*/Precedence > 0);
1201       }
1202     }
1203 
1204     if (LatestOperator && (Current || Precedence > 0)) {
1205       LatestOperator->LastOperator = true;
1206       if (Precedence == PrecedenceArrowAndPeriod) {
1207         // Call expressions don't have a binary operator precedence.
1208         addFakeParenthesis(Start, prec::Unknown);
1209       } else {
1210         addFakeParenthesis(Start, prec::Level(Precedence));
1211       }
1212     }
1213   }
1214 
1215 private:
1216   /// \brief Gets the precedence (+1) of the given token for binary operators
1217   /// and other tokens that we treat like binary operators.
1218   int getCurrentPrecedence() {
1219     if (Current) {
1220       const FormatToken *NextNonComment = Current->getNextNonComment();
1221       if (Current->is(TT_ConditionalExpr))
1222         return prec::Conditional;
1223       else if (NextNonComment && NextNonComment->is(tok::colon) &&
1224                NextNonComment->is(TT_DictLiteral))
1225         return prec::Comma;
1226       else if (Current->is(TT_LambdaArrow))
1227         return prec::Comma;
1228       else if (Current->isOneOf(tok::semi, TT_InlineASMColon,
1229                                 TT_SelectorName) ||
1230                (Current->is(tok::comment) && NextNonComment &&
1231                 NextNonComment->is(TT_SelectorName)))
1232         return 0;
1233       else if (Current->is(TT_RangeBasedForLoopColon))
1234         return prec::Comma;
1235       else if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1236         return Current->getPrecedence();
1237       else if (Current->isOneOf(tok::period, tok::arrow))
1238         return PrecedenceArrowAndPeriod;
1239       else if (Style.Language == FormatStyle::LK_Java &&
1240                Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1241                                 Keywords.kw_throws))
1242         return 0;
1243     }
1244     return -1;
1245   }
1246 
1247   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1248     Start->FakeLParens.push_back(Precedence);
1249     if (Precedence > prec::Unknown)
1250       Start->StartsBinaryExpression = true;
1251     if (Current) {
1252       FormatToken *Previous = Current->Previous;
1253       while (Previous->is(tok::comment) && Previous->Previous)
1254         Previous = Previous->Previous;
1255       ++Previous->FakeRParens;
1256       if (Precedence > prec::Unknown)
1257         Previous->EndsBinaryExpression = true;
1258     }
1259   }
1260 
1261   /// \brief Parse unary operator expressions and surround them with fake
1262   /// parentheses if appropriate.
1263   void parseUnaryOperator() {
1264     if (!Current || Current->isNot(TT_UnaryOperator)) {
1265       parse(PrecedenceArrowAndPeriod);
1266       return;
1267     }
1268 
1269     FormatToken *Start = Current;
1270     next();
1271     parseUnaryOperator();
1272 
1273     // The actual precedence doesn't matter.
1274     addFakeParenthesis(Start, prec::Unknown);
1275   }
1276 
1277   void parseConditionalExpr() {
1278     while (Current && Current->isTrailingComment()) {
1279       next();
1280     }
1281     FormatToken *Start = Current;
1282     parse(prec::LogicalOr);
1283     if (!Current || !Current->is(tok::question))
1284       return;
1285     next();
1286     parse(prec::Assignment);
1287     if (!Current || Current->isNot(TT_ConditionalExpr))
1288       return;
1289     next();
1290     parse(prec::Assignment);
1291     addFakeParenthesis(Start, prec::Conditional);
1292   }
1293 
1294   void next(bool SkipPastLeadingComments = true) {
1295     if (Current)
1296       Current = Current->Next;
1297     while (Current &&
1298            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1299            Current->isTrailingComment())
1300       Current = Current->Next;
1301   }
1302 
1303   const FormatStyle &Style;
1304   const AdditionalKeywords &Keywords;
1305   FormatToken *Current;
1306 };
1307 
1308 } // end anonymous namespace
1309 
1310 void TokenAnnotator::setCommentLineLevels(
1311     SmallVectorImpl<AnnotatedLine *> &Lines) {
1312   const AnnotatedLine *NextNonCommentLine = nullptr;
1313   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1314                                                           E = Lines.rend();
1315        I != E; ++I) {
1316     if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1317         (*I)->First->Next == nullptr)
1318       (*I)->Level = NextNonCommentLine->Level;
1319     else
1320       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1321 
1322     setCommentLineLevels((*I)->Children);
1323   }
1324 }
1325 
1326 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1327   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1328                                                   E = Line.Children.end();
1329        I != E; ++I) {
1330     annotate(**I);
1331   }
1332   AnnotatingParser Parser(Style, Line, Keywords);
1333   Line.Type = Parser.parseLine();
1334   if (Line.Type == LT_Invalid)
1335     return;
1336 
1337   ExpressionParser ExprParser(Style, Keywords, Line);
1338   ExprParser.parse();
1339 
1340   if (Line.First->is(TT_ObjCMethodSpecifier))
1341     Line.Type = LT_ObjCMethodDecl;
1342   else if (Line.First->is(TT_ObjCDecl))
1343     Line.Type = LT_ObjCDecl;
1344   else if (Line.First->is(TT_ObjCProperty))
1345     Line.Type = LT_ObjCProperty;
1346 
1347   Line.First->SpacesRequiredBefore = 1;
1348   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1349 }
1350 
1351 // This function heuristically determines whether 'Current' starts the name of a
1352 // function declaration.
1353 static bool isFunctionDeclarationName(const FormatToken &Current) {
1354   if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1355     return false;
1356   const FormatToken *Next = Current.Next;
1357   for (; Next; Next = Next->Next) {
1358     if (Next->is(TT_TemplateOpener)) {
1359       Next = Next->MatchingParen;
1360     } else if (Next->is(tok::coloncolon)) {
1361       Next = Next->Next;
1362       if (!Next || !Next->is(tok::identifier))
1363         return false;
1364     } else if (Next->is(tok::l_paren)) {
1365       break;
1366     } else {
1367       return false;
1368     }
1369   }
1370   if (!Next)
1371     return false;
1372   assert(Next->is(tok::l_paren));
1373   if (Next->Next == Next->MatchingParen)
1374     return true;
1375   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1376        Tok = Tok->Next) {
1377     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1378         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1379       return true;
1380     if (Tok->isOneOf(tok::l_brace, tok::string_literal) || Tok->Tok.isLiteral())
1381       return false;
1382   }
1383   return false;
1384 }
1385 
1386 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1387   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1388                                                   E = Line.Children.end();
1389        I != E; ++I) {
1390     calculateFormattingInformation(**I);
1391   }
1392 
1393   Line.First->TotalLength =
1394       Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1395   if (!Line.First->Next)
1396     return;
1397   FormatToken *Current = Line.First->Next;
1398   bool InFunctionDecl = Line.MightBeFunctionDecl;
1399   while (Current) {
1400     if (isFunctionDeclarationName(*Current))
1401       Current->Type = TT_FunctionDeclarationName;
1402     if (Current->is(TT_LineComment)) {
1403       if (Current->Previous->BlockKind == BK_BracedInit &&
1404           Current->Previous->opensScope())
1405         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1406       else
1407         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1408 
1409       // If we find a trailing comment, iterate backwards to determine whether
1410       // it seems to relate to a specific parameter. If so, break before that
1411       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1412       // to the previous line in:
1413       //   SomeFunction(a,
1414       //                b, // comment
1415       //                c);
1416       if (!Current->HasUnescapedNewline) {
1417         for (FormatToken *Parameter = Current->Previous; Parameter;
1418              Parameter = Parameter->Previous) {
1419           if (Parameter->isOneOf(tok::comment, tok::r_brace))
1420             break;
1421           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1422             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1423                 Parameter->HasUnescapedNewline)
1424               Parameter->MustBreakBefore = true;
1425             break;
1426           }
1427         }
1428       }
1429     } else if (Current->SpacesRequiredBefore == 0 &&
1430                spaceRequiredBefore(Line, *Current)) {
1431       Current->SpacesRequiredBefore = 1;
1432     }
1433 
1434     Current->MustBreakBefore =
1435         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1436 
1437     if (Style.AlwaysBreakAfterDefinitionReturnType && InFunctionDecl &&
1438         Current->is(TT_FunctionDeclarationName) &&
1439         !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
1440       // FIXME: Line.Last points to other characters than tok::semi
1441       // and tok::lbrace.
1442       Current->MustBreakBefore = true;
1443 
1444     Current->CanBreakBefore =
1445         Current->MustBreakBefore || canBreakBefore(Line, *Current);
1446     unsigned ChildSize = 0;
1447     if (Current->Previous->Children.size() == 1) {
1448       FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1449       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1450                                                   : LastOfChild.TotalLength + 1;
1451     }
1452     const FormatToken *Prev = Current->Previous;
1453     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1454         (Prev->Children.size() == 1 &&
1455          Prev->Children[0]->First->MustBreakBefore) ||
1456         Current->IsMultiline)
1457       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1458     else
1459       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1460                              ChildSize + Current->SpacesRequiredBefore;
1461 
1462     if (Current->is(TT_CtorInitializerColon))
1463       InFunctionDecl = false;
1464 
1465     // FIXME: Only calculate this if CanBreakBefore is true once static
1466     // initializers etc. are sorted out.
1467     // FIXME: Move magic numbers to a better place.
1468     Current->SplitPenalty = 20 * Current->BindingStrength +
1469                             splitPenalty(Line, *Current, InFunctionDecl);
1470 
1471     Current = Current->Next;
1472   }
1473 
1474   calculateUnbreakableTailLengths(Line);
1475   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1476     if (Current->Role)
1477       Current->Role->precomputeFormattingInfos(Current);
1478   }
1479 
1480   DEBUG({ printDebugInfo(Line); });
1481 }
1482 
1483 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1484   unsigned UnbreakableTailLength = 0;
1485   FormatToken *Current = Line.Last;
1486   while (Current) {
1487     Current->UnbreakableTailLength = UnbreakableTailLength;
1488     if (Current->CanBreakBefore ||
1489         Current->isOneOf(tok::comment, tok::string_literal)) {
1490       UnbreakableTailLength = 0;
1491     } else {
1492       UnbreakableTailLength +=
1493           Current->ColumnWidth + Current->SpacesRequiredBefore;
1494     }
1495     Current = Current->Previous;
1496   }
1497 }
1498 
1499 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1500                                       const FormatToken &Tok,
1501                                       bool InFunctionDecl) {
1502   const FormatToken &Left = *Tok.Previous;
1503   const FormatToken &Right = Tok;
1504 
1505   if (Left.is(tok::semi))
1506     return 0;
1507 
1508   if (Style.Language == FormatStyle::LK_Java) {
1509     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1510       return 1;
1511     if (Right.is(Keywords.kw_implements))
1512       return 2;
1513     if (Left.is(tok::comma) && Left.NestingLevel == 0)
1514       return 3;
1515   } else if (Style.Language == FormatStyle::LK_JavaScript) {
1516     if (Right.is(Keywords.kw_function))
1517       return 100;
1518   }
1519 
1520   if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1521                               Right.Next->is(TT_DictLiteral)))
1522     return 1;
1523   if (Right.is(tok::l_square)) {
1524     if (Style.Language == FormatStyle::LK_Proto)
1525       return 1;
1526     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare))
1527       return 500;
1528   }
1529 
1530   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1531       Right.is(tok::kw_operator)) {
1532     if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1533       return 3;
1534     if (Left.is(TT_StartOfName))
1535       return 20;
1536     if (InFunctionDecl && Right.NestingLevel == 0)
1537       return Style.PenaltyReturnTypeOnItsOwnLine;
1538     return 200;
1539   }
1540   if (Right.is(TT_PointerOrReference))
1541     return 190;
1542   if (Right.is(TT_TrailingReturnArrow))
1543     return 110;
1544   if (Left.is(tok::equal) && Right.is(tok::l_brace))
1545     return 150;
1546   if (Left.is(TT_CastRParen))
1547     return 100;
1548   if (Left.is(tok::coloncolon) ||
1549       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1550     return 500;
1551   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1552     return 5000;
1553 
1554   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1555     return 2;
1556 
1557   if (Right.isMemberAccess()) {
1558     if (Left.is(tok::r_paren) && Left.MatchingParen &&
1559         Left.MatchingParen->ParameterCount > 0)
1560       return 20; // Should be smaller than breaking at a nested comma.
1561     return 150;
1562   }
1563 
1564   if (Right.is(TT_TrailingAnnotation) &&
1565       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1566     // Moving trailing annotations to the next line is fine for ObjC method
1567     // declarations.
1568     if (Line.First->is(TT_ObjCMethodSpecifier))
1569 
1570       return 10;
1571     // Generally, breaking before a trailing annotation is bad unless it is
1572     // function-like. It seems to be especially preferable to keep standard
1573     // annotations (i.e. "const", "final" and "override") on the same line.
1574     // Use a slightly higher penalty after ")" so that annotations like
1575     // "const override" are kept together.
1576     bool is_short_annotation = Right.TokenText.size() < 10;
1577     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1578   }
1579 
1580   // In for-loops, prefer breaking at ',' and ';'.
1581   if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
1582     return 4;
1583 
1584   // In Objective-C method expressions, prefer breaking before "param:" over
1585   // breaking after it.
1586   if (Right.is(TT_SelectorName))
1587     return 0;
1588   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1589     return Line.MightBeFunctionDecl ? 50 : 500;
1590 
1591   if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
1592     return 100;
1593   if (Left.is(tok::l_paren) && Left.Previous && Left.Previous->is(tok::kw_if))
1594     return 1000;
1595   if (Left.is(tok::equal) && InFunctionDecl)
1596     return 110;
1597   if (Right.is(tok::r_brace))
1598     return 1;
1599   if (Left.is(TT_TemplateOpener))
1600     return 100;
1601   if (Left.opensScope()) {
1602     if (!Style.AlignAfterOpenBracket)
1603       return 0;
1604     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1605                                    : 19;
1606   }
1607   if (Left.is(TT_JavaAnnotation))
1608     return 50;
1609 
1610   if (Right.is(tok::lessless)) {
1611     if (Left.is(tok::string_literal)) {
1612       StringRef Content = Left.TokenText;
1613       if (Content.startswith("\""))
1614         Content = Content.drop_front(1);
1615       if (Content.endswith("\""))
1616         Content = Content.drop_back(1);
1617       Content = Content.trim();
1618       if (Content.size() > 1 &&
1619           (Content.back() == ':' || Content.back() == '='))
1620         return 25;
1621     }
1622     return 1; // Breaking at a << is really cheap.
1623   }
1624   if (Left.is(TT_ConditionalExpr))
1625     return prec::Conditional;
1626   prec::Level Level = Left.getPrecedence();
1627 
1628   if (Level != prec::Unknown)
1629     return Level;
1630 
1631   return 3;
1632 }
1633 
1634 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1635                                           const FormatToken &Left,
1636                                           const FormatToken &Right) {
1637   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1638     return true;
1639   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1640       Left.Tok.getObjCKeywordID() == tok::objc_property)
1641     return true;
1642   if (Right.is(tok::hashhash))
1643     return Left.is(tok::hash);
1644   if (Left.isOneOf(tok::hashhash, tok::hash))
1645     return Right.is(tok::hash);
1646   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1647     return Style.SpaceInEmptyParentheses;
1648   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1649     return (Right.is(TT_CastRParen) ||
1650             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1651                ? Style.SpacesInCStyleCastParentheses
1652                : Style.SpacesInParentheses;
1653   if (Right.isOneOf(tok::semi, tok::comma))
1654     return false;
1655   if (Right.is(tok::less) &&
1656       (Left.isOneOf(tok::kw_template, tok::r_paren) ||
1657        (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1658     return true;
1659   if (Left.isOneOf(tok::exclaim, tok::tilde))
1660     return false;
1661   if (Left.is(tok::at) &&
1662       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1663                     tok::numeric_constant, tok::l_paren, tok::l_brace,
1664                     tok::kw_true, tok::kw_false))
1665     return false;
1666   if (Left.is(tok::coloncolon))
1667     return false;
1668   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1669     return false;
1670   if (Right.is(tok::ellipsis))
1671     return Left.Tok.isLiteral();
1672   if (Left.is(tok::l_square) && Right.is(tok::amp))
1673     return false;
1674   if (Right.is(TT_PointerOrReference))
1675     return !(Left.is(tok::r_paren) && Left.MatchingParen &&
1676              (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1677               (Left.MatchingParen->Previous &&
1678                Left.MatchingParen->Previous->is(
1679                    TT_FunctionDeclarationName)))) &&
1680            (Left.Tok.isLiteral() ||
1681             (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1682              (Style.PointerAlignment != FormatStyle::PAS_Left ||
1683               Line.IsMultiVariableDeclStmt)));
1684   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1685       (!Left.is(TT_PointerOrReference) ||
1686        (Style.PointerAlignment != FormatStyle::PAS_Right &&
1687         !Line.IsMultiVariableDeclStmt)))
1688     return true;
1689   if (Left.is(TT_PointerOrReference))
1690     return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
1691            (!Right.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1692             (Style.PointerAlignment != FormatStyle::PAS_Right &&
1693              !Line.IsMultiVariableDeclStmt) &&
1694             Left.Previous &&
1695             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1696   if (Right.is(tok::star) && Left.is(tok::l_paren))
1697     return false;
1698   if (Left.is(tok::l_square))
1699     return (Left.is(TT_ArrayInitializerLSquare) &&
1700             Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1701            (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1702             Right.isNot(tok::r_square));
1703   if (Right.is(tok::r_square))
1704     return Right.MatchingParen &&
1705            ((Style.SpacesInContainerLiterals &&
1706              Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1707             (Style.SpacesInSquareBrackets &&
1708              Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1709   if (Right.is(tok::l_square) &&
1710       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1711       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1712     return false;
1713   if (Left.is(tok::colon))
1714     return !Left.is(TT_ObjCMethodExpr);
1715   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1716     return !Left.Children.empty(); // No spaces in "{}".
1717   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1718       (Right.is(tok::r_brace) && Right.MatchingParen &&
1719        Right.MatchingParen->BlockKind != BK_Block))
1720     return !Style.Cpp11BracedListStyle;
1721   if (Left.is(TT_BlockComment))
1722     return !Left.TokenText.endswith("=*/");
1723   if (Right.is(tok::l_paren)) {
1724     if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1725       return true;
1726     return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1727            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1728             (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
1729                           tok::kw_switch, tok::kw_case) ||
1730              (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1731                            tok::kw_new, tok::kw_delete) &&
1732               (!Left.Previous || Left.Previous->isNot(tok::period))) ||
1733              Left.IsForEachMacro)) ||
1734            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1735             (Left.is(tok::identifier) || Left.isFunctionLikeKeyword()) &&
1736             Line.Type != LT_PreprocessorDirective);
1737   }
1738   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1739     return false;
1740   if (Right.is(TT_UnaryOperator))
1741     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1742            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1743   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1744                     tok::r_paren) ||
1745        Left.isSimpleTypeSpecifier()) &&
1746       Right.is(tok::l_brace) && Right.getNextNonComment() &&
1747       Right.BlockKind != BK_Block)
1748     return false;
1749   if (Left.is(tok::period) || Right.is(tok::period))
1750     return false;
1751   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1752     return false;
1753   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1754       Left.MatchingParen->Previous &&
1755       Left.MatchingParen->Previous->is(tok::period))
1756     // A.<B>DoSomething();
1757     return false;
1758   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1759     return false;
1760   return true;
1761 }
1762 
1763 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1764                                          const FormatToken &Right) {
1765   const FormatToken &Left = *Right.Previous;
1766   if (Style.Language == FormatStyle::LK_Proto) {
1767     if (Right.is(tok::period) &&
1768         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
1769                      Keywords.kw_repeated))
1770       return true;
1771     if (Right.is(tok::l_paren) &&
1772         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
1773       return true;
1774   } else if (Style.Language == FormatStyle::LK_JavaScript) {
1775     if (Left.is(Keywords.kw_var))
1776       return true;
1777     if (Right.is(TT_JsTypeColon))
1778       return false;
1779     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
1780         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
1781       return false;
1782     if (Left.is(TT_TemplateCloser) &&
1783         !Right.isOneOf(tok::l_brace, tok::comma, tok::l_square,
1784                        Keywords.kw_implements, Keywords.kw_extends))
1785       // Type assertions ('<type>expr') are not followed by whitespace. Other
1786       // locations that should have whitespace following are identified by the
1787       // above set of follower tokens.
1788       return false;
1789   } else if (Style.Language == FormatStyle::LK_Java) {
1790     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
1791       return true;
1792     if (Left.is(TT_LambdaArrow) || Right.is(TT_LambdaArrow))
1793       return true;
1794     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
1795       return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
1796     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
1797                       tok::kw_protected) ||
1798          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
1799                       Keywords.kw_native)) &&
1800         Right.is(TT_TemplateOpener))
1801       return true;
1802   }
1803   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1804     return true; // Never ever merge two identifiers.
1805   if (Left.is(TT_ImplicitStringLiteral))
1806     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
1807   if (Line.Type == LT_ObjCMethodDecl) {
1808     if (Left.is(TT_ObjCMethodSpecifier))
1809       return true;
1810     if (Left.is(tok::r_paren) && Right.is(tok::identifier))
1811       // Don't space between ')' and <id>
1812       return false;
1813   }
1814   if (Line.Type == LT_ObjCProperty &&
1815       (Right.is(tok::equal) || Left.is(tok::equal)))
1816     return false;
1817 
1818   if (Right.is(TT_TrailingReturnArrow) || Left.is(TT_TrailingReturnArrow))
1819     return true;
1820   if (Left.is(tok::comma))
1821     return true;
1822   if (Right.is(tok::comma))
1823     return false;
1824   if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
1825     return true;
1826   if (Left.is(tok::kw_operator))
1827     return Right.is(tok::coloncolon);
1828   if (Right.is(TT_OverloadedOperatorLParen))
1829     return false;
1830   if (Right.is(tok::colon))
1831     return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
1832            Right.getNextNonComment() && Right.isNot(TT_ObjCMethodExpr) &&
1833            !Left.is(tok::question) &&
1834            !(Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) &&
1835            (Right.isNot(TT_DictLiteral) || Style.SpacesInContainerLiterals);
1836   if (Left.is(TT_UnaryOperator))
1837     return Right.is(TT_BinaryOperator);
1838   if (Left.is(TT_CastRParen))
1839     return Style.SpaceAfterCStyleCast || Right.is(TT_BinaryOperator);
1840   if (Left.is(tok::greater) && Right.is(tok::greater)) {
1841     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
1842            (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
1843   }
1844   if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
1845       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
1846     return false;
1847   if (!Style.SpaceBeforeAssignmentOperators &&
1848       Right.getPrecedence() == prec::Assignment)
1849     return false;
1850   if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
1851     return (Left.is(TT_TemplateOpener) &&
1852             Style.Standard == FormatStyle::LS_Cpp03) ||
1853            !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
1854              Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
1855   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
1856     return Style.SpacesInAngles;
1857   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
1858       Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr))
1859     return true;
1860   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
1861       Right.isNot(TT_FunctionTypeLParen))
1862     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
1863   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
1864       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
1865     return false;
1866   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
1867       Line.First->is(tok::hash))
1868     return true;
1869   if (Right.is(TT_TrailingUnaryOperator))
1870     return false;
1871   if (Left.is(TT_RegexLiteral))
1872     return false;
1873   return spaceRequiredBetween(Line, Left, Right);
1874 }
1875 
1876 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
1877 static bool isAllmanBrace(const FormatToken &Tok) {
1878   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
1879          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
1880 }
1881 
1882 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
1883                                      const FormatToken &Right) {
1884   const FormatToken &Left = *Right.Previous;
1885   if (Right.NewlinesBefore > 1)
1886     return true;
1887 
1888   // If the last token before a '}' is a comma or a trailing comment, the
1889   // intention is to insert a line break after it in order to make shuffling
1890   // around entries easier.
1891   const FormatToken *BeforeClosingBrace = nullptr;
1892   if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1893       Left.BlockKind != BK_Block && Left.MatchingParen)
1894     BeforeClosingBrace = Left.MatchingParen->Previous;
1895   else if (Right.MatchingParen &&
1896            Right.MatchingParen->isOneOf(tok::l_brace,
1897                                         TT_ArrayInitializerLSquare))
1898     BeforeClosingBrace = &Left;
1899   if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
1900                              BeforeClosingBrace->isTrailingComment()))
1901     return true;
1902 
1903   if (Right.is(tok::comment))
1904     return Left.BlockKind != BK_BracedInit &&
1905            Left.isNot(TT_CtorInitializerColon) &&
1906            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
1907   if (Right.Previous->isTrailingComment() ||
1908       (Right.isStringLiteral() && Right.Previous->isStringLiteral()))
1909     return true;
1910   if (Right.Previous->IsUnterminatedLiteral)
1911     return true;
1912   if (Right.is(tok::lessless) && Right.Next &&
1913       Right.Previous->is(tok::string_literal) &&
1914       Right.Next->is(tok::string_literal))
1915     return true;
1916   if (Right.Previous->ClosesTemplateDeclaration &&
1917       Right.Previous->MatchingParen &&
1918       Right.Previous->MatchingParen->NestingLevel == 0 &&
1919       Style.AlwaysBreakTemplateDeclarations)
1920     return true;
1921   if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
1922       Style.BreakConstructorInitializersBeforeComma &&
1923       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
1924     return true;
1925   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
1926     // Raw string literals are special wrt. line breaks. The author has made a
1927     // deliberate choice and might have aligned the contents of the string
1928     // literal accordingly. Thus, we try keep existing line breaks.
1929     return Right.NewlinesBefore > 0;
1930   if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
1931       Style.Language == FormatStyle::LK_Proto)
1932     // Don't put enums onto single lines in protocol buffers.
1933     return true;
1934   if (Style.Language == FormatStyle::LK_JavaScript && Right.is(tok::r_brace) &&
1935       Left.is(tok::l_brace) && !Left.Children.empty())
1936     // Support AllowShortFunctionsOnASingleLine for JavaScript.
1937     return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
1938            (Left.NestingLevel == 0 && Line.Level == 0 &&
1939             Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline);
1940   if (isAllmanBrace(Left) || isAllmanBrace(Right))
1941     return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1942            Style.BreakBeforeBraces == FormatStyle::BS_GNU;
1943   if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
1944       Right.is(TT_SelectorName))
1945     return true;
1946   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
1947     return true;
1948 
1949   if ((Style.Language == FormatStyle::LK_Java ||
1950        Style.Language == FormatStyle::LK_JavaScript) &&
1951       Left.is(TT_LeadingJavaAnnotation) &&
1952       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
1953       Line.Last->is(tok::l_brace))
1954     return true;
1955 
1956   if (Style.Language == FormatStyle::LK_JavaScript) {
1957     // FIXME: This might apply to other languages and token kinds.
1958     if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
1959         Left.Previous->is(tok::char_constant))
1960       return true;
1961     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) &&
1962         Left.NestingLevel == 0 && Left.Previous &&
1963         Left.Previous->is(tok::equal) &&
1964         Line.First->isOneOf(tok::identifier, Keywords.kw_import,
1965                             tok::kw_export) &&
1966         // kw_var is a pseudo-token that's a tok::identifier, so matches above.
1967         !Line.First->is(Keywords.kw_var))
1968       // Enum style object literal.
1969       return true;
1970   } else if (Style.Language == FormatStyle::LK_Java) {
1971     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
1972         Right.Next->is(tok::string_literal))
1973       return true;
1974   }
1975 
1976   return false;
1977 }
1978 
1979 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
1980                                     const FormatToken &Right) {
1981   const FormatToken &Left = *Right.Previous;
1982 
1983   if (Style.Language == FormatStyle::LK_Java) {
1984     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
1985                      Keywords.kw_implements))
1986       return false;
1987     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
1988                       Keywords.kw_implements))
1989       return true;
1990   }
1991 
1992   if (Left.is(tok::at))
1993     return false;
1994   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
1995     return false;
1996   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
1997     return !Right.is(tok::l_paren);
1998   if (Right.is(TT_PointerOrReference))
1999     return Line.IsMultiVariableDeclStmt ||
2000            (Style.PointerAlignment == FormatStyle::PAS_Right &&
2001             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2002   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2003       Right.is(tok::kw_operator))
2004     return true;
2005   if (Left.is(TT_PointerOrReference))
2006     return false;
2007   if (Right.isTrailingComment())
2008     // We rely on MustBreakBefore being set correctly here as we should not
2009     // change the "binding" behavior of a comment.
2010     // The first comment in a braced lists is always interpreted as belonging to
2011     // the first list element. Otherwise, it should be placed outside of the
2012     // list.
2013     return Left.BlockKind == BK_BracedInit;
2014   if (Left.is(tok::question) && Right.is(tok::colon))
2015     return false;
2016   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2017     return Style.BreakBeforeTernaryOperators;
2018   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2019     return !Style.BreakBeforeTernaryOperators;
2020   if (Right.is(TT_InheritanceColon))
2021     return true;
2022   if (Right.is(tok::colon) &&
2023       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2024     return false;
2025   if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2026     return true;
2027   if (Right.is(TT_SelectorName))
2028     return true;
2029   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2030     return true;
2031   if (Left.ClosesTemplateDeclaration)
2032     return true;
2033   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2034                     TT_OverloadedOperator))
2035     return false;
2036   if (Left.is(TT_RangeBasedForLoopColon))
2037     return true;
2038   if (Right.is(TT_RangeBasedForLoopColon))
2039     return false;
2040   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2041       Left.is(tok::kw_operator))
2042     return false;
2043   if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
2044     return false;
2045   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2046     return false;
2047   if (Left.is(tok::l_paren) && Left.Previous &&
2048       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2049     return false;
2050   if (Right.is(TT_ImplicitStringLiteral))
2051     return false;
2052 
2053   if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2054     return false;
2055 
2056   // We only break before r_brace if there was a corresponding break before
2057   // the l_brace, which is tracked by BreakBeforeClosingBrace.
2058   if (Right.is(tok::r_brace))
2059     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2060 
2061   // Allow breaking after a trailing annotation, e.g. after a method
2062   // declaration.
2063   if (Left.is(TT_TrailingAnnotation))
2064     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2065                           tok::less, tok::coloncolon);
2066 
2067   if (Right.is(tok::kw___attribute))
2068     return true;
2069 
2070   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2071     return true;
2072 
2073   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2074     return true;
2075 
2076   if (Left.is(TT_CtorInitializerComma) &&
2077       Style.BreakConstructorInitializersBeforeComma)
2078     return false;
2079   if (Right.is(TT_CtorInitializerComma) &&
2080       Style.BreakConstructorInitializersBeforeComma)
2081     return true;
2082   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2083       (Left.is(tok::less) && Right.is(tok::less)))
2084     return false;
2085   if (Right.is(TT_BinaryOperator) &&
2086       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2087       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2088        Right.getPrecedence() != prec::Assignment))
2089     return true;
2090   if (Left.is(TT_ArrayInitializerLSquare))
2091     return true;
2092   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2093     return true;
2094   if (Left.isBinaryOperator() && !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2095       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2096       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2097        Left.getPrecedence() == prec::Assignment))
2098     return true;
2099   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2100                       tok::kw_class, tok::kw_struct) ||
2101          Right.isMemberAccess() || Right.is(TT_TrailingReturnArrow) ||
2102          Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at) ||
2103          (Left.is(tok::r_paren) &&
2104           Right.isOneOf(tok::identifier, tok::kw_const)) ||
2105          (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2106 }
2107 
2108 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2109   llvm::errs() << "AnnotatedTokens:\n";
2110   const FormatToken *Tok = Line.First;
2111   while (Tok) {
2112     llvm::errs() << " M=" << Tok->MustBreakBefore
2113                  << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
2114                  << " S=" << Tok->SpacesRequiredBefore
2115                  << " B=" << Tok->BlockParameterCount
2116                  << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2117                  << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2118                  << " FakeLParens=";
2119     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2120       llvm::errs() << Tok->FakeLParens[i] << "/";
2121     llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2122     if (!Tok->Next)
2123       assert(Tok == Line.Last);
2124     Tok = Tok->Next;
2125   }
2126   llvm::errs() << "----\n";
2127 }
2128 
2129 } // namespace format
2130 } // namespace clang
2131