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