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 /// \brief A parser that gathers additional information about tokens.
24 ///
25 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
26 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
27 /// into template parameter lists.
28 class AnnotatingParser {
29 public:
30   AnnotatingParser(AnnotatedLine &Line, IdentifierInfo &Ident_in)
31       : Line(Line), CurrentToken(Line.First), KeywordVirtualFound(false),
32         NameFound(false), Ident_in(Ident_in) {
33     Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/ false));
34   }
35 
36 private:
37   bool parseAngle() {
38     if (CurrentToken == NULL)
39       return false;
40     ScopedContextCreator ContextCreator(*this, tok::less, 10);
41     FormatToken *Left = CurrentToken->Previous;
42     Contexts.back().IsExpression = false;
43     while (CurrentToken != NULL) {
44       if (CurrentToken->is(tok::greater)) {
45         Left->MatchingParen = CurrentToken;
46         CurrentToken->MatchingParen = Left;
47         CurrentToken->Type = TT_TemplateCloser;
48         next();
49         return true;
50       }
51       if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace,
52                                 tok::question, tok::colon))
53         return false;
54       // If a && or || is found and interpreted as a binary operator, this set
55       // of angles is likely part of something like "a < b && c > d". If the
56       // angles are inside an expression, the ||/&& might also be a binary
57       // operator that was misinterpreted because we are parsing template
58       // parameters.
59       // FIXME: This is getting out of hand, write a decent parser.
60       if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
61           (CurrentToken->Previous->Type == TT_BinaryOperator ||
62            Contexts[Contexts.size() - 2].IsExpression) &&
63           Line.First->isNot(tok::kw_template))
64         return false;
65       updateParameterCount(Left, CurrentToken);
66       if (!consumeToken())
67         return false;
68     }
69     return false;
70   }
71 
72   bool parseParens(bool LookForDecls = false) {
73     if (CurrentToken == NULL)
74       return false;
75     ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
76 
77     // FIXME: This is a bit of a hack. Do better.
78     Contexts.back().ColonIsForRangeExpr =
79         Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
80 
81     bool StartsObjCMethodExpr = false;
82     FormatToken *Left = CurrentToken->Previous;
83     if (CurrentToken->is(tok::caret)) {
84       // ^( starts a block.
85       Left->Type = TT_ObjCBlockLParen;
86     } else if (FormatToken *MaybeSel = Left->Previous) {
87       // @selector( starts a selector.
88       if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
89           MaybeSel->Previous->is(tok::at)) {
90         StartsObjCMethodExpr = true;
91       }
92     }
93 
94     if (StartsObjCMethodExpr) {
95       Contexts.back().ColonIsObjCMethodExpr = true;
96       Left->Type = TT_ObjCMethodExpr;
97     }
98 
99     bool MightBeFunctionType = CurrentToken->is(tok::star);
100     while (CurrentToken != NULL) {
101       // LookForDecls is set when "if (" has been seen. Check for
102       // 'identifier' '*' 'identifier' followed by not '=' -- this
103       // '*' has to be a binary operator but determineStarAmpUsage() will
104       // categorize it as an unary operator, so set the right type here.
105       if (LookForDecls && CurrentToken->Next) {
106         FormatToken *Prev = CurrentToken->getPreviousNoneComment();
107         if (Prev) {
108           FormatToken *PrevPrev = Prev->getPreviousNoneComment();
109           FormatToken *Next = CurrentToken->Next;
110           if (PrevPrev && PrevPrev->is(tok::identifier) &&
111               Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
112               CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
113             Prev->Type = TT_BinaryOperator;
114             LookForDecls = false;
115           }
116         }
117       }
118 
119       if (CurrentToken->is(tok::r_paren)) {
120         if (MightBeFunctionType && CurrentToken->Next &&
121             CurrentToken->Next->isOneOf(tok::l_paren, tok::l_square))
122           Left->Type = TT_FunctionTypeLParen;
123         Left->MatchingParen = CurrentToken;
124         CurrentToken->MatchingParen = Left;
125 
126         if (StartsObjCMethodExpr) {
127           CurrentToken->Type = TT_ObjCMethodExpr;
128           if (Contexts.back().FirstObjCSelectorName != NULL) {
129             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
130                 Contexts.back().LongestObjCSelectorName;
131           }
132         }
133 
134         next();
135         return true;
136       }
137       if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
138         return false;
139       if (CurrentToken->Previous->Type == TT_PointerOrReference &&
140           CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
141                                                     tok::coloncolon))
142         MightBeFunctionType = true;
143       updateParameterCount(Left, CurrentToken);
144       if (!consumeToken())
145         return false;
146     }
147     return false;
148   }
149 
150   bool parseSquare() {
151     if (!CurrentToken)
152       return false;
153 
154     // A '[' could be an index subscript (after an indentifier or after
155     // ')' or ']'), it could be the start of an Objective-C method
156     // expression, or it could the the start of an Objective-C array literal.
157     FormatToken *Left = CurrentToken->Previous;
158     FormatToken *Parent = Left->getPreviousNoneComment();
159     bool StartsObjCMethodExpr =
160         Contexts.back().CanBeExpression &&
161         (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
162                                     tok::kw_return, tok::kw_throw) ||
163          Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
164          Parent->Type == TT_CastRParen ||
165          getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
166     ScopedContextCreator ContextCreator(*this, tok::l_square, 10);
167     Contexts.back().IsExpression = true;
168     bool StartsObjCArrayLiteral = Parent && Parent->is(tok::at);
169 
170     if (StartsObjCMethodExpr) {
171       Contexts.back().ColonIsObjCMethodExpr = true;
172       Left->Type = TT_ObjCMethodExpr;
173     } else if (StartsObjCArrayLiteral) {
174       Left->Type = TT_ObjCArrayLiteral;
175     }
176 
177     while (CurrentToken != NULL) {
178       if (CurrentToken->is(tok::r_square)) {
179         if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren)) {
180           // An ObjC method call is rarely followed by an open parenthesis.
181           // FIXME: Do we incorrectly label ":" with this?
182           StartsObjCMethodExpr = false;
183           Left->Type = TT_Unknown;
184         }
185         if (StartsObjCMethodExpr) {
186           CurrentToken->Type = TT_ObjCMethodExpr;
187           // determineStarAmpUsage() thinks that '*' '[' is allocating an
188           // array of pointers, but if '[' starts a selector then '*' is a
189           // binary operator.
190           if (Parent != NULL && Parent->Type == TT_PointerOrReference)
191             Parent->Type = TT_BinaryOperator;
192         } else if (StartsObjCArrayLiteral) {
193           CurrentToken->Type = TT_ObjCArrayLiteral;
194         }
195         Left->MatchingParen = CurrentToken;
196         CurrentToken->MatchingParen = Left;
197         if (Contexts.back().FirstObjCSelectorName != NULL)
198           Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
199               Contexts.back().LongestObjCSelectorName;
200         next();
201         return true;
202       }
203       if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
204         return false;
205       updateParameterCount(Left, CurrentToken);
206       if (!consumeToken())
207         return false;
208     }
209     return false;
210   }
211 
212   bool parseBrace() {
213     if (CurrentToken != NULL) {
214       ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
215       FormatToken *Left = CurrentToken->Previous;
216 
217       FormatToken *Parent = Left->getPreviousNoneComment();
218       bool StartsObjCDictLiteral = Parent && Parent->is(tok::at);
219       if (StartsObjCDictLiteral) {
220         Contexts.back().ColonIsObjCDictLiteral = true;
221         Left->Type = TT_ObjCDictLiteral;
222       }
223 
224       while (CurrentToken != NULL) {
225         if (CurrentToken->is(tok::r_brace)) {
226           if (StartsObjCDictLiteral)
227             CurrentToken->Type = TT_ObjCDictLiteral;
228           Left->MatchingParen = CurrentToken;
229           CurrentToken->MatchingParen = Left;
230           next();
231           return true;
232         }
233         if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
234           return false;
235         updateParameterCount(Left, CurrentToken);
236         if (!consumeToken())
237           return false;
238       }
239     }
240     // No closing "}" found, this probably starts a definition.
241     Line.StartsDefinition = true;
242     return true;
243   }
244 
245   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
246     if (Current->is(tok::comma))
247       ++Left->ParameterCount;
248     else if (Left->ParameterCount == 0 && Current->isNot(tok::comment))
249       Left->ParameterCount = 1;
250   }
251 
252   bool parseConditional() {
253     while (CurrentToken != NULL) {
254       if (CurrentToken->is(tok::colon)) {
255         CurrentToken->Type = TT_ConditionalExpr;
256         next();
257         return true;
258       }
259       if (!consumeToken())
260         return false;
261     }
262     return false;
263   }
264 
265   bool parseTemplateDeclaration() {
266     if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
267       CurrentToken->Type = TT_TemplateOpener;
268       next();
269       if (!parseAngle())
270         return false;
271       if (CurrentToken != NULL)
272         CurrentToken->Previous->ClosesTemplateDeclaration = true;
273       return true;
274     }
275     return false;
276   }
277 
278   bool consumeToken() {
279     FormatToken *Tok = CurrentToken;
280     next();
281     switch (Tok->Tok.getKind()) {
282     case tok::plus:
283     case tok::minus:
284       if (Tok->Previous == NULL && Line.MustBeDeclaration)
285         Tok->Type = TT_ObjCMethodSpecifier;
286       break;
287     case tok::colon:
288       if (Tok->Previous == NULL)
289         return false;
290       // Colons from ?: are handled in parseConditional().
291       if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1) {
292         Tok->Type = TT_CtorInitializerColon;
293       } else if (Contexts.back().ColonIsObjCDictLiteral) {
294         Tok->Type = TT_ObjCDictLiteral;
295       } else if (Contexts.back().ColonIsObjCMethodExpr ||
296                  Line.First->Type == TT_ObjCMethodSpecifier) {
297         Tok->Type = TT_ObjCMethodExpr;
298         Tok->Previous->Type = TT_ObjCSelectorName;
299         if (Tok->Previous->CodePointCount >
300             Contexts.back().LongestObjCSelectorName) {
301           Contexts.back().LongestObjCSelectorName =
302               Tok->Previous->CodePointCount;
303         }
304         if (Contexts.back().FirstObjCSelectorName == NULL)
305           Contexts.back().FirstObjCSelectorName = Tok->Previous;
306       } else if (Contexts.back().ColonIsForRangeExpr) {
307         Tok->Type = TT_RangeBasedForLoopColon;
308       } else if (Contexts.size() == 1) {
309         Tok->Type = TT_InheritanceColon;
310       } else if (Contexts.back().ContextKind == tok::l_paren) {
311         Tok->Type = TT_InlineASMColon;
312       }
313       break;
314     case tok::kw_if:
315     case tok::kw_while:
316       if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
317         next();
318         if (!parseParens(/*LookForDecls=*/ true))
319           return false;
320       }
321       break;
322     case tok::kw_for:
323       Contexts.back().ColonIsForRangeExpr = true;
324       next();
325       if (!parseParens())
326         return false;
327       break;
328     case tok::l_paren:
329       if (!parseParens())
330         return false;
331       if (Line.MustBeDeclaration && NameFound && !Contexts.back().IsExpression)
332         Line.MightBeFunctionDecl = true;
333       break;
334     case tok::l_square:
335       if (!parseSquare())
336         return false;
337       break;
338     case tok::l_brace:
339       if (!parseBrace())
340         return false;
341       break;
342     case tok::less:
343       if (parseAngle())
344         Tok->Type = TT_TemplateOpener;
345       else {
346         Tok->Type = TT_BinaryOperator;
347         CurrentToken = Tok;
348         next();
349       }
350       break;
351     case tok::r_paren:
352     case tok::r_square:
353       return false;
354     case tok::r_brace:
355       // Lines can start with '}'.
356       if (Tok->Previous != NULL)
357         return false;
358       break;
359     case tok::greater:
360       Tok->Type = TT_BinaryOperator;
361       break;
362     case tok::kw_operator:
363       while (CurrentToken && CurrentToken->isNot(tok::l_paren)) {
364         if (CurrentToken->isOneOf(tok::star, tok::amp))
365           CurrentToken->Type = TT_PointerOrReference;
366         consumeToken();
367       }
368       if (CurrentToken) {
369         CurrentToken->Type = TT_OverloadedOperatorLParen;
370         if (CurrentToken->Previous->Type == TT_BinaryOperator)
371           CurrentToken->Previous->Type = TT_OverloadedOperator;
372       }
373       break;
374     case tok::question:
375       parseConditional();
376       break;
377     case tok::kw_template:
378       parseTemplateDeclaration();
379       break;
380     case tok::identifier:
381       if (Line.First->is(tok::kw_for) &&
382           Tok->Tok.getIdentifierInfo() == &Ident_in)
383         Tok->Type = TT_ObjCForIn;
384       break;
385     case tok::comma:
386       if (Contexts.back().FirstStartOfName)
387         Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
388       break;
389     default:
390       break;
391     }
392     return true;
393   }
394 
395   void parseIncludeDirective() {
396     next();
397     if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
398       next();
399       while (CurrentToken != NULL) {
400         if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
401           CurrentToken->Type = TT_ImplicitStringLiteral;
402         next();
403       }
404     } else {
405       while (CurrentToken != NULL) {
406         if (CurrentToken->is(tok::string_literal))
407           // Mark these string literals as "implicit" literals, too, so that
408           // they are not split or line-wrapped.
409           CurrentToken->Type = TT_ImplicitStringLiteral;
410         next();
411       }
412     }
413   }
414 
415   void parseWarningOrError() {
416     next();
417     // We still want to format the whitespace left of the first token of the
418     // warning or error.
419     next();
420     while (CurrentToken != NULL) {
421       CurrentToken->Type = TT_ImplicitStringLiteral;
422       next();
423     }
424   }
425 
426   void parsePreprocessorDirective() {
427     next();
428     if (CurrentToken == NULL)
429       return;
430     // Hashes in the middle of a line can lead to any strange token
431     // sequence.
432     if (CurrentToken->Tok.getIdentifierInfo() == NULL)
433       return;
434     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
435     case tok::pp_include:
436     case tok::pp_import:
437       parseIncludeDirective();
438       break;
439     case tok::pp_error:
440     case tok::pp_warning:
441       parseWarningOrError();
442       break;
443     case tok::pp_if:
444     case tok::pp_elif:
445       parseLine();
446       break;
447     default:
448       break;
449     }
450     while (CurrentToken != NULL)
451       next();
452   }
453 
454 public:
455   LineType parseLine() {
456     int PeriodsAndArrows = 0;
457     FormatToken *LastPeriodOrArrow = NULL;
458     bool CanBeBuilderTypeStmt = true;
459     if (CurrentToken->is(tok::hash)) {
460       parsePreprocessorDirective();
461       return LT_PreprocessorDirective;
462     }
463     while (CurrentToken != NULL) {
464       if (CurrentToken->is(tok::kw_virtual))
465         KeywordVirtualFound = true;
466       if (CurrentToken->isOneOf(tok::period, tok::arrow)) {
467         ++PeriodsAndArrows;
468         LastPeriodOrArrow = CurrentToken;
469       }
470       FormatToken *TheToken = CurrentToken;
471       if (!consumeToken())
472         return LT_Invalid;
473       if (TheToken->getPrecedence() > prec::Assignment &&
474           TheToken->Type == TT_BinaryOperator)
475         CanBeBuilderTypeStmt = false;
476     }
477     if (KeywordVirtualFound)
478       return LT_VirtualFunctionDecl;
479 
480     // Assume a builder-type call if there are 2 or more "." and "->".
481     if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt) {
482       LastPeriodOrArrow->LastInChainOfCalls = true;
483       return LT_BuilderTypeCall;
484     }
485 
486     if (Line.First->Type == TT_ObjCMethodSpecifier) {
487       if (Contexts.back().FirstObjCSelectorName != NULL)
488         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
489             Contexts.back().LongestObjCSelectorName;
490       return LT_ObjCMethodDecl;
491     }
492 
493     return LT_Other;
494   }
495 
496 private:
497   void next() {
498     if (CurrentToken != NULL) {
499       determineTokenType(*CurrentToken);
500       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
501     }
502 
503     if (CurrentToken != NULL)
504       CurrentToken = CurrentToken->Next;
505 
506     // Reset token type in case we have already looked at it and then recovered
507     // from an error (e.g. failure to find the matching >).
508     if (CurrentToken != NULL)
509       CurrentToken->Type = TT_Unknown;
510   }
511 
512   /// \brief A struct to hold information valid in a specific context, e.g.
513   /// a pair of parenthesis.
514   struct Context {
515     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
516             bool IsExpression)
517         : ContextKind(ContextKind), BindingStrength(BindingStrength),
518           LongestObjCSelectorName(0), ColonIsForRangeExpr(false),
519           ColonIsObjCDictLiteral(false), ColonIsObjCMethodExpr(false),
520           FirstObjCSelectorName(NULL), FirstStartOfName(NULL),
521           IsExpression(IsExpression), CanBeExpression(true) {}
522 
523     tok::TokenKind ContextKind;
524     unsigned BindingStrength;
525     unsigned LongestObjCSelectorName;
526     bool ColonIsForRangeExpr;
527     bool ColonIsObjCDictLiteral;
528     bool ColonIsObjCMethodExpr;
529     FormatToken *FirstObjCSelectorName;
530     FormatToken *FirstStartOfName;
531     bool IsExpression;
532     bool CanBeExpression;
533   };
534 
535   /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
536   /// of each instance.
537   struct ScopedContextCreator {
538     AnnotatingParser &P;
539 
540     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
541                          unsigned Increase)
542         : P(P) {
543       P.Contexts.push_back(
544           Context(ContextKind, P.Contexts.back().BindingStrength + Increase,
545                   P.Contexts.back().IsExpression));
546     }
547 
548     ~ScopedContextCreator() { P.Contexts.pop_back(); }
549   };
550 
551   void determineTokenType(FormatToken &Current) {
552     if (Current.getPrecedence() == prec::Assignment &&
553         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
554       Contexts.back().IsExpression = true;
555       for (FormatToken *Previous = Current.Previous;
556            Previous && Previous->isNot(tok::comma);
557            Previous = Previous->Previous) {
558         if (Previous->is(tok::r_square))
559           Previous = Previous->MatchingParen;
560         if (Previous->Type == TT_BinaryOperator &&
561             Previous->isOneOf(tok::star, tok::amp)) {
562           Previous->Type = TT_PointerOrReference;
563         }
564       }
565     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw) ||
566                (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
567                 !Line.InPPDirective &&
568                 (!Current.Previous || Current.Previous->isNot(tok::kw_for)))) {
569       Contexts.back().IsExpression = true;
570     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
571       for (FormatToken *Previous = Current.Previous;
572            Previous && Previous->isOneOf(tok::star, tok::amp);
573            Previous = Previous->Previous)
574         Previous->Type = TT_PointerOrReference;
575     } else if (Current.Previous &&
576                Current.Previous->Type == TT_CtorInitializerColon) {
577       Contexts.back().IsExpression = true;
578     } else if (Current.is(tok::kw_new)) {
579       Contexts.back().CanBeExpression = false;
580     } else if (Current.is(tok::semi)) {
581       // This should be the condition or increment in a for-loop.
582       Contexts.back().IsExpression = true;
583     }
584 
585     if (Current.Type == TT_Unknown) {
586       if (Current.Previous && Current.is(tok::identifier) &&
587           ((Current.Previous->is(tok::identifier) &&
588             Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
589                 tok::pp_not_keyword) ||
590            isSimpleTypeSpecifier(*Current.Previous) ||
591            Current.Previous->Type == TT_PointerOrReference ||
592            Current.Previous->Type == TT_TemplateCloser)) {
593         Contexts.back().FirstStartOfName = &Current;
594         Current.Type = TT_StartOfName;
595         NameFound = true;
596       } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
597         Current.Type =
598             determineStarAmpUsage(Current, Contexts.back().IsExpression);
599       } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
600         Current.Type = determinePlusMinusCaretUsage(Current);
601       } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
602         Current.Type = determineIncrementUsage(Current);
603       } else if (Current.is(tok::exclaim)) {
604         Current.Type = TT_UnaryOperator;
605       } else if (Current.isBinaryOperator()) {
606         Current.Type = TT_BinaryOperator;
607       } else if (Current.is(tok::comment)) {
608         if (Current.TokenText.startswith("//"))
609           Current.Type = TT_LineComment;
610         else
611           Current.Type = TT_BlockComment;
612       } else if (Current.is(tok::r_paren)) {
613         FormatToken *LeftOfParens = NULL;
614         if (Current.MatchingParen)
615           LeftOfParens = Current.MatchingParen->getPreviousNoneComment();
616         bool IsCast = false;
617         bool ParensAreEmpty = Current.Previous == Current.MatchingParen;
618         bool ParensAreType = !Current.Previous ||
619                              Current.Previous->Type == TT_PointerOrReference ||
620                              Current.Previous->Type == TT_TemplateCloser ||
621                              isSimpleTypeSpecifier(*Current.Previous);
622         bool ParensCouldEndDecl =
623             Current.Next &&
624             Current.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
625         bool IsSizeOfOrAlignOf =
626             LeftOfParens &&
627             LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
628         if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
629             Contexts.back().IsExpression)
630           IsCast = true;
631         if (Current.Next &&
632             Current.Next->isNot(tok::string_literal) &&
633             (Current.Next->Tok.isLiteral() ||
634              Current.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
635           IsCast = true;
636         // If there is an identifier after the (), it is likely a cast, unless
637         // there is also an identifier before the ().
638         if (LeftOfParens && (LeftOfParens->Tok.getIdentifierInfo() == NULL ||
639                              LeftOfParens->is(tok::kw_return)) &&
640             LeftOfParens->Type != TT_TemplateCloser &&
641             LeftOfParens->Type != TT_ObjCMethodExpr && Current.Next &&
642             (Current.Next->is(tok::identifier)))
643           IsCast = true;
644         if (IsCast && !ParensAreEmpty)
645           Current.Type = TT_CastRParen;
646       } else if (Current.is(tok::at) && Current.Next) {
647         switch (Current.Next->Tok.getObjCKeywordID()) {
648         case tok::objc_interface:
649         case tok::objc_implementation:
650         case tok::objc_protocol:
651           Current.Type = TT_ObjCDecl;
652           break;
653         case tok::objc_property:
654           Current.Type = TT_ObjCProperty;
655           break;
656         default:
657           break;
658         }
659       } else if (Current.is(tok::period)) {
660         FormatToken *PreviousNoComment = Current.getPreviousNoneComment();
661         if (PreviousNoComment &&
662             PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
663           Current.Type = TT_DesignatedInitializerPeriod;
664       }
665     }
666   }
667 
668   /// \brief Return the type of the given token assuming it is * or &.
669   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression) {
670     const FormatToken *PrevToken = Tok.getPreviousNoneComment();
671     if (PrevToken == NULL)
672       return TT_UnaryOperator;
673 
674     const FormatToken *NextToken = Tok.getNextNoneComment();
675     if (NextToken == NULL)
676       return TT_Unknown;
677 
678     if (PrevToken->is(tok::coloncolon) ||
679         (PrevToken->is(tok::l_paren) && !IsExpression))
680       return TT_PointerOrReference;
681 
682     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
683                            tok::comma, tok::semi, tok::kw_return, tok::colon,
684                            tok::equal, tok::kw_delete) ||
685         PrevToken->Type == TT_BinaryOperator ||
686         PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
687       return TT_UnaryOperator;
688 
689     if (NextToken->is(tok::l_square))
690       return TT_PointerOrReference;
691 
692     if (PrevToken->Tok.isLiteral() ||
693         PrevToken->isOneOf(tok::r_paren, tok::r_square) ||
694         NextToken->Tok.isLiteral() || NextToken->isUnaryOperator())
695       return TT_BinaryOperator;
696 
697     // It is very unlikely that we are going to find a pointer or reference type
698     // definition on the RHS of an assignment.
699     if (IsExpression)
700       return TT_BinaryOperator;
701 
702     return TT_PointerOrReference;
703   }
704 
705   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
706     const FormatToken *PrevToken = Tok.getPreviousNoneComment();
707     if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
708       return TT_UnaryOperator;
709 
710     // Use heuristics to recognize unary operators.
711     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
712                            tok::question, tok::colon, tok::kw_return,
713                            tok::kw_case, tok::at, tok::l_brace))
714       return TT_UnaryOperator;
715 
716     // There can't be two consecutive binary operators.
717     if (PrevToken->Type == TT_BinaryOperator)
718       return TT_UnaryOperator;
719 
720     // Fall back to marking the token as binary operator.
721     return TT_BinaryOperator;
722   }
723 
724   /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
725   TokenType determineIncrementUsage(const FormatToken &Tok) {
726     const FormatToken *PrevToken = Tok.getPreviousNoneComment();
727     if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
728       return TT_UnaryOperator;
729     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
730       return TT_TrailingUnaryOperator;
731 
732     return TT_UnaryOperator;
733   }
734 
735   // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
736   // duplication.
737   /// \brief Determine whether the token kind starts a simple-type-specifier.
738   bool isSimpleTypeSpecifier(const FormatToken &Tok) const {
739     switch (Tok.Tok.getKind()) {
740     case tok::kw_short:
741     case tok::kw_long:
742     case tok::kw___int64:
743     case tok::kw___int128:
744     case tok::kw_signed:
745     case tok::kw_unsigned:
746     case tok::kw_void:
747     case tok::kw_char:
748     case tok::kw_int:
749     case tok::kw_half:
750     case tok::kw_float:
751     case tok::kw_double:
752     case tok::kw_wchar_t:
753     case tok::kw_bool:
754     case tok::kw___underlying_type:
755     case tok::annot_typename:
756     case tok::kw_char16_t:
757     case tok::kw_char32_t:
758     case tok::kw_typeof:
759     case tok::kw_decltype:
760       return true;
761     default:
762       return false;
763     }
764   }
765 
766   SmallVector<Context, 8> Contexts;
767 
768   AnnotatedLine &Line;
769   FormatToken *CurrentToken;
770   bool KeywordVirtualFound;
771   bool NameFound;
772   IdentifierInfo &Ident_in;
773 };
774 
775 /// \brief Parses binary expressions by inserting fake parenthesis based on
776 /// operator precedence.
777 class ExpressionParser {
778 public:
779   ExpressionParser(AnnotatedLine &Line) : Current(Line.First) {
780     // Skip leading "}", e.g. in "} else if (...) {".
781     if (Current->is(tok::r_brace))
782       next();
783   }
784 
785   /// \brief Parse expressions with the given operatore precedence.
786   void parse(int Precedence = 0) {
787     // Conditional expressions need to be parsed separately for proper nesting.
788     if (Precedence == prec::Conditional + 1) {
789       parseConditionalExpr();
790       return;
791     }
792     if (Precedence > prec::PointerToMember || Current == NULL)
793       return;
794 
795     // Eagerly consume trailing comments.
796     while (Current && Current->isTrailingComment()) {
797       next();
798     }
799 
800     FormatToken *Start = Current;
801     bool OperatorFound = false;
802 
803     while (Current) {
804       // Consume operators with higher precedence.
805       parse(Precedence + 1);
806 
807       int CurrentPrecedence = 0;
808       if (Current) {
809         if (Current->Type == TT_ConditionalExpr)
810           CurrentPrecedence = 1 + (int)prec::Conditional;
811         else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon)
812           CurrentPrecedence = 1;
813         else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
814           CurrentPrecedence = 1 + (int)Current->getPrecedence();
815       }
816 
817       // At the end of the line or when an operator with higher precedence is
818       // found, insert fake parenthesis and return.
819       if (Current == NULL || Current->closesScope() ||
820           (CurrentPrecedence != 0 && CurrentPrecedence < Precedence)) {
821         if (OperatorFound)
822           addFakeParenthesis(Start, prec::Level(Precedence - 1));
823         return;
824       }
825 
826       // Consume scopes: (), [], <> and {}
827       if (Current->opensScope()) {
828         while (Current && !Current->closesScope()) {
829           next();
830           parse();
831         }
832         next();
833       } else {
834         // Operator found.
835         if (CurrentPrecedence == Precedence)
836           OperatorFound = true;
837 
838         next();
839       }
840     }
841   }
842 
843 private:
844   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
845     Start->FakeLParens.push_back(Precedence);
846     if (Current)
847       ++Current->Previous->FakeRParens;
848   }
849 
850   void parseConditionalExpr() {
851     FormatToken *Start = Current;
852     parse(prec::LogicalOr + 1);
853     if (!Current || !Current->is(tok::question))
854       return;
855     next();
856     parse(prec::LogicalOr + 1);
857     if (!Current || Current->Type != TT_ConditionalExpr)
858       return;
859     next();
860     parseConditionalExpr();
861     addFakeParenthesis(Start, prec::Conditional);
862   }
863 
864   void next() {
865     if (Current != NULL)
866       Current = Current->Next;
867   }
868 
869   FormatToken *Current;
870 };
871 
872 void TokenAnnotator::annotate(AnnotatedLine &Line) {
873   AnnotatingParser Parser(Line, Ident_in);
874   Line.Type = Parser.parseLine();
875   if (Line.Type == LT_Invalid)
876     return;
877 
878   ExpressionParser ExprParser(Line);
879   ExprParser.parse();
880 
881   if (Line.First->Type == TT_ObjCMethodSpecifier)
882     Line.Type = LT_ObjCMethodDecl;
883   else if (Line.First->Type == TT_ObjCDecl)
884     Line.Type = LT_ObjCDecl;
885   else if (Line.First->Type == TT_ObjCProperty)
886     Line.Type = LT_ObjCProperty;
887 
888   Line.First->SpacesRequiredBefore = 1;
889   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
890 }
891 
892 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
893   Line.First->TotalLength = Line.First->CodePointCount;
894   if (!Line.First->Next)
895     return;
896   FormatToken *Current = Line.First->Next;
897   while (Current != NULL) {
898     if (Current->Type == TT_LineComment)
899       Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
900     else
901       Current->SpacesRequiredBefore =
902           spaceRequiredBefore(Line, *Current) ? 1 : 0;
903 
904     if (Current->MustBreakBefore) {
905     } else if (Current->is(tok::comment)) {
906       Current->MustBreakBefore = Current->NewlinesBefore > 0;
907     } else if (Current->Previous->isTrailingComment() ||
908                (Current->is(tok::string_literal) &&
909                 Current->Previous->is(tok::string_literal))) {
910       Current->MustBreakBefore = true;
911     } else if (Current->is(tok::lessless) && Current->Next &&
912                Current->Previous->is(tok::string_literal) &&
913                Current->Next->is(tok::string_literal)) {
914       Current->MustBreakBefore = true;
915     } else if (Current->Previous->ClosesTemplateDeclaration &&
916                Style.AlwaysBreakTemplateDeclarations) {
917       Current->MustBreakBefore = true;
918     } else {
919       Current->MustBreakBefore = false;
920     }
921     Current->CanBreakBefore =
922         Current->MustBreakBefore || canBreakBefore(Line, *Current);
923     if (Current->MustBreakBefore)
924       Current->TotalLength = Current->Previous->TotalLength + Style.ColumnLimit;
925     else
926       Current->TotalLength =
927           Current->Previous->TotalLength + Current->CodePointCount +
928           Current->SpacesRequiredBefore;
929     // FIXME: Only calculate this if CanBreakBefore is true once static
930     // initializers etc. are sorted out.
931     // FIXME: Move magic numbers to a better place.
932     Current->SplitPenalty =
933         20 * Current->BindingStrength + splitPenalty(Line, *Current);
934 
935     Current = Current->Next;
936   }
937 
938   calculateUnbreakableTailLengths(Line);
939   DEBUG({
940     printDebugInfo(Line);
941   });
942 }
943 
944 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
945   unsigned UnbreakableTailLength = 0;
946   FormatToken *Current = Line.Last;
947   while (Current != NULL) {
948     Current->UnbreakableTailLength = UnbreakableTailLength;
949     if (Current->CanBreakBefore ||
950         Current->isOneOf(tok::comment, tok::string_literal)) {
951       UnbreakableTailLength = 0;
952     } else {
953       UnbreakableTailLength +=
954           Current->CodePointCount + Current->SpacesRequiredBefore;
955     }
956     Current = Current->Previous;
957   }
958 }
959 
960 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
961                                       const FormatToken &Tok) {
962   const FormatToken &Left = *Tok.Previous;
963   const FormatToken &Right = Tok;
964 
965   if (Left.is(tok::semi))
966     return 0;
967   if (Left.is(tok::comma))
968     return 1;
969 
970   if (Right.Type == TT_StartOfName) {
971     if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
972       return 3;
973     else if (Line.MightBeFunctionDecl && Right.BindingStrength == 1)
974       // FIXME: Clean up hack of using BindingStrength to find top-level names.
975       return Style.PenaltyReturnTypeOnItsOwnLine;
976     else
977       return 200;
978   }
979   if (Left.is(tok::equal) && Right.is(tok::l_brace))
980     return 150;
981   if (Left.is(tok::coloncolon))
982     return 500;
983   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
984     return 5000;
985 
986   if (Left.Type == TT_RangeBasedForLoopColon ||
987       Left.Type == TT_InheritanceColon)
988     return 2;
989 
990   if (Right.isOneOf(tok::arrow, tok::period) &&
991       Right.Type != TT_DesignatedInitializerPeriod) {
992     if (Line.Type == LT_BuilderTypeCall)
993       return prec::PointerToMember;
994     if (Left.isOneOf(tok::r_paren, tok::r_square) && Left.MatchingParen &&
995         Left.MatchingParen->ParameterCount > 0)
996       return 20; // Should be smaller than breaking at a nested comma.
997     return 150;
998   }
999 
1000   // Breaking before a trailing 'const' is bad.
1001   if (Left.is(tok::r_paren) && Right.is(tok::kw_const))
1002     return 150;
1003 
1004   // In for-loops, prefer breaking at ',' and ';'.
1005   if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
1006     return 4;
1007 
1008   // In Objective-C method expressions, prefer breaking before "param:" over
1009   // breaking after it.
1010   if (Right.Type == TT_ObjCSelectorName)
1011     return 0;
1012   if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1013     return 20;
1014 
1015   if (Left.is(tok::l_paren) && Line.MightBeFunctionDecl)
1016     return 100;
1017   if (Left.opensScope())
1018     return Left.ParameterCount > 1 ? prec::Comma : 20;
1019 
1020   if (Right.is(tok::lessless)) {
1021     if (Left.is(tok::string_literal)) {
1022       StringRef Content = Left.TokenText;
1023       Content = Content.drop_back(1).drop_front(1).trim();
1024       if (Content.size() > 1 &&
1025           (Content.back() == ':' || Content.back() == '='))
1026         return 20;
1027     }
1028     return prec::Shift;
1029   }
1030   if (Left.Type == TT_ConditionalExpr)
1031     return prec::Conditional;
1032   prec::Level Level = Left.getPrecedence();
1033 
1034   if (Level != prec::Unknown)
1035     return Level;
1036 
1037   return 3;
1038 }
1039 
1040 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1041                                           const FormatToken &Left,
1042                                           const FormatToken &Right) {
1043   if (Right.is(tok::hashhash))
1044     return Left.is(tok::hash);
1045   if (Left.isOneOf(tok::hashhash, tok::hash))
1046     return Right.is(tok::hash);
1047   if (Right.isOneOf(tok::r_paren, tok::semi, tok::comma))
1048     return false;
1049   if (Right.is(tok::less) &&
1050       (Left.is(tok::kw_template) ||
1051        (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1052     return true;
1053   if (Left.is(tok::arrow) || Right.is(tok::arrow))
1054     return false;
1055   if (Left.isOneOf(tok::exclaim, tok::tilde))
1056     return false;
1057   if (Left.is(tok::at) &&
1058       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1059                     tok::numeric_constant, tok::l_paren, tok::l_brace,
1060                     tok::kw_true, tok::kw_false))
1061     return false;
1062   if (Left.is(tok::coloncolon))
1063     return false;
1064   if (Right.is(tok::coloncolon))
1065     return !Left.isOneOf(tok::identifier, tok::greater, tok::l_paren);
1066   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1067     return false;
1068   if (Right.Type == TT_PointerOrReference)
1069     return Left.Tok.isLiteral() ||
1070            ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
1071             !Style.PointerBindsToType);
1072   if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
1073       (Left.Type != TT_PointerOrReference || Style.PointerBindsToType))
1074     return true;
1075   if (Left.Type == TT_PointerOrReference)
1076     return Right.Tok.isLiteral() ||
1077            ((Right.Type != TT_PointerOrReference) &&
1078             Right.isNot(tok::l_paren) && Style.PointerBindsToType &&
1079             Left.Previous &&
1080             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1081   if (Right.is(tok::star) && Left.is(tok::l_paren))
1082     return false;
1083   if (Left.is(tok::l_square))
1084     return Left.Type == TT_ObjCArrayLiteral && Right.isNot(tok::r_square);
1085   if (Right.is(tok::r_square))
1086     return Right.Type == TT_ObjCArrayLiteral;
1087   if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
1088     return false;
1089   if (Left.is(tok::colon))
1090     return Left.Type != TT_ObjCMethodExpr;
1091   if (Right.is(tok::colon))
1092     return Right.Type != TT_ObjCMethodExpr;
1093   if (Left.is(tok::l_paren))
1094     return false;
1095   if (Right.is(tok::l_paren)) {
1096     return Line.Type == LT_ObjCDecl ||
1097            Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
1098                         tok::kw_return, tok::kw_catch, tok::kw_new,
1099                         tok::kw_delete, tok::semi);
1100   }
1101   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1102     return false;
1103   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1104     return false; // No spaces in "{}".
1105   if (Left.is(tok::l_brace) || Right.is(tok::r_brace))
1106     return Style.SpacesInBracedLists;
1107   if (Right.Type == TT_UnaryOperator)
1108     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1109            (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
1110   if (Left.isOneOf(tok::identifier, tok::greater, tok::r_square) &&
1111       Right.is(tok::l_brace) && Right.getNextNoneComment())
1112     return false;
1113   if (Right.is(tok::ellipsis))
1114     return false;
1115   if (Left.is(tok::period) || Right.is(tok::period))
1116     return false;
1117   return true;
1118 }
1119 
1120 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1121                                          const FormatToken &Tok) {
1122   if (Tok.Tok.getIdentifierInfo() && Tok.Previous->Tok.getIdentifierInfo())
1123     return true; // Never ever merge two identifiers.
1124   if (Line.Type == LT_ObjCMethodDecl) {
1125     if (Tok.Previous->Type == TT_ObjCMethodSpecifier)
1126       return true;
1127     if (Tok.Previous->is(tok::r_paren) && Tok.is(tok::identifier))
1128       // Don't space between ')' and <id>
1129       return false;
1130   }
1131   if (Line.Type == LT_ObjCProperty &&
1132       (Tok.is(tok::equal) || Tok.Previous->is(tok::equal)))
1133     return false;
1134 
1135   if (Tok.Previous->is(tok::comma))
1136     return true;
1137   if (Tok.is(tok::comma))
1138     return false;
1139   if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
1140     return true;
1141   if (Tok.Previous->Tok.is(tok::kw_operator))
1142     return false;
1143   if (Tok.Type == TT_OverloadedOperatorLParen)
1144     return false;
1145   if (Tok.is(tok::colon))
1146     return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
1147            Tok.getNextNoneComment() != NULL && Tok.Type != TT_ObjCMethodExpr;
1148   if (Tok.Previous->Type == TT_UnaryOperator ||
1149       Tok.Previous->Type == TT_CastRParen)
1150     return false;
1151   if (Tok.Previous->is(tok::greater) && Tok.is(tok::greater)) {
1152     return Tok.Type == TT_TemplateCloser &&
1153            Tok.Previous->Type == TT_TemplateCloser &&
1154            Style.Standard != FormatStyle::LS_Cpp11;
1155   }
1156   if (Tok.isOneOf(tok::arrowstar, tok::periodstar) ||
1157       Tok.Previous->isOneOf(tok::arrowstar, tok::periodstar))
1158     return false;
1159   if (Tok.Type == TT_BinaryOperator || Tok.Previous->Type == TT_BinaryOperator)
1160     return true;
1161   if (Tok.Previous->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
1162     return false;
1163   if (Tok.is(tok::less) && Line.First->is(tok::hash))
1164     return true;
1165   if (Tok.Type == TT_TrailingUnaryOperator)
1166     return false;
1167   return spaceRequiredBetween(Line, *Tok.Previous, Tok);
1168 }
1169 
1170 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
1171                                     const FormatToken &Right) {
1172   const FormatToken &Left = *Right.Previous;
1173   if (Right.Type == TT_StartOfName)
1174     return true;
1175   if (Right.is(tok::colon) &&
1176       (Right.Type == TT_ObjCDictLiteral || Right.Type == TT_ObjCMethodExpr))
1177     return false;
1178   if (Left.is(tok::colon) &&
1179       (Left.Type == TT_ObjCDictLiteral || Left.Type == TT_ObjCMethodExpr))
1180     return true;
1181   if (Right.Type == TT_ObjCSelectorName)
1182     return true;
1183   if (Left.ClosesTemplateDeclaration)
1184     return true;
1185   if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1186     return true;
1187   if (Right.Type == TT_RangeBasedForLoopColon ||
1188       Right.Type == TT_OverloadedOperatorLParen)
1189     return false;
1190   if (Left.Type == TT_RangeBasedForLoopColon)
1191     return true;
1192   if (Right.Type == TT_RangeBasedForLoopColon)
1193     return false;
1194   if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
1195       Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1196       Left.isOneOf(tok::question, tok::kw_operator))
1197     return false;
1198   if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
1199     return false;
1200   if (Left.is(tok::l_paren) && Right.is(tok::l_paren) && Left.Previous &&
1201       Left.Previous->is(tok::kw___attribute))
1202     return false;
1203 
1204   if (Right.isTrailingComment())
1205     // We rely on MustBreakBefore being set correctly here as we should not
1206     // change the "binding" behavior of a comment.
1207     return false;
1208 
1209   // We only break before r_brace if there was a corresponding break before
1210   // the l_brace, which is tracked by BreakBeforeClosingBrace.
1211   if (Right.isOneOf(tok::r_brace, tok::r_paren, tok::greater))
1212     return false;
1213 
1214   // Allow breaking after a trailing 'const', e.g. after a method declaration,
1215   // unless it is follow by ';', '{' or '='.
1216   if (Left.is(tok::kw_const) && Left.Previous != NULL &&
1217       Left.Previous->is(tok::r_paren))
1218     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal);
1219 
1220   if (Right.is(tok::kw___attribute))
1221     return true;
1222 
1223   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
1224     return true;
1225   return (Left.isBinaryOperator() && Left.isNot(tok::lessless)) ||
1226          Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
1227                       tok::kw_class, tok::kw_struct) ||
1228          Right.isOneOf(tok::lessless, tok::arrow, tok::period, tok::colon) ||
1229          (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1230           Right.isOneOf(tok::identifier, tok::kw_const, tok::kw___attribute)) ||
1231          (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1232          (Left.is(tok::l_square) && !Right.is(tok::r_square));
1233 }
1234 
1235 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
1236   llvm::errs() << "AnnotatedTokens:\n";
1237   const FormatToken *Tok = Line.First;
1238   while (Tok) {
1239     llvm::errs() << " M=" << Tok->MustBreakBefore
1240                  << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type << " S="
1241                  << Tok->SpacesRequiredBefore << " P=" << Tok->SplitPenalty
1242                  << " Name=" << Tok->Tok.getName() << " FakeLParens=";
1243     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
1244       llvm::errs() << Tok->FakeLParens[i] << "/";
1245     llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
1246     Tok = Tok->Next;
1247   }
1248   llvm::errs() << "----\n";
1249 }
1250 
1251 } // namespace format
1252 } // namespace clang
1253