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