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