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