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