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