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