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