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