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