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