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