]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp
Merge ^/head r285153 through r285283.
[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.startsWith(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 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.startsWith(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.startsWith(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::comma, 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.startsWith(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.startsWith(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.startsWith(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.isOneOf(tok::semi, 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->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
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->isOneOf(tok::kw_return, tok::kw_case)) &&
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 || NextToken->is(tok::arrow) ||
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 ((Style.Language == FormatStyle::LK_Java ||
1340            Style.Language == FormatStyle::LK_JavaScript) &&
1341           Current->is(Keywords.kw_instanceof))
1342         return prec::Relational;
1343       if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1344         return Current->getPrecedence();
1345       if (Current->isOneOf(tok::period, tok::arrow))
1346         return PrecedenceArrowAndPeriod;
1347       if (Style.Language == FormatStyle::LK_Java &&
1348           Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1349                            Keywords.kw_throws))
1350         return 0;
1351     }
1352     return -1;
1353   }
1354
1355   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1356     Start->FakeLParens.push_back(Precedence);
1357     if (Precedence > prec::Unknown)
1358       Start->StartsBinaryExpression = true;
1359     if (Current) {
1360       FormatToken *Previous = Current->Previous;
1361       while (Previous->is(tok::comment) && Previous->Previous)
1362         Previous = Previous->Previous;
1363       ++Previous->FakeRParens;
1364       if (Precedence > prec::Unknown)
1365         Previous->EndsBinaryExpression = true;
1366     }
1367   }
1368
1369   /// \brief Parse unary operator expressions and surround them with fake
1370   /// parentheses if appropriate.
1371   void parseUnaryOperator() {
1372     if (!Current || Current->isNot(TT_UnaryOperator)) {
1373       parse(PrecedenceArrowAndPeriod);
1374       return;
1375     }
1376
1377     FormatToken *Start = Current;
1378     next();
1379     parseUnaryOperator();
1380
1381     // The actual precedence doesn't matter.
1382     addFakeParenthesis(Start, prec::Unknown);
1383   }
1384
1385   void parseConditionalExpr() {
1386     while (Current && Current->isTrailingComment()) {
1387       next();
1388     }
1389     FormatToken *Start = Current;
1390     parse(prec::LogicalOr);
1391     if (!Current || !Current->is(tok::question))
1392       return;
1393     next();
1394     parse(prec::Assignment);
1395     if (!Current || Current->isNot(TT_ConditionalExpr))
1396       return;
1397     next();
1398     parse(prec::Assignment);
1399     addFakeParenthesis(Start, prec::Conditional);
1400   }
1401
1402   void next(bool SkipPastLeadingComments = true) {
1403     if (Current)
1404       Current = Current->Next;
1405     while (Current &&
1406            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1407            Current->isTrailingComment())
1408       Current = Current->Next;
1409   }
1410
1411   const FormatStyle &Style;
1412   const AdditionalKeywords &Keywords;
1413   FormatToken *Current;
1414 };
1415
1416 } // end anonymous namespace
1417
1418 void TokenAnnotator::setCommentLineLevels(
1419     SmallVectorImpl<AnnotatedLine *> &Lines) {
1420   const AnnotatedLine *NextNonCommentLine = nullptr;
1421   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1422                                                           E = Lines.rend();
1423        I != E; ++I) {
1424     if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1425         (*I)->First->Next == nullptr)
1426       (*I)->Level = NextNonCommentLine->Level;
1427     else
1428       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1429
1430     setCommentLineLevels((*I)->Children);
1431   }
1432 }
1433
1434 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1435   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1436                                                   E = Line.Children.end();
1437        I != E; ++I) {
1438     annotate(**I);
1439   }
1440   AnnotatingParser Parser(Style, Line, Keywords);
1441   Line.Type = Parser.parseLine();
1442   if (Line.Type == LT_Invalid)
1443     return;
1444
1445   ExpressionParser ExprParser(Style, Keywords, Line);
1446   ExprParser.parse();
1447
1448   if (Line.startsWith(TT_ObjCMethodSpecifier))
1449     Line.Type = LT_ObjCMethodDecl;
1450   else if (Line.startsWith(TT_ObjCDecl))
1451     Line.Type = LT_ObjCDecl;
1452   else if (Line.startsWith(TT_ObjCProperty))
1453     Line.Type = LT_ObjCProperty;
1454
1455   Line.First->SpacesRequiredBefore = 1;
1456   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1457 }
1458
1459 // This function heuristically determines whether 'Current' starts the name of a
1460 // function declaration.
1461 static bool isFunctionDeclarationName(const FormatToken &Current) {
1462   if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1463     return false;
1464   const FormatToken *Next = Current.Next;
1465   for (; Next; Next = Next->Next) {
1466     if (Next->is(TT_TemplateOpener)) {
1467       Next = Next->MatchingParen;
1468     } else if (Next->is(tok::coloncolon)) {
1469       Next = Next->Next;
1470       if (!Next || !Next->is(tok::identifier))
1471         return false;
1472     } else if (Next->is(tok::l_paren)) {
1473       break;
1474     } else {
1475       return false;
1476     }
1477   }
1478   if (!Next)
1479     return false;
1480   assert(Next->is(tok::l_paren));
1481   if (Next->Next == Next->MatchingParen)
1482     return true;
1483   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1484        Tok = Tok->Next) {
1485     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1486         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1487       return true;
1488     if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1489         Tok->Tok.isLiteral())
1490       return false;
1491   }
1492   return false;
1493 }
1494
1495 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1496   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1497                                                   E = Line.Children.end();
1498        I != E; ++I) {
1499     calculateFormattingInformation(**I);
1500   }
1501
1502   Line.First->TotalLength =
1503       Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1504   if (!Line.First->Next)
1505     return;
1506   FormatToken *Current = Line.First->Next;
1507   bool InFunctionDecl = Line.MightBeFunctionDecl;
1508   while (Current) {
1509     if (isFunctionDeclarationName(*Current))
1510       Current->Type = TT_FunctionDeclarationName;
1511     if (Current->is(TT_LineComment)) {
1512       if (Current->Previous->BlockKind == BK_BracedInit &&
1513           Current->Previous->opensScope())
1514         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1515       else
1516         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1517
1518       // If we find a trailing comment, iterate backwards to determine whether
1519       // it seems to relate to a specific parameter. If so, break before that
1520       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1521       // to the previous line in:
1522       //   SomeFunction(a,
1523       //                b, // comment
1524       //                c);
1525       if (!Current->HasUnescapedNewline) {
1526         for (FormatToken *Parameter = Current->Previous; Parameter;
1527              Parameter = Parameter->Previous) {
1528           if (Parameter->isOneOf(tok::comment, tok::r_brace))
1529             break;
1530           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1531             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1532                 Parameter->HasUnescapedNewline)
1533               Parameter->MustBreakBefore = true;
1534             break;
1535           }
1536         }
1537       }
1538     } else if (Current->SpacesRequiredBefore == 0 &&
1539                spaceRequiredBefore(Line, *Current)) {
1540       Current->SpacesRequiredBefore = 1;
1541     }
1542
1543     Current->MustBreakBefore =
1544         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1545
1546     if ((Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All ||
1547          (Style.AlwaysBreakAfterDefinitionReturnType ==
1548               FormatStyle::DRTBS_TopLevel &&
1549           Line.Level == 0)) &&
1550         InFunctionDecl && Current->is(TT_FunctionDeclarationName) &&
1551         !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
1552       // FIXME: Line.Last points to other characters than tok::semi
1553       // and tok::lbrace.
1554       Current->MustBreakBefore = true;
1555
1556     Current->CanBreakBefore =
1557         Current->MustBreakBefore || canBreakBefore(Line, *Current);
1558     unsigned ChildSize = 0;
1559     if (Current->Previous->Children.size() == 1) {
1560       FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1561       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1562                                                   : LastOfChild.TotalLength + 1;
1563     }
1564     const FormatToken *Prev = Current->Previous;
1565     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1566         (Prev->Children.size() == 1 &&
1567          Prev->Children[0]->First->MustBreakBefore) ||
1568         Current->IsMultiline)
1569       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1570     else
1571       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1572                              ChildSize + Current->SpacesRequiredBefore;
1573
1574     if (Current->is(TT_CtorInitializerColon))
1575       InFunctionDecl = false;
1576
1577     // FIXME: Only calculate this if CanBreakBefore is true once static
1578     // initializers etc. are sorted out.
1579     // FIXME: Move magic numbers to a better place.
1580     Current->SplitPenalty = 20 * Current->BindingStrength +
1581                             splitPenalty(Line, *Current, InFunctionDecl);
1582
1583     Current = Current->Next;
1584   }
1585
1586   calculateUnbreakableTailLengths(Line);
1587   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1588     if (Current->Role)
1589       Current->Role->precomputeFormattingInfos(Current);
1590   }
1591
1592   DEBUG({ printDebugInfo(Line); });
1593 }
1594
1595 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1596   unsigned UnbreakableTailLength = 0;
1597   FormatToken *Current = Line.Last;
1598   while (Current) {
1599     Current->UnbreakableTailLength = UnbreakableTailLength;
1600     if (Current->CanBreakBefore ||
1601         Current->isOneOf(tok::comment, tok::string_literal)) {
1602       UnbreakableTailLength = 0;
1603     } else {
1604       UnbreakableTailLength +=
1605           Current->ColumnWidth + Current->SpacesRequiredBefore;
1606     }
1607     Current = Current->Previous;
1608   }
1609 }
1610
1611 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1612                                       const FormatToken &Tok,
1613                                       bool InFunctionDecl) {
1614   const FormatToken &Left = *Tok.Previous;
1615   const FormatToken &Right = Tok;
1616
1617   if (Left.is(tok::semi))
1618     return 0;
1619
1620   if (Style.Language == FormatStyle::LK_Java) {
1621     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1622       return 1;
1623     if (Right.is(Keywords.kw_implements))
1624       return 2;
1625     if (Left.is(tok::comma) && Left.NestingLevel == 0)
1626       return 3;
1627   } else if (Style.Language == FormatStyle::LK_JavaScript) {
1628     if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1629       return 100;
1630   }
1631
1632   if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1633                               Right.Next->is(TT_DictLiteral)))
1634     return 1;
1635   if (Right.is(tok::l_square)) {
1636     if (Style.Language == FormatStyle::LK_Proto)
1637       return 1;
1638     // Slightly prefer formatting local lambda definitions like functions.
1639     if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1640       return 50;
1641     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1642                        TT_ArrayInitializerLSquare))
1643       return 500;
1644   }
1645
1646   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1647       Right.is(tok::kw_operator)) {
1648     if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1649       return 3;
1650     if (Left.is(TT_StartOfName))
1651       return 110;
1652     if (InFunctionDecl && Right.NestingLevel == 0)
1653       return Style.PenaltyReturnTypeOnItsOwnLine;
1654     return 200;
1655   }
1656   if (Right.is(TT_PointerOrReference))
1657     return 190;
1658   if (Right.is(TT_LambdaArrow))
1659     return 110;
1660   if (Left.is(tok::equal) && Right.is(tok::l_brace))
1661     return 150;
1662   if (Left.is(TT_CastRParen))
1663     return 100;
1664   if (Left.is(tok::coloncolon) ||
1665       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1666     return 500;
1667   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1668     return 5000;
1669
1670   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1671     return 2;
1672
1673   if (Right.isMemberAccess()) {
1674     if (Left.is(tok::r_paren) && Left.MatchingParen &&
1675         Left.MatchingParen->ParameterCount > 0)
1676       return 20; // Should be smaller than breaking at a nested comma.
1677     return 150;
1678   }
1679
1680   if (Right.is(TT_TrailingAnnotation) &&
1681       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1682     // Moving trailing annotations to the next line is fine for ObjC method
1683     // declarations.
1684     if (Line.startsWith(TT_ObjCMethodSpecifier))
1685       return 10;
1686     // Generally, breaking before a trailing annotation is bad unless it is
1687     // function-like. It seems to be especially preferable to keep standard
1688     // annotations (i.e. "const", "final" and "override") on the same line.
1689     // Use a slightly higher penalty after ")" so that annotations like
1690     // "const override" are kept together.
1691     bool is_short_annotation = Right.TokenText.size() < 10;
1692     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1693   }
1694
1695   // In for-loops, prefer breaking at ',' and ';'.
1696   if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1697     return 4;
1698
1699   // In Objective-C method expressions, prefer breaking before "param:" over
1700   // breaking after it.
1701   if (Right.is(TT_SelectorName))
1702     return 0;
1703   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1704     return Line.MightBeFunctionDecl ? 50 : 500;
1705
1706   if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
1707     return 100;
1708   if (Left.is(tok::l_paren) && Left.Previous && Left.Previous->is(tok::kw_if))
1709     return 1000;
1710   if (Left.is(tok::equal) && InFunctionDecl)
1711     return 110;
1712   if (Right.is(tok::r_brace))
1713     return 1;
1714   if (Left.is(TT_TemplateOpener))
1715     return 100;
1716   if (Left.opensScope()) {
1717     if (!Style.AlignAfterOpenBracket)
1718       return 0;
1719     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1720                                    : 19;
1721   }
1722   if (Left.is(TT_JavaAnnotation))
1723     return 50;
1724
1725   if (Right.is(tok::lessless)) {
1726     if (Left.is(tok::string_literal) &&
1727         (!Right.LastOperator || Right.OperatorIndex != 1)) {
1728       StringRef Content = Left.TokenText;
1729       if (Content.startswith("\""))
1730         Content = Content.drop_front(1);
1731       if (Content.endswith("\""))
1732         Content = Content.drop_back(1);
1733       Content = Content.trim();
1734       if (Content.size() > 1 &&
1735           (Content.back() == ':' || Content.back() == '='))
1736         return 25;
1737     }
1738     return 1; // Breaking at a << is really cheap.
1739   }
1740   if (Left.is(TT_ConditionalExpr))
1741     return prec::Conditional;
1742   prec::Level Level = Left.getPrecedence();
1743   if (Level != prec::Unknown)
1744     return Level;
1745   Level = Right.getPrecedence();
1746   if (Level != prec::Unknown)
1747     return Level;
1748
1749   return 3;
1750 }
1751
1752 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1753                                           const FormatToken &Left,
1754                                           const FormatToken &Right) {
1755   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1756     return true;
1757   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1758       Left.Tok.getObjCKeywordID() == tok::objc_property)
1759     return true;
1760   if (Right.is(tok::hashhash))
1761     return Left.is(tok::hash);
1762   if (Left.isOneOf(tok::hashhash, tok::hash))
1763     return Right.is(tok::hash);
1764   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1765     return Style.SpaceInEmptyParentheses;
1766   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1767     return (Right.is(TT_CastRParen) ||
1768             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1769                ? Style.SpacesInCStyleCastParentheses
1770                : Style.SpacesInParentheses;
1771   if (Right.isOneOf(tok::semi, tok::comma))
1772     return false;
1773   if (Right.is(tok::less) &&
1774       (Left.is(tok::kw_template) ||
1775        (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1776     return true;
1777   if (Left.isOneOf(tok::exclaim, tok::tilde))
1778     return false;
1779   if (Left.is(tok::at) &&
1780       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1781                     tok::numeric_constant, tok::l_paren, tok::l_brace,
1782                     tok::kw_true, tok::kw_false))
1783     return false;
1784   if (Left.is(tok::coloncolon))
1785     return false;
1786   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1787     return false;
1788   if (Right.is(tok::ellipsis))
1789     return Left.Tok.isLiteral();
1790   if (Left.is(tok::l_square) && Right.is(tok::amp))
1791     return false;
1792   if (Right.is(TT_PointerOrReference))
1793     return !(Left.is(tok::r_paren) && Left.MatchingParen &&
1794              (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1795               (Left.MatchingParen->Previous &&
1796                Left.MatchingParen->Previous->is(
1797                    TT_FunctionDeclarationName)))) &&
1798            (Left.Tok.isLiteral() ||
1799             (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1800              (Style.PointerAlignment != FormatStyle::PAS_Left ||
1801               Line.IsMultiVariableDeclStmt)));
1802   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1803       (!Left.is(TT_PointerOrReference) ||
1804        (Style.PointerAlignment != FormatStyle::PAS_Right &&
1805         !Line.IsMultiVariableDeclStmt)))
1806     return true;
1807   if (Left.is(TT_PointerOrReference))
1808     return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
1809            (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
1810            (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1811                            tok::l_paren) &&
1812             (Style.PointerAlignment != FormatStyle::PAS_Right &&
1813              !Line.IsMultiVariableDeclStmt) &&
1814             Left.Previous &&
1815             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1816   if (Right.is(tok::star) && Left.is(tok::l_paren))
1817     return false;
1818   if (Left.is(tok::l_square))
1819     return (Left.is(TT_ArrayInitializerLSquare) &&
1820             Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1821            (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1822             Right.isNot(tok::r_square));
1823   if (Right.is(tok::r_square))
1824     return Right.MatchingParen &&
1825            ((Style.SpacesInContainerLiterals &&
1826              Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1827             (Style.SpacesInSquareBrackets &&
1828              Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1829   if (Right.is(tok::l_square) &&
1830       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1831       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1832     return false;
1833   if (Left.is(tok::colon))
1834     return !Left.is(TT_ObjCMethodExpr);
1835   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1836     return !Left.Children.empty(); // No spaces in "{}".
1837   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1838       (Right.is(tok::r_brace) && Right.MatchingParen &&
1839        Right.MatchingParen->BlockKind != BK_Block))
1840     return !Style.Cpp11BracedListStyle;
1841   if (Left.is(TT_BlockComment))
1842     return !Left.TokenText.endswith("=*/");
1843   if (Right.is(tok::l_paren)) {
1844     if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1845       return true;
1846     return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1847            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1848             (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
1849                           tok::kw_switch, tok::kw_case, TT_ForEachMacro) ||
1850              (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1851                            tok::kw_new, tok::kw_delete) &&
1852               (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
1853            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1854             (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
1855              Left.is(tok::r_paren)) &&
1856             Line.Type != LT_PreprocessorDirective);
1857   }
1858   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1859     return false;
1860   if (Right.is(TT_UnaryOperator))
1861     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1862            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1863   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1864                     tok::r_paren) ||
1865        Left.isSimpleTypeSpecifier()) &&
1866       Right.is(tok::l_brace) && Right.getNextNonComment() &&
1867       Right.BlockKind != BK_Block)
1868     return false;
1869   if (Left.is(tok::period) || Right.is(tok::period))
1870     return false;
1871   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1872     return false;
1873   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1874       Left.MatchingParen->Previous &&
1875       Left.MatchingParen->Previous->is(tok::period))
1876     // A.<B>DoSomething();
1877     return false;
1878   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1879     return false;
1880   return true;
1881 }
1882
1883 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1884                                          const FormatToken &Right) {
1885   const FormatToken &Left = *Right.Previous;
1886   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1887     return true; // Never ever merge two identifiers.
1888   if (Style.Language == FormatStyle::LK_Cpp) {
1889     if (Left.is(tok::kw_operator))
1890       return Right.is(tok::coloncolon);
1891   } else if (Style.Language == FormatStyle::LK_Proto) {
1892     if (Right.is(tok::period) &&
1893         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
1894                      Keywords.kw_repeated))
1895       return true;
1896     if (Right.is(tok::l_paren) &&
1897         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
1898       return true;
1899   } else if (Style.Language == FormatStyle::LK_JavaScript) {
1900     if (Left.isOneOf(Keywords.kw_var, TT_JsFatArrow))
1901       return true;
1902     if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
1903       return false;
1904     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
1905         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
1906       return false;
1907     if (Left.is(tok::ellipsis))
1908       return false;
1909     if (Left.is(TT_TemplateCloser) &&
1910         !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
1911                        Keywords.kw_implements, Keywords.kw_extends))
1912       // Type assertions ('<type>expr') are not followed by whitespace. Other
1913       // locations that should have whitespace following are identified by the
1914       // above set of follower tokens.
1915       return false;
1916   } else if (Style.Language == FormatStyle::LK_Java) {
1917     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
1918       return true;
1919     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
1920       return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
1921     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
1922                       tok::kw_protected) ||
1923          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
1924                       Keywords.kw_native)) &&
1925         Right.is(TT_TemplateOpener))
1926       return true;
1927   }
1928   if (Left.is(TT_ImplicitStringLiteral))
1929     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
1930   if (Line.Type == LT_ObjCMethodDecl) {
1931     if (Left.is(TT_ObjCMethodSpecifier))
1932       return true;
1933     if (Left.is(tok::r_paren) && Right.is(tok::identifier))
1934       // Don't space between ')' and <id>
1935       return false;
1936   }
1937   if (Line.Type == LT_ObjCProperty &&
1938       (Right.is(tok::equal) || Left.is(tok::equal)))
1939     return false;
1940
1941   if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
1942       Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
1943     return true;
1944   if (Left.is(tok::comma))
1945     return true;
1946   if (Right.is(tok::comma))
1947     return false;
1948   if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
1949     return true;
1950   if (Right.is(TT_OverloadedOperatorLParen))
1951     return false;
1952   if (Right.is(tok::colon)) {
1953     if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
1954         !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
1955       return false;
1956     if (Right.is(TT_ObjCMethodExpr))
1957       return false;
1958     if (Left.is(tok::question))
1959       return false;
1960     if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
1961       return false;
1962     if (Right.is(TT_DictLiteral))
1963       return Style.SpacesInContainerLiterals;
1964     return true;
1965   }
1966   if (Left.is(TT_UnaryOperator))
1967     return Right.is(TT_BinaryOperator);
1968
1969   // If the next token is a binary operator or a selector name, we have
1970   // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
1971   if (Left.is(TT_CastRParen))
1972     return Style.SpaceAfterCStyleCast ||
1973            Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
1974
1975   if (Left.is(tok::greater) && Right.is(tok::greater))
1976     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
1977            (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
1978   if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
1979       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
1980     return false;
1981   if (!Style.SpaceBeforeAssignmentOperators &&
1982       Right.getPrecedence() == prec::Assignment)
1983     return false;
1984   if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
1985     return (Left.is(TT_TemplateOpener) &&
1986             Style.Standard == FormatStyle::LS_Cpp03) ||
1987            !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
1988              Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
1989   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
1990     return Style.SpacesInAngles;
1991   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
1992       Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr))
1993     return true;
1994   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
1995       Right.isNot(TT_FunctionTypeLParen))
1996     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
1997   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
1998       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
1999     return false;
2000   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2001       Line.startsWith(tok::hash))
2002     return true;
2003   if (Right.is(TT_TrailingUnaryOperator))
2004     return false;
2005   if (Left.is(TT_RegexLiteral))
2006     return false;
2007   return spaceRequiredBetween(Line, Left, Right);
2008 }
2009
2010 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2011 static bool isAllmanBrace(const FormatToken &Tok) {
2012   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2013          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2014 }
2015
2016 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2017                                      const FormatToken &Right) {
2018   const FormatToken &Left = *Right.Previous;
2019   if (Right.NewlinesBefore > 1)
2020     return true;
2021
2022   if (Style.Language == FormatStyle::LK_JavaScript) {
2023     // FIXME: This might apply to other languages and token kinds.
2024     if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
2025         Left.Previous->is(tok::char_constant))
2026       return true;
2027     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2028         Left.Previous && Left.Previous->is(tok::equal) &&
2029         Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2030                             tok::kw_const) &&
2031         // kw_var is a pseudo-token that's a tok::identifier, so matches above.
2032         !Line.startsWith(Keywords.kw_var))
2033       // Object literals on the top level of a file are treated as "enum-style".
2034       // Each key/value pair is put on a separate line, instead of bin-packing.
2035       return true;
2036     if (Left.is(tok::l_brace) && Line.Level == 0 &&
2037         (Line.startsWith(tok::kw_enum) ||
2038          Line.startsWith(tok::kw_export, tok::kw_enum)))
2039       // JavaScript top-level enum key/value pairs are put on separate lines
2040       // instead of bin-packing.
2041       return true;
2042     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2043         !Left.Children.empty())
2044       // Support AllowShortFunctionsOnASingleLine for JavaScript.
2045       return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2046              (Left.NestingLevel == 0 && Line.Level == 0 &&
2047               Style.AllowShortFunctionsOnASingleLine ==
2048                   FormatStyle::SFS_Inline);
2049   } else if (Style.Language == FormatStyle::LK_Java) {
2050     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2051         Right.Next->is(tok::string_literal))
2052       return true;
2053   }
2054
2055   // If the last token before a '}' is a comma or a trailing comment, the
2056   // intention is to insert a line break after it in order to make shuffling
2057   // around entries easier.
2058   const FormatToken *BeforeClosingBrace = nullptr;
2059   if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2060       Left.BlockKind != BK_Block && Left.MatchingParen)
2061     BeforeClosingBrace = Left.MatchingParen->Previous;
2062   else if (Right.MatchingParen &&
2063            Right.MatchingParen->isOneOf(tok::l_brace,
2064                                         TT_ArrayInitializerLSquare))
2065     BeforeClosingBrace = &Left;
2066   if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2067                              BeforeClosingBrace->isTrailingComment()))
2068     return true;
2069
2070   if (Right.is(tok::comment))
2071     return Left.BlockKind != BK_BracedInit &&
2072            Left.isNot(TT_CtorInitializerColon) &&
2073            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2074   if (Left.isTrailingComment())
2075     return true;
2076   if (Left.isStringLiteral() &&
2077       (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2078     return true;
2079   if (Right.Previous->IsUnterminatedLiteral)
2080     return true;
2081   if (Right.is(tok::lessless) && Right.Next &&
2082       Right.Previous->is(tok::string_literal) &&
2083       Right.Next->is(tok::string_literal))
2084     return true;
2085   if (Right.Previous->ClosesTemplateDeclaration &&
2086       Right.Previous->MatchingParen &&
2087       Right.Previous->MatchingParen->NestingLevel == 0 &&
2088       Style.AlwaysBreakTemplateDeclarations)
2089     return true;
2090   if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2091       Style.BreakConstructorInitializersBeforeComma &&
2092       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2093     return true;
2094   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2095     // Raw string literals are special wrt. line breaks. The author has made a
2096     // deliberate choice and might have aligned the contents of the string
2097     // literal accordingly. Thus, we try keep existing line breaks.
2098     return Right.NewlinesBefore > 0;
2099   if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2100       Style.Language == FormatStyle::LK_Proto)
2101     // Don't put enums onto single lines in protocol buffers.
2102     return true;
2103   if (Right.is(TT_InlineASMBrace))
2104     return Right.HasUnescapedNewline;
2105   if (isAllmanBrace(Left) || isAllmanBrace(Right))
2106     return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
2107            Style.BreakBeforeBraces == FormatStyle::BS_GNU;
2108   if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2109       Right.is(TT_SelectorName))
2110     return true;
2111   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2112     return true;
2113
2114   if ((Style.Language == FormatStyle::LK_Java ||
2115        Style.Language == FormatStyle::LK_JavaScript) &&
2116       Left.is(TT_LeadingJavaAnnotation) &&
2117       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2118       Line.Last->is(tok::l_brace))
2119     return true;
2120
2121   return false;
2122 }
2123
2124 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2125                                     const FormatToken &Right) {
2126   const FormatToken &Left = *Right.Previous;
2127
2128   // Language-specific stuff.
2129   if (Style.Language == FormatStyle::LK_Java) {
2130     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2131                      Keywords.kw_implements))
2132       return false;
2133     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2134                       Keywords.kw_implements))
2135       return true;
2136   } else if (Style.Language == FormatStyle::LK_JavaScript) {
2137     if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2138       return false;
2139     if (Left.is(TT_JsTypeColon))
2140       return true;
2141   }
2142
2143   if (Left.is(tok::at))
2144     return false;
2145   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2146     return false;
2147   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2148     return !Right.is(tok::l_paren);
2149   if (Right.is(TT_PointerOrReference))
2150     return Line.IsMultiVariableDeclStmt ||
2151            (Style.PointerAlignment == FormatStyle::PAS_Right &&
2152             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2153   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2154       Right.is(tok::kw_operator))
2155     return true;
2156   if (Left.is(TT_PointerOrReference))
2157     return false;
2158   if (Right.isTrailingComment())
2159     // We rely on MustBreakBefore being set correctly here as we should not
2160     // change the "binding" behavior of a comment.
2161     // The first comment in a braced lists is always interpreted as belonging to
2162     // the first list element. Otherwise, it should be placed outside of the
2163     // list.
2164     return Left.BlockKind == BK_BracedInit;
2165   if (Left.is(tok::question) && Right.is(tok::colon))
2166     return false;
2167   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2168     return Style.BreakBeforeTernaryOperators;
2169   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2170     return !Style.BreakBeforeTernaryOperators;
2171   if (Right.is(TT_InheritanceColon))
2172     return true;
2173   if (Right.is(tok::colon) &&
2174       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2175     return false;
2176   if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2177     return true;
2178   if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2179                                     Right.Next->is(TT_ObjCMethodExpr)))
2180     return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2181   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2182     return true;
2183   if (Left.ClosesTemplateDeclaration)
2184     return true;
2185   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2186                     TT_OverloadedOperator))
2187     return false;
2188   if (Left.is(TT_RangeBasedForLoopColon))
2189     return true;
2190   if (Right.is(TT_RangeBasedForLoopColon))
2191     return false;
2192   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2193       Left.is(tok::kw_operator))
2194     return false;
2195   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2196       Line.Type == LT_VirtualFunctionDecl)
2197     return false;
2198   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2199     return false;
2200   if (Left.is(tok::l_paren) && Left.Previous &&
2201       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2202     return false;
2203   if (Right.is(TT_ImplicitStringLiteral))
2204     return false;
2205
2206   if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2207     return false;
2208
2209   // We only break before r_brace if there was a corresponding break before
2210   // the l_brace, which is tracked by BreakBeforeClosingBrace.
2211   if (Right.is(tok::r_brace))
2212     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2213
2214   // Allow breaking after a trailing annotation, e.g. after a method
2215   // declaration.
2216   if (Left.is(TT_TrailingAnnotation))
2217     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2218                           tok::less, tok::coloncolon);
2219
2220   if (Right.is(tok::kw___attribute))
2221     return true;
2222
2223   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2224     return true;
2225
2226   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2227     return true;
2228
2229   if (Left.is(TT_CtorInitializerComma) &&
2230       Style.BreakConstructorInitializersBeforeComma)
2231     return false;
2232   if (Right.is(TT_CtorInitializerComma) &&
2233       Style.BreakConstructorInitializersBeforeComma)
2234     return true;
2235   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2236       (Left.is(tok::less) && Right.is(tok::less)))
2237     return false;
2238   if (Right.is(TT_BinaryOperator) &&
2239       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2240       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2241        Right.getPrecedence() != prec::Assignment))
2242     return true;
2243   if (Left.is(TT_ArrayInitializerLSquare))
2244     return true;
2245   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2246     return true;
2247   if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2248       !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2249       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2250       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2251        Left.getPrecedence() == prec::Assignment))
2252     return true;
2253   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2254                       tok::kw_class, tok::kw_struct) ||
2255          Right.isMemberAccess() ||
2256          Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2257                        tok::colon, tok::l_square, tok::at) ||
2258          (Left.is(tok::r_paren) &&
2259           Right.isOneOf(tok::identifier, tok::kw_const)) ||
2260          (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2261 }
2262
2263 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2264   llvm::errs() << "AnnotatedTokens:\n";
2265   const FormatToken *Tok = Line.First;
2266   while (Tok) {
2267     llvm::errs() << " M=" << Tok->MustBreakBefore
2268                  << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
2269                  << " S=" << Tok->SpacesRequiredBefore
2270                  << " B=" << Tok->BlockParameterCount
2271                  << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2272                  << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2273                  << " FakeLParens=";
2274     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2275       llvm::errs() << Tok->FakeLParens[i] << "/";
2276     llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2277     if (!Tok->Next)
2278       assert(Tok == Line.Last);
2279     Tok = Tok->Next;
2280   }
2281   llvm::errs() << "----\n";
2282 }
2283
2284 } // namespace format
2285 } // namespace clang