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