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